Revert r53282. This was causing a miscompile on Linux. Also, the transformation
[oota-llvm.git] / lib / Transforms / Scalar / InstructionCombining.cpp
1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions.  This pass does not modify the CFG.  This pass is where
12 // algebraic simplification happens.
13 //
14 // This pass combines things like:
15 //    %Y = add i32 %X, 1
16 //    %Z = add i32 %Y, 1
17 // into:
18 //    %Z = add i32 %X, 2
19 //
20 // This is a simple worklist driven algorithm.
21 //
22 // This pass guarantees that the following canonicalizations are performed on
23 // the program:
24 //    1. If a binary operator has a constant operand, it is moved to the RHS
25 //    2. Bitwise operators with constant operands are always grouped so that
26 //       shifts are performed first, then or's, then and's, then xor's.
27 //    3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All cmp instructions on boolean values are replaced with logical ops
29 //    5. add X, X is represented as (X*2) => (X << 1)
30 //    6. Multiplies with a power-of-two constant argument are transformed into
31 //       shifts.
32 //   ... etc.
33 //
34 //===----------------------------------------------------------------------===//
35
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/Analysis/ConstantFolding.h"
43 #include "llvm/Analysis/ValueTracking.h"
44 #include "llvm/Target/TargetData.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Support/CallSite.h"
48 #include "llvm/Support/ConstantRange.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/GetElementPtrTypeIterator.h"
51 #include "llvm/Support/InstVisitor.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/PatternMatch.h"
54 #include "llvm/Support/Compiler.h"
55 #include "llvm/ADT/DenseMap.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/SmallPtrSet.h"
58 #include "llvm/ADT/Statistic.h"
59 #include "llvm/ADT/STLExtras.h"
60 #include <algorithm>
61 #include <climits>
62 #include <sstream>
63 using namespace llvm;
64 using namespace llvm::PatternMatch;
65
66 STATISTIC(NumCombined , "Number of insts combined");
67 STATISTIC(NumConstProp, "Number of constant folds");
68 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70 STATISTIC(NumSunkInst , "Number of instructions sunk");
71
72 namespace {
73   class VISIBILITY_HIDDEN InstCombiner
74     : public FunctionPass,
75       public InstVisitor<InstCombiner, Instruction*> {
76     // Worklist of all of the instructions that need to be simplified.
77     std::vector<Instruction*> Worklist;
78     DenseMap<Instruction*, unsigned> WorklistMap;
79     TargetData *TD;
80     bool MustPreserveLCSSA;
81   public:
82     static char ID; // Pass identification, replacement for typeid
83     InstCombiner() : FunctionPass((intptr_t)&ID) {}
84
85     /// AddToWorkList - Add the specified instruction to the worklist if it
86     /// isn't already in it.
87     void AddToWorkList(Instruction *I) {
88       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).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         else if (LHSKnownOne[BitWidth-1])
1270           LHSKnownOne |= ~LowBits;
1271
1272         KnownZero |= LHSKnownZero & DemandedMask;
1273         KnownOne |= LHSKnownOne & DemandedMask;
1274
1275         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1276       }
1277     }
1278     break;
1279   case Instruction::URem: {
1280     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1281     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1282     if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1283                              KnownZero2, KnownOne2, Depth+1))
1284       return true;
1285
1286     uint32_t Leaders = KnownZero2.countLeadingOnes();
1287     if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1288                              KnownZero2, KnownOne2, Depth+1))
1289       return true;
1290
1291     Leaders = std::max(Leaders,
1292                        KnownZero2.countLeadingOnes());
1293     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1294     break;
1295   }
1296   case Instruction::Call:
1297     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1298       switch (II->getIntrinsicID()) {
1299       default: break;
1300       case Intrinsic::bswap: {
1301         // If the only bits demanded come from one byte of the bswap result,
1302         // just shift the input byte into position to eliminate the bswap.
1303         unsigned NLZ = DemandedMask.countLeadingZeros();
1304         unsigned NTZ = DemandedMask.countTrailingZeros();
1305           
1306         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1307         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1308         // have 14 leading zeros, round to 8.
1309         NLZ &= ~7;
1310         NTZ &= ~7;
1311         // If we need exactly one byte, we can do this transformation.
1312         if (BitWidth-NLZ-NTZ == 8) {
1313           unsigned ResultBit = NTZ;
1314           unsigned InputBit = BitWidth-NTZ-8;
1315           
1316           // Replace this with either a left or right shift to get the byte into
1317           // the right place.
1318           Instruction *NewVal;
1319           if (InputBit > ResultBit)
1320             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1321                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1322           else
1323             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1324                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1325           NewVal->takeName(I);
1326           InsertNewInstBefore(NewVal, *I);
1327           return UpdateValueUsesWith(I, NewVal);
1328         }
1329           
1330         // TODO: Could compute known zero/one bits based on the input.
1331         break;
1332       }
1333       }
1334     }
1335     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1336     break;
1337   }
1338   
1339   // If the client is only demanding bits that we know, return the known
1340   // constant.
1341   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1342     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1343   return false;
1344 }
1345
1346
1347 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1348 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1349 /// actually used by the caller.  This method analyzes which elements of the
1350 /// operand are undef and returns that information in UndefElts.
1351 ///
1352 /// If the information about demanded elements can be used to simplify the
1353 /// operation, the operation is simplified, then the resultant value is
1354 /// returned.  This returns null if no change was made.
1355 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1356                                                 uint64_t &UndefElts,
1357                                                 unsigned Depth) {
1358   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1359   assert(VWidth <= 64 && "Vector too wide to analyze!");
1360   uint64_t EltMask = ~0ULL >> (64-VWidth);
1361   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1362          "Invalid DemandedElts!");
1363
1364   if (isa<UndefValue>(V)) {
1365     // If the entire vector is undefined, just return this info.
1366     UndefElts = EltMask;
1367     return 0;
1368   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1369     UndefElts = EltMask;
1370     return UndefValue::get(V->getType());
1371   }
1372   
1373   UndefElts = 0;
1374   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1375     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1376     Constant *Undef = UndefValue::get(EltTy);
1377
1378     std::vector<Constant*> Elts;
1379     for (unsigned i = 0; i != VWidth; ++i)
1380       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1381         Elts.push_back(Undef);
1382         UndefElts |= (1ULL << i);
1383       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1384         Elts.push_back(Undef);
1385         UndefElts |= (1ULL << i);
1386       } else {                               // Otherwise, defined.
1387         Elts.push_back(CP->getOperand(i));
1388       }
1389         
1390     // If we changed the constant, return it.
1391     Constant *NewCP = ConstantVector::get(Elts);
1392     return NewCP != CP ? NewCP : 0;
1393   } else if (isa<ConstantAggregateZero>(V)) {
1394     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1395     // set to undef.
1396     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1397     Constant *Zero = Constant::getNullValue(EltTy);
1398     Constant *Undef = UndefValue::get(EltTy);
1399     std::vector<Constant*> Elts;
1400     for (unsigned i = 0; i != VWidth; ++i)
1401       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1402     UndefElts = DemandedElts ^ EltMask;
1403     return ConstantVector::get(Elts);
1404   }
1405   
1406   if (!V->hasOneUse()) {    // Other users may use these bits.
1407     if (Depth != 0) {       // Not at the root.
1408       // TODO: Just compute the UndefElts information recursively.
1409       return false;
1410     }
1411     return false;
1412   } else if (Depth == 10) {        // Limit search depth.
1413     return false;
1414   }
1415   
1416   Instruction *I = dyn_cast<Instruction>(V);
1417   if (!I) return false;        // Only analyze instructions.
1418   
1419   bool MadeChange = false;
1420   uint64_t UndefElts2;
1421   Value *TmpV;
1422   switch (I->getOpcode()) {
1423   default: break;
1424     
1425   case Instruction::InsertElement: {
1426     // If this is a variable index, we don't know which element it overwrites.
1427     // demand exactly the same input as we produce.
1428     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1429     if (Idx == 0) {
1430       // Note that we can't propagate undef elt info, because we don't know
1431       // which elt is getting updated.
1432       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1433                                         UndefElts2, Depth+1);
1434       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1435       break;
1436     }
1437     
1438     // If this is inserting an element that isn't demanded, remove this
1439     // insertelement.
1440     unsigned IdxNo = Idx->getZExtValue();
1441     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1442       return AddSoonDeadInstToWorklist(*I, 0);
1443     
1444     // Otherwise, the element inserted overwrites whatever was there, so the
1445     // input demanded set is simpler than the output set.
1446     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1447                                       DemandedElts & ~(1ULL << IdxNo),
1448                                       UndefElts, Depth+1);
1449     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1450
1451     // The inserted element is defined.
1452     UndefElts |= 1ULL << IdxNo;
1453     break;
1454   }
1455   case Instruction::BitCast: {
1456     // Vector->vector casts only.
1457     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1458     if (!VTy) break;
1459     unsigned InVWidth = VTy->getNumElements();
1460     uint64_t InputDemandedElts = 0;
1461     unsigned Ratio;
1462
1463     if (VWidth == InVWidth) {
1464       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1465       // elements as are demanded of us.
1466       Ratio = 1;
1467       InputDemandedElts = DemandedElts;
1468     } else if (VWidth > InVWidth) {
1469       // Untested so far.
1470       break;
1471       
1472       // If there are more elements in the result than there are in the source,
1473       // then an input element is live if any of the corresponding output
1474       // elements are live.
1475       Ratio = VWidth/InVWidth;
1476       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1477         if (DemandedElts & (1ULL << OutIdx))
1478           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1479       }
1480     } else {
1481       // Untested so far.
1482       break;
1483       
1484       // If there are more elements in the source than there are in the result,
1485       // then an input element is live if the corresponding output element is
1486       // live.
1487       Ratio = InVWidth/VWidth;
1488       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1489         if (DemandedElts & (1ULL << InIdx/Ratio))
1490           InputDemandedElts |= 1ULL << InIdx;
1491     }
1492     
1493     // div/rem demand all inputs, because they don't want divide by zero.
1494     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1495                                       UndefElts2, Depth+1);
1496     if (TmpV) {
1497       I->setOperand(0, TmpV);
1498       MadeChange = true;
1499     }
1500     
1501     UndefElts = UndefElts2;
1502     if (VWidth > InVWidth) {
1503       assert(0 && "Unimp");
1504       // If there are more elements in the result than there are in the source,
1505       // then an output element is undef if the corresponding input element is
1506       // undef.
1507       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1508         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1509           UndefElts |= 1ULL << OutIdx;
1510     } else if (VWidth < InVWidth) {
1511       assert(0 && "Unimp");
1512       // If there are more elements in the source than there are in the result,
1513       // then a result element is undef if all of the corresponding input
1514       // elements are undef.
1515       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1516       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1517         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1518           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1519     }
1520     break;
1521   }
1522   case Instruction::And:
1523   case Instruction::Or:
1524   case Instruction::Xor:
1525   case Instruction::Add:
1526   case Instruction::Sub:
1527   case Instruction::Mul:
1528     // div/rem demand all inputs, because they don't want divide by zero.
1529     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1530                                       UndefElts, Depth+1);
1531     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1532     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1533                                       UndefElts2, Depth+1);
1534     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1535       
1536     // Output elements are undefined if both are undefined.  Consider things
1537     // like undef&0.  The result is known zero, not undef.
1538     UndefElts &= UndefElts2;
1539     break;
1540     
1541   case Instruction::Call: {
1542     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1543     if (!II) break;
1544     switch (II->getIntrinsicID()) {
1545     default: break;
1546       
1547     // Binary vector operations that work column-wise.  A dest element is a
1548     // function of the corresponding input elements from the two inputs.
1549     case Intrinsic::x86_sse_sub_ss:
1550     case Intrinsic::x86_sse_mul_ss:
1551     case Intrinsic::x86_sse_min_ss:
1552     case Intrinsic::x86_sse_max_ss:
1553     case Intrinsic::x86_sse2_sub_sd:
1554     case Intrinsic::x86_sse2_mul_sd:
1555     case Intrinsic::x86_sse2_min_sd:
1556     case Intrinsic::x86_sse2_max_sd:
1557       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1558                                         UndefElts, Depth+1);
1559       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1560       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1561                                         UndefElts2, Depth+1);
1562       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1563
1564       // If only the low elt is demanded and this is a scalarizable intrinsic,
1565       // scalarize it now.
1566       if (DemandedElts == 1) {
1567         switch (II->getIntrinsicID()) {
1568         default: break;
1569         case Intrinsic::x86_sse_sub_ss:
1570         case Intrinsic::x86_sse_mul_ss:
1571         case Intrinsic::x86_sse2_sub_sd:
1572         case Intrinsic::x86_sse2_mul_sd:
1573           // TODO: Lower MIN/MAX/ABS/etc
1574           Value *LHS = II->getOperand(1);
1575           Value *RHS = II->getOperand(2);
1576           // Extract the element as scalars.
1577           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1578           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1579           
1580           switch (II->getIntrinsicID()) {
1581           default: assert(0 && "Case stmts out of sync!");
1582           case Intrinsic::x86_sse_sub_ss:
1583           case Intrinsic::x86_sse2_sub_sd:
1584             TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
1585                                                         II->getName()), *II);
1586             break;
1587           case Intrinsic::x86_sse_mul_ss:
1588           case Intrinsic::x86_sse2_mul_sd:
1589             TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
1590                                                          II->getName()), *II);
1591             break;
1592           }
1593           
1594           Instruction *New =
1595             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1596                                       II->getName());
1597           InsertNewInstBefore(New, *II);
1598           AddSoonDeadInstToWorklist(*II, 0);
1599           return New;
1600         }            
1601       }
1602         
1603       // Output elements are undefined if both are undefined.  Consider things
1604       // like undef&0.  The result is known zero, not undef.
1605       UndefElts &= UndefElts2;
1606       break;
1607     }
1608     break;
1609   }
1610   }
1611   return MadeChange ? I : 0;
1612 }
1613
1614
1615 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1616 /// function is designed to check a chain of associative operators for a
1617 /// potential to apply a certain optimization.  Since the optimization may be
1618 /// applicable if the expression was reassociated, this checks the chain, then
1619 /// reassociates the expression as necessary to expose the optimization
1620 /// opportunity.  This makes use of a special Functor, which must define
1621 /// 'shouldApply' and 'apply' methods.
1622 ///
1623 template<typename Functor>
1624 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1625   unsigned Opcode = Root.getOpcode();
1626   Value *LHS = Root.getOperand(0);
1627
1628   // Quick check, see if the immediate LHS matches...
1629   if (F.shouldApply(LHS))
1630     return F.apply(Root);
1631
1632   // Otherwise, if the LHS is not of the same opcode as the root, return.
1633   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1634   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1635     // Should we apply this transform to the RHS?
1636     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1637
1638     // If not to the RHS, check to see if we should apply to the LHS...
1639     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1640       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1641       ShouldApply = true;
1642     }
1643
1644     // If the functor wants to apply the optimization to the RHS of LHSI,
1645     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1646     if (ShouldApply) {
1647       // Now all of the instructions are in the current basic block, go ahead
1648       // and perform the reassociation.
1649       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1650
1651       // First move the selected RHS to the LHS of the root...
1652       Root.setOperand(0, LHSI->getOperand(1));
1653
1654       // Make what used to be the LHS of the root be the user of the root...
1655       Value *ExtraOperand = TmpLHSI->getOperand(1);
1656       if (&Root == TmpLHSI) {
1657         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1658         return 0;
1659       }
1660       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1661       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1662       BasicBlock::iterator ARI = &Root; ++ARI;
1663       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1664       ARI = Root;
1665
1666       // Now propagate the ExtraOperand down the chain of instructions until we
1667       // get to LHSI.
1668       while (TmpLHSI != LHSI) {
1669         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1670         // Move the instruction to immediately before the chain we are
1671         // constructing to avoid breaking dominance properties.
1672         NextLHSI->moveBefore(ARI);
1673         ARI = NextLHSI;
1674
1675         Value *NextOp = NextLHSI->getOperand(1);
1676         NextLHSI->setOperand(1, ExtraOperand);
1677         TmpLHSI = NextLHSI;
1678         ExtraOperand = NextOp;
1679       }
1680
1681       // Now that the instructions are reassociated, have the functor perform
1682       // the transformation...
1683       return F.apply(Root);
1684     }
1685
1686     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1687   }
1688   return 0;
1689 }
1690
1691 namespace {
1692
1693 // AddRHS - Implements: X + X --> X << 1
1694 struct AddRHS {
1695   Value *RHS;
1696   AddRHS(Value *rhs) : RHS(rhs) {}
1697   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1698   Instruction *apply(BinaryOperator &Add) const {
1699     return BinaryOperator::CreateShl(Add.getOperand(0),
1700                                      ConstantInt::get(Add.getType(), 1));
1701   }
1702 };
1703
1704 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1705 //                 iff C1&C2 == 0
1706 struct AddMaskingAnd {
1707   Constant *C2;
1708   AddMaskingAnd(Constant *c) : C2(c) {}
1709   bool shouldApply(Value *LHS) const {
1710     ConstantInt *C1;
1711     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1712            ConstantExpr::getAnd(C1, C2)->isNullValue();
1713   }
1714   Instruction *apply(BinaryOperator &Add) const {
1715     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1716   }
1717 };
1718
1719 }
1720
1721 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1722                                              InstCombiner *IC) {
1723   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1724     if (Constant *SOC = dyn_cast<Constant>(SO))
1725       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1726
1727     return IC->InsertNewInstBefore(CastInst::Create(
1728           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1729   }
1730
1731   // Figure out if the constant is the left or the right argument.
1732   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1733   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1734
1735   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1736     if (ConstIsRHS)
1737       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1738     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1739   }
1740
1741   Value *Op0 = SO, *Op1 = ConstOperand;
1742   if (!ConstIsRHS)
1743     std::swap(Op0, Op1);
1744   Instruction *New;
1745   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1746     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1747   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1748     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1749                           SO->getName()+".cmp");
1750   else {
1751     assert(0 && "Unknown binary instruction type!");
1752     abort();
1753   }
1754   return IC->InsertNewInstBefore(New, I);
1755 }
1756
1757 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1758 // constant as the other operand, try to fold the binary operator into the
1759 // select arguments.  This also works for Cast instructions, which obviously do
1760 // not have a second operand.
1761 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1762                                      InstCombiner *IC) {
1763   // Don't modify shared select instructions
1764   if (!SI->hasOneUse()) return 0;
1765   Value *TV = SI->getOperand(1);
1766   Value *FV = SI->getOperand(2);
1767
1768   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1769     // Bool selects with constant operands can be folded to logical ops.
1770     if (SI->getType() == Type::Int1Ty) return 0;
1771
1772     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1773     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1774
1775     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1776                               SelectFalseVal);
1777   }
1778   return 0;
1779 }
1780
1781
1782 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1783 /// node as operand #0, see if we can fold the instruction into the PHI (which
1784 /// is only possible if all operands to the PHI are constants).
1785 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1786   PHINode *PN = cast<PHINode>(I.getOperand(0));
1787   unsigned NumPHIValues = PN->getNumIncomingValues();
1788   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1789
1790   // Check to see if all of the operands of the PHI are constants.  If there is
1791   // one non-constant value, remember the BB it is.  If there is more than one
1792   // or if *it* is a PHI, bail out.
1793   BasicBlock *NonConstBB = 0;
1794   for (unsigned i = 0; i != NumPHIValues; ++i)
1795     if (!isa<Constant>(PN->getIncomingValue(i))) {
1796       if (NonConstBB) return 0;  // More than one non-const value.
1797       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1798       NonConstBB = PN->getIncomingBlock(i);
1799       
1800       // If the incoming non-constant value is in I's block, we have an infinite
1801       // loop.
1802       if (NonConstBB == I.getParent())
1803         return 0;
1804     }
1805   
1806   // If there is exactly one non-constant value, we can insert a copy of the
1807   // operation in that block.  However, if this is a critical edge, we would be
1808   // inserting the computation one some other paths (e.g. inside a loop).  Only
1809   // do this if the pred block is unconditionally branching into the phi block.
1810   if (NonConstBB) {
1811     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1812     if (!BI || !BI->isUnconditional()) return 0;
1813   }
1814
1815   // Okay, we can do the transformation: create the new PHI node.
1816   PHINode *NewPN = PHINode::Create(I.getType(), "");
1817   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1818   InsertNewInstBefore(NewPN, *PN);
1819   NewPN->takeName(PN);
1820
1821   // Next, add all of the operands to the PHI.
1822   if (I.getNumOperands() == 2) {
1823     Constant *C = cast<Constant>(I.getOperand(1));
1824     for (unsigned i = 0; i != NumPHIValues; ++i) {
1825       Value *InV = 0;
1826       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1827         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1828           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1829         else
1830           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1831       } else {
1832         assert(PN->getIncomingBlock(i) == NonConstBB);
1833         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1834           InV = BinaryOperator::Create(BO->getOpcode(),
1835                                        PN->getIncomingValue(i), C, "phitmp",
1836                                        NonConstBB->getTerminator());
1837         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1838           InV = CmpInst::Create(CI->getOpcode(), 
1839                                 CI->getPredicate(),
1840                                 PN->getIncomingValue(i), C, "phitmp",
1841                                 NonConstBB->getTerminator());
1842         else
1843           assert(0 && "Unknown binop!");
1844         
1845         AddToWorkList(cast<Instruction>(InV));
1846       }
1847       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1848     }
1849   } else { 
1850     CastInst *CI = cast<CastInst>(&I);
1851     const Type *RetTy = CI->getType();
1852     for (unsigned i = 0; i != NumPHIValues; ++i) {
1853       Value *InV;
1854       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1855         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1856       } else {
1857         assert(PN->getIncomingBlock(i) == NonConstBB);
1858         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
1859                                I.getType(), "phitmp", 
1860                                NonConstBB->getTerminator());
1861         AddToWorkList(cast<Instruction>(InV));
1862       }
1863       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1864     }
1865   }
1866   return ReplaceInstUsesWith(I, NewPN);
1867 }
1868
1869
1870 /// WillNotOverflowSignedAdd - Return true if we can prove that:
1871 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
1872 /// This basically requires proving that the add in the original type would not
1873 /// overflow to change the sign bit or have a carry out.
1874 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1875   // There are different heuristics we can use for this.  Here are some simple
1876   // ones.
1877   
1878   // Add has the property that adding any two 2's complement numbers can only 
1879   // have one carry bit which can change a sign.  As such, if LHS and RHS each
1880   // have at least two sign bits, we know that the addition of the two values will
1881   // sign extend fine.
1882   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1883     return true;
1884   
1885   
1886   // If one of the operands only has one non-zero bit, and if the other operand
1887   // has a known-zero bit in a more significant place than it (not including the
1888   // sign bit) the ripple may go up to and fill the zero, but won't change the
1889   // sign.  For example, (X & ~4) + 1.
1890   
1891   // TODO: Implement.
1892   
1893   return false;
1894 }
1895
1896
1897 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1898   bool Changed = SimplifyCommutative(I);
1899   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1900
1901   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1902     // X + undef -> undef
1903     if (isa<UndefValue>(RHS))
1904       return ReplaceInstUsesWith(I, RHS);
1905
1906     // X + 0 --> X
1907     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1908       if (RHSC->isNullValue())
1909         return ReplaceInstUsesWith(I, LHS);
1910     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1911       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1912                               (I.getType())->getValueAPF()))
1913         return ReplaceInstUsesWith(I, LHS);
1914     }
1915
1916     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1917       // X + (signbit) --> X ^ signbit
1918       const APInt& Val = CI->getValue();
1919       uint32_t BitWidth = Val.getBitWidth();
1920       if (Val == APInt::getSignBit(BitWidth))
1921         return BinaryOperator::CreateXor(LHS, RHS);
1922       
1923       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1924       // (X & 254)+1 -> (X&254)|1
1925       if (!isa<VectorType>(I.getType())) {
1926         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1927         if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1928                                  KnownZero, KnownOne))
1929           return &I;
1930       }
1931     }
1932
1933     if (isa<PHINode>(LHS))
1934       if (Instruction *NV = FoldOpIntoPhi(I))
1935         return NV;
1936     
1937     ConstantInt *XorRHS = 0;
1938     Value *XorLHS = 0;
1939     if (isa<ConstantInt>(RHSC) &&
1940         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1941       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
1942       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
1943       
1944       uint32_t Size = TySizeBits / 2;
1945       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1946       APInt CFF80Val(-C0080Val);
1947       do {
1948         if (TySizeBits > Size) {
1949           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1950           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1951           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1952               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
1953             // This is a sign extend if the top bits are known zero.
1954             if (!MaskedValueIsZero(XorLHS, 
1955                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
1956               Size = 0;  // Not a sign ext, but can't be any others either.
1957             break;
1958           }
1959         }
1960         Size >>= 1;
1961         C0080Val = APIntOps::lshr(C0080Val, Size);
1962         CFF80Val = APIntOps::ashr(CFF80Val, Size);
1963       } while (Size >= 1);
1964       
1965       // FIXME: This shouldn't be necessary. When the backends can handle types
1966       // with funny bit widths then this switch statement should be removed. It
1967       // is just here to get the size of the "middle" type back up to something
1968       // that the back ends can handle.
1969       const Type *MiddleType = 0;
1970       switch (Size) {
1971         default: break;
1972         case 32: MiddleType = Type::Int32Ty; break;
1973         case 16: MiddleType = Type::Int16Ty; break;
1974         case  8: MiddleType = Type::Int8Ty; break;
1975       }
1976       if (MiddleType) {
1977         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
1978         InsertNewInstBefore(NewTrunc, I);
1979         return new SExtInst(NewTrunc, I.getType(), I.getName());
1980       }
1981     }
1982   }
1983
1984   if (I.getType() == Type::Int1Ty)
1985     return BinaryOperator::CreateXor(LHS, RHS);
1986
1987   // X + X --> X << 1
1988   if (I.getType()->isInteger()) {
1989     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1990
1991     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1992       if (RHSI->getOpcode() == Instruction::Sub)
1993         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
1994           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1995     }
1996     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1997       if (LHSI->getOpcode() == Instruction::Sub)
1998         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
1999           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2000     }
2001   }
2002
2003   // -A + B  -->  B - A
2004   // -A + -B  -->  -(A + B)
2005   if (Value *LHSV = dyn_castNegVal(LHS)) {
2006     if (LHS->getType()->isIntOrIntVector()) {
2007       if (Value *RHSV = dyn_castNegVal(RHS)) {
2008         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2009         InsertNewInstBefore(NewAdd, I);
2010         return BinaryOperator::CreateNeg(NewAdd);
2011       }
2012     }
2013     
2014     return BinaryOperator::CreateSub(RHS, LHSV);
2015   }
2016
2017   // A + -B  -->  A - B
2018   if (!isa<Constant>(RHS))
2019     if (Value *V = dyn_castNegVal(RHS))
2020       return BinaryOperator::CreateSub(LHS, V);
2021
2022
2023   ConstantInt *C2;
2024   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2025     if (X == RHS)   // X*C + X --> X * (C+1)
2026       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2027
2028     // X*C1 + X*C2 --> X * (C1+C2)
2029     ConstantInt *C1;
2030     if (X == dyn_castFoldableMul(RHS, C1))
2031       return BinaryOperator::CreateMul(X, Add(C1, C2));
2032   }
2033
2034   // X + X*C --> X * (C+1)
2035   if (dyn_castFoldableMul(RHS, C2) == LHS)
2036     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2037
2038   // X + ~X --> -1   since   ~X = -X-1
2039   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2040     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2041   
2042
2043   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2044   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2045     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2046       return R;
2047   
2048   // A+B --> A|B iff A and B have no bits set in common.
2049   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2050     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2051     APInt LHSKnownOne(IT->getBitWidth(), 0);
2052     APInt LHSKnownZero(IT->getBitWidth(), 0);
2053     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2054     if (LHSKnownZero != 0) {
2055       APInt RHSKnownOne(IT->getBitWidth(), 0);
2056       APInt RHSKnownZero(IT->getBitWidth(), 0);
2057       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2058       
2059       // No bits in common -> bitwise or.
2060       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2061         return BinaryOperator::CreateOr(LHS, RHS);
2062     }
2063   }
2064
2065   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2066   if (I.getType()->isIntOrIntVector()) {
2067     Value *W, *X, *Y, *Z;
2068     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2069         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2070       if (W != Y) {
2071         if (W == Z) {
2072           std::swap(Y, Z);
2073         } else if (Y == X) {
2074           std::swap(W, X);
2075         } else if (X == Z) {
2076           std::swap(Y, Z);
2077           std::swap(W, X);
2078         }
2079       }
2080
2081       if (W == Y) {
2082         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2083                                                             LHS->getName()), I);
2084         return BinaryOperator::CreateMul(W, NewAdd);
2085       }
2086     }
2087   }
2088
2089   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2090     Value *X = 0;
2091     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2092       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2093
2094     // (X & FF00) + xx00  -> (X+xx00) & FF00
2095     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2096       Constant *Anded = And(CRHS, C2);
2097       if (Anded == CRHS) {
2098         // See if all bits from the first bit set in the Add RHS up are included
2099         // in the mask.  First, get the rightmost bit.
2100         const APInt& AddRHSV = CRHS->getValue();
2101
2102         // Form a mask of all bits from the lowest bit added through the top.
2103         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2104
2105         // See if the and mask includes all of these bits.
2106         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2107
2108         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2109           // Okay, the xform is safe.  Insert the new add pronto.
2110           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2111                                                             LHS->getName()), I);
2112           return BinaryOperator::CreateAnd(NewAdd, C2);
2113         }
2114       }
2115     }
2116
2117     // Try to fold constant add into select arguments.
2118     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2119       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2120         return R;
2121   }
2122
2123   // add (cast *A to intptrtype) B -> 
2124   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2125   {
2126     CastInst *CI = dyn_cast<CastInst>(LHS);
2127     Value *Other = RHS;
2128     if (!CI) {
2129       CI = dyn_cast<CastInst>(RHS);
2130       Other = LHS;
2131     }
2132     if (CI && CI->getType()->isSized() && 
2133         (CI->getType()->getPrimitiveSizeInBits() == 
2134          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2135         && isa<PointerType>(CI->getOperand(0)->getType())) {
2136       unsigned AS =
2137         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2138       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2139                                       PointerType::get(Type::Int8Ty, AS), I);
2140       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2141       return new PtrToIntInst(I2, CI->getType());
2142     }
2143   }
2144   
2145   // add (select X 0 (sub n A)) A  -->  select X A n
2146   {
2147     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2148     Value *Other = RHS;
2149     if (!SI) {
2150       SI = dyn_cast<SelectInst>(RHS);
2151       Other = LHS;
2152     }
2153     if (SI && SI->hasOneUse()) {
2154       Value *TV = SI->getTrueValue();
2155       Value *FV = SI->getFalseValue();
2156       Value *A, *N;
2157
2158       // Can we fold the add into the argument of the select?
2159       // We check both true and false select arguments for a matching subtract.
2160       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2161           A == Other)  // Fold the add into the true select value.
2162         return SelectInst::Create(SI->getCondition(), N, A);
2163       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) && 
2164           A == Other)  // Fold the add into the false select value.
2165         return SelectInst::Create(SI->getCondition(), A, N);
2166     }
2167   }
2168   
2169   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2170   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2171     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2172       return ReplaceInstUsesWith(I, LHS);
2173
2174   // Check for (add (sext x), y), see if we can merge this into an
2175   // integer add followed by a sext.
2176   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2177     // (add (sext x), cst) --> (sext (add x, cst'))
2178     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2179       Constant *CI = 
2180         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2181       if (LHSConv->hasOneUse() &&
2182           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2183           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2184         // Insert the new, smaller add.
2185         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2186                                                         CI, "addconv");
2187         InsertNewInstBefore(NewAdd, I);
2188         return new SExtInst(NewAdd, I.getType());
2189       }
2190     }
2191     
2192     // (add (sext x), (sext y)) --> (sext (add int x, y))
2193     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2194       // Only do this if x/y have the same type, if at last one of them has a
2195       // single use (so we don't increase the number of sexts), and if the
2196       // integer add will not overflow.
2197       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2198           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2199           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2200                                    RHSConv->getOperand(0))) {
2201         // Insert the new integer add.
2202         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2203                                                         RHSConv->getOperand(0),
2204                                                         "addconv");
2205         InsertNewInstBefore(NewAdd, I);
2206         return new SExtInst(NewAdd, I.getType());
2207       }
2208     }
2209   }
2210   
2211   // Check for (add double (sitofp x), y), see if we can merge this into an
2212   // integer add followed by a promotion.
2213   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2214     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2215     // ... if the constant fits in the integer value.  This is useful for things
2216     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2217     // requires a constant pool load, and generally allows the add to be better
2218     // instcombined.
2219     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2220       Constant *CI = 
2221       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2222       if (LHSConv->hasOneUse() &&
2223           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2224           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2225         // Insert the new integer add.
2226         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2227                                                         CI, "addconv");
2228         InsertNewInstBefore(NewAdd, I);
2229         return new SIToFPInst(NewAdd, I.getType());
2230       }
2231     }
2232     
2233     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2234     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2235       // Only do this if x/y have the same type, if at last one of them has a
2236       // single use (so we don't increase the number of int->fp conversions),
2237       // and if the integer add will not overflow.
2238       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2239           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2240           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2241                                    RHSConv->getOperand(0))) {
2242         // Insert the new integer add.
2243         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2244                                                         RHSConv->getOperand(0),
2245                                                         "addconv");
2246         InsertNewInstBefore(NewAdd, I);
2247         return new SIToFPInst(NewAdd, I.getType());
2248       }
2249     }
2250   }
2251   
2252   return Changed ? &I : 0;
2253 }
2254
2255 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2256   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2257
2258   if (Op0 == Op1 &&                        // sub X, X  -> 0
2259       !I.getType()->isFPOrFPVector())
2260     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2261
2262   // If this is a 'B = x-(-A)', change to B = x+A...
2263   if (Value *V = dyn_castNegVal(Op1))
2264     return BinaryOperator::CreateAdd(Op0, V);
2265
2266   if (isa<UndefValue>(Op0))
2267     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2268   if (isa<UndefValue>(Op1))
2269     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2270
2271   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2272     // Replace (-1 - A) with (~A)...
2273     if (C->isAllOnesValue())
2274       return BinaryOperator::CreateNot(Op1);
2275
2276     // C - ~X == X + (1+C)
2277     Value *X = 0;
2278     if (match(Op1, m_Not(m_Value(X))))
2279       return BinaryOperator::CreateAdd(X, AddOne(C));
2280
2281     // -(X >>u 31) -> (X >>s 31)
2282     // -(X >>s 31) -> (X >>u 31)
2283     if (C->isZero()) {
2284       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2285         if (SI->getOpcode() == Instruction::LShr) {
2286           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2287             // Check to see if we are shifting out everything but the sign bit.
2288             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2289                 SI->getType()->getPrimitiveSizeInBits()-1) {
2290               // Ok, the transformation is safe.  Insert AShr.
2291               return BinaryOperator::Create(Instruction::AShr, 
2292                                           SI->getOperand(0), CU, SI->getName());
2293             }
2294           }
2295         }
2296         else if (SI->getOpcode() == Instruction::AShr) {
2297           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2298             // Check to see if we are shifting out everything but the sign bit.
2299             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2300                 SI->getType()->getPrimitiveSizeInBits()-1) {
2301               // Ok, the transformation is safe.  Insert LShr. 
2302               return BinaryOperator::CreateLShr(
2303                                           SI->getOperand(0), CU, SI->getName());
2304             }
2305           }
2306         }
2307       }
2308     }
2309
2310     // Try to fold constant sub into select arguments.
2311     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2312       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2313         return R;
2314
2315     if (isa<PHINode>(Op0))
2316       if (Instruction *NV = FoldOpIntoPhi(I))
2317         return NV;
2318   }
2319
2320   if (I.getType() == Type::Int1Ty)
2321     return BinaryOperator::CreateXor(Op0, Op1);
2322
2323   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2324     if (Op1I->getOpcode() == Instruction::Add &&
2325         !Op0->getType()->isFPOrFPVector()) {
2326       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2327         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2328       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2329         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2330       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2331         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2332           // C1-(X+C2) --> (C1-C2)-X
2333           return BinaryOperator::CreateSub(Subtract(CI1, CI2), 
2334                                            Op1I->getOperand(0));
2335       }
2336     }
2337
2338     if (Op1I->hasOneUse()) {
2339       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2340       // is not used by anyone else...
2341       //
2342       if (Op1I->getOpcode() == Instruction::Sub &&
2343           !Op1I->getType()->isFPOrFPVector()) {
2344         // Swap the two operands of the subexpr...
2345         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2346         Op1I->setOperand(0, IIOp1);
2347         Op1I->setOperand(1, IIOp0);
2348
2349         // Create the new top level add instruction...
2350         return BinaryOperator::CreateAdd(Op0, Op1);
2351       }
2352
2353       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2354       //
2355       if (Op1I->getOpcode() == Instruction::And &&
2356           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2357         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2358
2359         Value *NewNot =
2360           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2361         return BinaryOperator::CreateAnd(Op0, NewNot);
2362       }
2363
2364       // 0 - (X sdiv C)  -> (X sdiv -C)
2365       if (Op1I->getOpcode() == Instruction::SDiv)
2366         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2367           if (CSI->isZero())
2368             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2369               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2370                                                ConstantExpr::getNeg(DivRHS));
2371
2372       // X - X*C --> X * (1-C)
2373       ConstantInt *C2 = 0;
2374       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2375         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2376         return BinaryOperator::CreateMul(Op0, CP1);
2377       }
2378
2379       // X - ((X / Y) * Y) --> X % Y
2380       if (Op1I->getOpcode() == Instruction::Mul)
2381         if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2382           if (Op0 == I->getOperand(0) &&
2383               Op1I->getOperand(1) == I->getOperand(1)) {
2384             if (I->getOpcode() == Instruction::SDiv)
2385               return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
2386             if (I->getOpcode() == Instruction::UDiv)
2387               return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
2388           }
2389     }
2390   }
2391
2392   if (!Op0->getType()->isFPOrFPVector())
2393     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2394       if (Op0I->getOpcode() == Instruction::Add) {
2395         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2396           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2397         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2398           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2399       } else if (Op0I->getOpcode() == Instruction::Sub) {
2400         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2401           return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2402       }
2403     }
2404
2405   ConstantInt *C1;
2406   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2407     if (X == Op1)  // X*C - X --> X * (C-1)
2408       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2409
2410     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2411     if (X == dyn_castFoldableMul(Op1, C2))
2412       return BinaryOperator::CreateMul(X, Subtract(C1, C2));
2413   }
2414   return 0;
2415 }
2416
2417 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2418 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2419 /// TrueIfSigned if the result of the comparison is true when the input value is
2420 /// signed.
2421 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2422                            bool &TrueIfSigned) {
2423   switch (pred) {
2424   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2425     TrueIfSigned = true;
2426     return RHS->isZero();
2427   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2428     TrueIfSigned = true;
2429     return RHS->isAllOnesValue();
2430   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2431     TrueIfSigned = false;
2432     return RHS->isAllOnesValue();
2433   case ICmpInst::ICMP_UGT:
2434     // True if LHS u> RHS and RHS == high-bit-mask - 1
2435     TrueIfSigned = true;
2436     return RHS->getValue() ==
2437       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2438   case ICmpInst::ICMP_UGE: 
2439     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2440     TrueIfSigned = true;
2441     return RHS->getValue().isSignBit();
2442   default:
2443     return false;
2444   }
2445 }
2446
2447 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2448   bool Changed = SimplifyCommutative(I);
2449   Value *Op0 = I.getOperand(0);
2450
2451   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2452     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2453
2454   // Simplify mul instructions with a constant RHS...
2455   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2456     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2457
2458       // ((X << C1)*C2) == (X * (C2 << C1))
2459       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2460         if (SI->getOpcode() == Instruction::Shl)
2461           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2462             return BinaryOperator::CreateMul(SI->getOperand(0),
2463                                              ConstantExpr::getShl(CI, ShOp));
2464
2465       if (CI->isZero())
2466         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2467       if (CI->equalsInt(1))                  // X * 1  == X
2468         return ReplaceInstUsesWith(I, Op0);
2469       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2470         return BinaryOperator::CreateNeg(Op0, I.getName());
2471
2472       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2473       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2474         return BinaryOperator::CreateShl(Op0,
2475                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2476       }
2477     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2478       if (Op1F->isNullValue())
2479         return ReplaceInstUsesWith(I, Op1);
2480
2481       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2482       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2483       // We need a better interface for long double here.
2484       if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2485         if (Op1F->isExactlyValue(1.0))
2486           return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2487     }
2488     
2489     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2490       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2491           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2492         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2493         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2494                                                      Op1, "tmp");
2495         InsertNewInstBefore(Add, I);
2496         Value *C1C2 = ConstantExpr::getMul(Op1, 
2497                                            cast<Constant>(Op0I->getOperand(1)));
2498         return BinaryOperator::CreateAdd(Add, C1C2);
2499         
2500       }
2501
2502     // Try to fold constant mul into select arguments.
2503     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2504       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2505         return R;
2506
2507     if (isa<PHINode>(Op0))
2508       if (Instruction *NV = FoldOpIntoPhi(I))
2509         return NV;
2510   }
2511
2512   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2513     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2514       return BinaryOperator::CreateMul(Op0v, Op1v);
2515
2516   if (I.getType() == Type::Int1Ty)
2517     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2518
2519   // If one of the operands of the multiply is a cast from a boolean value, then
2520   // we know the bool is either zero or one, so this is a 'masking' multiply.
2521   // See if we can simplify things based on how the boolean was originally
2522   // formed.
2523   CastInst *BoolCast = 0;
2524   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2525     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2526       BoolCast = CI;
2527   if (!BoolCast)
2528     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2529       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2530         BoolCast = CI;
2531   if (BoolCast) {
2532     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2533       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2534       const Type *SCOpTy = SCIOp0->getType();
2535       bool TIS = false;
2536       
2537       // If the icmp is true iff the sign bit of X is set, then convert this
2538       // multiply into a shift/and combination.
2539       if (isa<ConstantInt>(SCIOp1) &&
2540           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2541           TIS) {
2542         // Shift the X value right to turn it into "all signbits".
2543         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2544                                           SCOpTy->getPrimitiveSizeInBits()-1);
2545         Value *V =
2546           InsertNewInstBefore(
2547             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2548                                             BoolCast->getOperand(0)->getName()+
2549                                             ".mask"), I);
2550
2551         // If the multiply type is not the same as the source type, sign extend
2552         // or truncate to the multiply type.
2553         if (I.getType() != V->getType()) {
2554           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2555           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2556           Instruction::CastOps opcode = 
2557             (SrcBits == DstBits ? Instruction::BitCast : 
2558              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2559           V = InsertCastBefore(opcode, V, I.getType(), I);
2560         }
2561
2562         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2563         return BinaryOperator::CreateAnd(V, OtherOp);
2564       }
2565     }
2566   }
2567
2568   return Changed ? &I : 0;
2569 }
2570
2571 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2572 /// instruction.
2573 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2574   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2575   
2576   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2577   int NonNullOperand = -1;
2578   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2579     if (ST->isNullValue())
2580       NonNullOperand = 2;
2581   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2582   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2583     if (ST->isNullValue())
2584       NonNullOperand = 1;
2585   
2586   if (NonNullOperand == -1)
2587     return false;
2588   
2589   Value *SelectCond = SI->getOperand(0);
2590   
2591   // Change the div/rem to use 'Y' instead of the select.
2592   I.setOperand(1, SI->getOperand(NonNullOperand));
2593   
2594   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2595   // problem.  However, the select, or the condition of the select may have
2596   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2597   // propagate the known value for the select into other uses of it, and
2598   // propagate a known value of the condition into its other users.
2599   
2600   // If the select and condition only have a single use, don't bother with this,
2601   // early exit.
2602   if (SI->use_empty() && SelectCond->hasOneUse())
2603     return true;
2604   
2605   // Scan the current block backward, looking for other uses of SI.
2606   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2607   
2608   while (BBI != BBFront) {
2609     --BBI;
2610     // If we found a call to a function, we can't assume it will return, so
2611     // information from below it cannot be propagated above it.
2612     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2613       break;
2614     
2615     // Replace uses of the select or its condition with the known values.
2616     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2617          I != E; ++I) {
2618       if (*I == SI) {
2619         *I = SI->getOperand(NonNullOperand);
2620         AddToWorkList(BBI);
2621       } else if (*I == SelectCond) {
2622         *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2623                                    ConstantInt::getFalse();
2624         AddToWorkList(BBI);
2625       }
2626     }
2627     
2628     // If we past the instruction, quit looking for it.
2629     if (&*BBI == SI)
2630       SI = 0;
2631     if (&*BBI == SelectCond)
2632       SelectCond = 0;
2633     
2634     // If we ran out of things to eliminate, break out of the loop.
2635     if (SelectCond == 0 && SI == 0)
2636       break;
2637     
2638   }
2639   return true;
2640 }
2641
2642
2643 /// This function implements the transforms on div instructions that work
2644 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2645 /// used by the visitors to those instructions.
2646 /// @brief Transforms common to all three div instructions
2647 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2648   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2649
2650   // undef / X -> 0        for integer.
2651   // undef / X -> undef    for FP (the undef could be a snan).
2652   if (isa<UndefValue>(Op0)) {
2653     if (Op0->getType()->isFPOrFPVector())
2654       return ReplaceInstUsesWith(I, Op0);
2655     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2656   }
2657
2658   // X / undef -> undef
2659   if (isa<UndefValue>(Op1))
2660     return ReplaceInstUsesWith(I, Op1);
2661
2662   return 0;
2663 }
2664
2665 /// This function implements the transforms common to both integer division
2666 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2667 /// division instructions.
2668 /// @brief Common integer divide transforms
2669 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2670   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2671
2672   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2673   if (Op0 == Op1) {
2674     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2675       ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2676       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2677       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2678     }
2679
2680     ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2681     return ReplaceInstUsesWith(I, CI);
2682   }
2683   
2684   if (Instruction *Common = commonDivTransforms(I))
2685     return Common;
2686   
2687   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2688   // This does not apply for fdiv.
2689   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2690     return &I;
2691
2692   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2693     // div X, 1 == X
2694     if (RHS->equalsInt(1))
2695       return ReplaceInstUsesWith(I, Op0);
2696
2697     // (X / C1) / C2  -> X / (C1*C2)
2698     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2699       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2700         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2701           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2702             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2703           else 
2704             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2705                                           Multiply(RHS, LHSRHS));
2706         }
2707
2708     if (!RHS->isZero()) { // avoid X udiv 0
2709       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2710         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2711           return R;
2712       if (isa<PHINode>(Op0))
2713         if (Instruction *NV = FoldOpIntoPhi(I))
2714           return NV;
2715     }
2716   }
2717
2718   // 0 / X == 0, we don't need to preserve faults!
2719   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2720     if (LHS->equalsInt(0))
2721       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2722
2723   // It can't be division by zero, hence it must be division by one.
2724   if (I.getType() == Type::Int1Ty)
2725     return ReplaceInstUsesWith(I, Op0);
2726
2727   return 0;
2728 }
2729
2730 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2731   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2732
2733   // Handle the integer div common cases
2734   if (Instruction *Common = commonIDivTransforms(I))
2735     return Common;
2736
2737   // X udiv C^2 -> X >> C
2738   // Check to see if this is an unsigned division with an exact power of 2,
2739   // if so, convert to a right shift.
2740   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2741     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2742       return BinaryOperator::CreateLShr(Op0, 
2743                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2744   }
2745
2746   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2747   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2748     if (RHSI->getOpcode() == Instruction::Shl &&
2749         isa<ConstantInt>(RHSI->getOperand(0))) {
2750       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2751       if (C1.isPowerOf2()) {
2752         Value *N = RHSI->getOperand(1);
2753         const Type *NTy = N->getType();
2754         if (uint32_t C2 = C1.logBase2()) {
2755           Constant *C2V = ConstantInt::get(NTy, C2);
2756           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
2757         }
2758         return BinaryOperator::CreateLShr(Op0, N);
2759       }
2760     }
2761   }
2762   
2763   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2764   // where C1&C2 are powers of two.
2765   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2766     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2767       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2768         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2769         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2770           // Compute the shift amounts
2771           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2772           // Construct the "on true" case of the select
2773           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2774           Instruction *TSI = BinaryOperator::CreateLShr(
2775                                                  Op0, TC, SI->getName()+".t");
2776           TSI = InsertNewInstBefore(TSI, I);
2777   
2778           // Construct the "on false" case of the select
2779           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2780           Instruction *FSI = BinaryOperator::CreateLShr(
2781                                                  Op0, FC, SI->getName()+".f");
2782           FSI = InsertNewInstBefore(FSI, I);
2783
2784           // construct the select instruction and return it.
2785           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
2786         }
2787       }
2788   return 0;
2789 }
2790
2791 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2792   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2793
2794   // Handle the integer div common cases
2795   if (Instruction *Common = commonIDivTransforms(I))
2796     return Common;
2797
2798   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2799     // sdiv X, -1 == -X
2800     if (RHS->isAllOnesValue())
2801       return BinaryOperator::CreateNeg(Op0);
2802
2803     // -X/C -> X/-C
2804     if (Value *LHSNeg = dyn_castNegVal(Op0))
2805       return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2806   }
2807
2808   // If the sign bits of both operands are zero (i.e. we can prove they are
2809   // unsigned inputs), turn this into a udiv.
2810   if (I.getType()->isInteger()) {
2811     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2812     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2813       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2814       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2815     }
2816   }      
2817   
2818   return 0;
2819 }
2820
2821 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2822   return commonDivTransforms(I);
2823 }
2824
2825 /// This function implements the transforms on rem instructions that work
2826 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2827 /// is used by the visitors to those instructions.
2828 /// @brief Transforms common to all three rem instructions
2829 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2830   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2831
2832   // 0 % X == 0 for integer, we don't need to preserve faults!
2833   if (Constant *LHS = dyn_cast<Constant>(Op0))
2834     if (LHS->isNullValue())
2835       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2836
2837   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
2838     if (I.getType()->isFPOrFPVector())
2839       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
2840     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2841   }
2842   if (isa<UndefValue>(Op1))
2843     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2844
2845   // Handle cases involving: rem X, (select Cond, Y, Z)
2846   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2847     return &I;
2848
2849   return 0;
2850 }
2851
2852 /// This function implements the transforms common to both integer remainder
2853 /// instructions (urem and srem). It is called by the visitors to those integer
2854 /// remainder instructions.
2855 /// @brief Common integer remainder transforms
2856 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2857   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2858
2859   if (Instruction *common = commonRemTransforms(I))
2860     return common;
2861
2862   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2863     // X % 0 == undef, we don't need to preserve faults!
2864     if (RHS->equalsInt(0))
2865       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2866     
2867     if (RHS->equalsInt(1))  // X % 1 == 0
2868       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2869
2870     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2871       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2872         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2873           return R;
2874       } else if (isa<PHINode>(Op0I)) {
2875         if (Instruction *NV = FoldOpIntoPhi(I))
2876           return NV;
2877       }
2878
2879       // See if we can fold away this rem instruction.
2880       uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2881       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2882       if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2883                                KnownZero, KnownOne))
2884         return &I;
2885     }
2886   }
2887
2888   return 0;
2889 }
2890
2891 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2892   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2893
2894   if (Instruction *common = commonIRemTransforms(I))
2895     return common;
2896   
2897   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2898     // X urem C^2 -> X and C
2899     // Check to see if this is an unsigned remainder with an exact power of 2,
2900     // if so, convert to a bitwise and.
2901     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2902       if (C->getValue().isPowerOf2())
2903         return BinaryOperator::CreateAnd(Op0, SubOne(C));
2904   }
2905
2906   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2907     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2908     if (RHSI->getOpcode() == Instruction::Shl &&
2909         isa<ConstantInt>(RHSI->getOperand(0))) {
2910       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2911         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2912         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
2913                                                                    "tmp"), I);
2914         return BinaryOperator::CreateAnd(Op0, Add);
2915       }
2916     }
2917   }
2918
2919   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2920   // where C1&C2 are powers of two.
2921   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2922     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2923       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2924         // STO == 0 and SFO == 0 handled above.
2925         if ((STO->getValue().isPowerOf2()) && 
2926             (SFO->getValue().isPowerOf2())) {
2927           Value *TrueAnd = InsertNewInstBefore(
2928             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2929           Value *FalseAnd = InsertNewInstBefore(
2930             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2931           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
2932         }
2933       }
2934   }
2935   
2936   return 0;
2937 }
2938
2939 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2940   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2941
2942   // Handle the integer rem common cases
2943   if (Instruction *common = commonIRemTransforms(I))
2944     return common;
2945   
2946   if (Value *RHSNeg = dyn_castNegVal(Op1))
2947     if (!isa<ConstantInt>(RHSNeg) || 
2948         cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
2949       // X % -Y -> X % Y
2950       AddUsesToWorkList(I);
2951       I.setOperand(1, RHSNeg);
2952       return &I;
2953     }
2954  
2955   // If the sign bits of both operands are zero (i.e. we can prove they are
2956   // unsigned inputs), turn this into a urem.
2957   if (I.getType()->isInteger()) {
2958     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2959     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2960       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2961       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
2962     }
2963   }
2964
2965   return 0;
2966 }
2967
2968 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2969   return commonRemTransforms(I);
2970 }
2971
2972 // isOneBitSet - Return true if there is exactly one bit set in the specified
2973 // constant.
2974 static bool isOneBitSet(const ConstantInt *CI) {
2975   return CI->getValue().isPowerOf2();
2976 }
2977
2978 // isHighOnes - Return true if the constant is of the form 1+0+.
2979 // This is the same as lowones(~X).
2980 static bool isHighOnes(const ConstantInt *CI) {
2981   return (~CI->getValue() + 1).isPowerOf2();
2982 }
2983
2984 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
2985 /// are carefully arranged to allow folding of expressions such as:
2986 ///
2987 ///      (A < B) | (A > B) --> (A != B)
2988 ///
2989 /// Note that this is only valid if the first and second predicates have the
2990 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
2991 ///
2992 /// Three bits are used to represent the condition, as follows:
2993 ///   0  A > B
2994 ///   1  A == B
2995 ///   2  A < B
2996 ///
2997 /// <=>  Value  Definition
2998 /// 000     0   Always false
2999 /// 001     1   A >  B
3000 /// 010     2   A == B
3001 /// 011     3   A >= B
3002 /// 100     4   A <  B
3003 /// 101     5   A != B
3004 /// 110     6   A <= B
3005 /// 111     7   Always true
3006 ///  
3007 static unsigned getICmpCode(const ICmpInst *ICI) {
3008   switch (ICI->getPredicate()) {
3009     // False -> 0
3010   case ICmpInst::ICMP_UGT: return 1;  // 001
3011   case ICmpInst::ICMP_SGT: return 1;  // 001
3012   case ICmpInst::ICMP_EQ:  return 2;  // 010
3013   case ICmpInst::ICMP_UGE: return 3;  // 011
3014   case ICmpInst::ICMP_SGE: return 3;  // 011
3015   case ICmpInst::ICMP_ULT: return 4;  // 100
3016   case ICmpInst::ICMP_SLT: return 4;  // 100
3017   case ICmpInst::ICMP_NE:  return 5;  // 101
3018   case ICmpInst::ICMP_ULE: return 6;  // 110
3019   case ICmpInst::ICMP_SLE: return 6;  // 110
3020     // True -> 7
3021   default:
3022     assert(0 && "Invalid ICmp predicate!");
3023     return 0;
3024   }
3025 }
3026
3027 /// getICmpValue - This is the complement of getICmpCode, which turns an
3028 /// opcode and two operands into either a constant true or false, or a brand 
3029 /// new ICmp instruction. The sign is passed in to determine which kind
3030 /// of predicate to use in new icmp instructions.
3031 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3032   switch (code) {
3033   default: assert(0 && "Illegal ICmp code!");
3034   case  0: return ConstantInt::getFalse();
3035   case  1: 
3036     if (sign)
3037       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3038     else
3039       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3040   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3041   case  3: 
3042     if (sign)
3043       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3044     else
3045       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3046   case  4: 
3047     if (sign)
3048       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3049     else
3050       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3051   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3052   case  6: 
3053     if (sign)
3054       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3055     else
3056       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3057   case  7: return ConstantInt::getTrue();
3058   }
3059 }
3060
3061 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3062   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3063     (ICmpInst::isSignedPredicate(p1) && 
3064      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3065     (ICmpInst::isSignedPredicate(p2) && 
3066      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3067 }
3068
3069 namespace { 
3070 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3071 struct FoldICmpLogical {
3072   InstCombiner &IC;
3073   Value *LHS, *RHS;
3074   ICmpInst::Predicate pred;
3075   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3076     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3077       pred(ICI->getPredicate()) {}
3078   bool shouldApply(Value *V) const {
3079     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3080       if (PredicatesFoldable(pred, ICI->getPredicate()))
3081         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3082                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3083     return false;
3084   }
3085   Instruction *apply(Instruction &Log) const {
3086     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3087     if (ICI->getOperand(0) != LHS) {
3088       assert(ICI->getOperand(1) == LHS);
3089       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3090     }
3091
3092     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3093     unsigned LHSCode = getICmpCode(ICI);
3094     unsigned RHSCode = getICmpCode(RHSICI);
3095     unsigned Code;
3096     switch (Log.getOpcode()) {
3097     case Instruction::And: Code = LHSCode & RHSCode; break;
3098     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3099     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3100     default: assert(0 && "Illegal logical opcode!"); return 0;
3101     }
3102
3103     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3104                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3105       
3106     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3107     if (Instruction *I = dyn_cast<Instruction>(RV))
3108       return I;
3109     // Otherwise, it's a constant boolean value...
3110     return IC.ReplaceInstUsesWith(Log, RV);
3111   }
3112 };
3113 } // end anonymous namespace
3114
3115 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3116 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3117 // guaranteed to be a binary operator.
3118 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3119                                     ConstantInt *OpRHS,
3120                                     ConstantInt *AndRHS,
3121                                     BinaryOperator &TheAnd) {
3122   Value *X = Op->getOperand(0);
3123   Constant *Together = 0;
3124   if (!Op->isShift())
3125     Together = And(AndRHS, OpRHS);
3126
3127   switch (Op->getOpcode()) {
3128   case Instruction::Xor:
3129     if (Op->hasOneUse()) {
3130       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3131       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3132       InsertNewInstBefore(And, TheAnd);
3133       And->takeName(Op);
3134       return BinaryOperator::CreateXor(And, Together);
3135     }
3136     break;
3137   case Instruction::Or:
3138     if (Together == AndRHS) // (X | C) & C --> C
3139       return ReplaceInstUsesWith(TheAnd, AndRHS);
3140
3141     if (Op->hasOneUse() && Together != OpRHS) {
3142       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3143       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3144       InsertNewInstBefore(Or, TheAnd);
3145       Or->takeName(Op);
3146       return BinaryOperator::CreateAnd(Or, AndRHS);
3147     }
3148     break;
3149   case Instruction::Add:
3150     if (Op->hasOneUse()) {
3151       // Adding a one to a single bit bit-field should be turned into an XOR
3152       // of the bit.  First thing to check is to see if this AND is with a
3153       // single bit constant.
3154       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3155
3156       // If there is only one bit set...
3157       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3158         // Ok, at this point, we know that we are masking the result of the
3159         // ADD down to exactly one bit.  If the constant we are adding has
3160         // no bits set below this bit, then we can eliminate the ADD.
3161         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3162
3163         // Check to see if any bits below the one bit set in AndRHSV are set.
3164         if ((AddRHS & (AndRHSV-1)) == 0) {
3165           // If not, the only thing that can effect the output of the AND is
3166           // the bit specified by AndRHSV.  If that bit is set, the effect of
3167           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3168           // no effect.
3169           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3170             TheAnd.setOperand(0, X);
3171             return &TheAnd;
3172           } else {
3173             // Pull the XOR out of the AND.
3174             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3175             InsertNewInstBefore(NewAnd, TheAnd);
3176             NewAnd->takeName(Op);
3177             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3178           }
3179         }
3180       }
3181     }
3182     break;
3183
3184   case Instruction::Shl: {
3185     // We know that the AND will not produce any of the bits shifted in, so if
3186     // the anded constant includes them, clear them now!
3187     //
3188     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3189     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3190     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3191     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3192
3193     if (CI->getValue() == ShlMask) { 
3194     // Masking out bits that the shift already masks
3195       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3196     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3197       TheAnd.setOperand(1, CI);
3198       return &TheAnd;
3199     }
3200     break;
3201   }
3202   case Instruction::LShr:
3203   {
3204     // We know that the AND will not produce any of the bits shifted in, so if
3205     // the anded constant includes them, clear them now!  This only applies to
3206     // unsigned shifts, because a signed shr may bring in set bits!
3207     //
3208     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3209     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3210     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3211     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3212
3213     if (CI->getValue() == ShrMask) {   
3214     // Masking out bits that the shift already masks.
3215       return ReplaceInstUsesWith(TheAnd, Op);
3216     } else if (CI != AndRHS) {
3217       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3218       return &TheAnd;
3219     }
3220     break;
3221   }
3222   case Instruction::AShr:
3223     // Signed shr.
3224     // See if this is shifting in some sign extension, then masking it out
3225     // with an and.
3226     if (Op->hasOneUse()) {
3227       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3228       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3229       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3230       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3231       if (C == AndRHS) {          // Masking out bits shifted in.
3232         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3233         // Make the argument unsigned.
3234         Value *ShVal = Op->getOperand(0);
3235         ShVal = InsertNewInstBefore(
3236             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3237                                    Op->getName()), TheAnd);
3238         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3239       }
3240     }
3241     break;
3242   }
3243   return 0;
3244 }
3245
3246
3247 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3248 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3249 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3250 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3251 /// insert new instructions.
3252 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3253                                            bool isSigned, bool Inside, 
3254                                            Instruction &IB) {
3255   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3256             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3257          "Lo is not <= Hi in range emission code!");
3258     
3259   if (Inside) {
3260     if (Lo == Hi)  // Trivially false.
3261       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3262
3263     // V >= Min && V < Hi --> V < Hi
3264     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3265       ICmpInst::Predicate pred = (isSigned ? 
3266         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3267       return new ICmpInst(pred, V, Hi);
3268     }
3269
3270     // Emit V-Lo <u Hi-Lo
3271     Constant *NegLo = ConstantExpr::getNeg(Lo);
3272     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3273     InsertNewInstBefore(Add, IB);
3274     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3275     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3276   }
3277
3278   if (Lo == Hi)  // Trivially true.
3279     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3280
3281   // V < Min || V >= Hi -> V > Hi-1
3282   Hi = SubOne(cast<ConstantInt>(Hi));
3283   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3284     ICmpInst::Predicate pred = (isSigned ? 
3285         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3286     return new ICmpInst(pred, V, Hi);
3287   }
3288
3289   // Emit V-Lo >u Hi-1-Lo
3290   // Note that Hi has already had one subtracted from it, above.
3291   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3292   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3293   InsertNewInstBefore(Add, IB);
3294   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3295   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3296 }
3297
3298 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3299 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3300 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3301 // not, since all 1s are not contiguous.
3302 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3303   const APInt& V = Val->getValue();
3304   uint32_t BitWidth = Val->getType()->getBitWidth();
3305   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3306
3307   // look for the first zero bit after the run of ones
3308   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3309   // look for the first non-zero bit
3310   ME = V.getActiveBits(); 
3311   return true;
3312 }
3313
3314 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3315 /// where isSub determines whether the operator is a sub.  If we can fold one of
3316 /// the following xforms:
3317 /// 
3318 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3319 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3320 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3321 ///
3322 /// return (A +/- B).
3323 ///
3324 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3325                                         ConstantInt *Mask, bool isSub,
3326                                         Instruction &I) {
3327   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3328   if (!LHSI || LHSI->getNumOperands() != 2 ||
3329       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3330
3331   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3332
3333   switch (LHSI->getOpcode()) {
3334   default: return 0;
3335   case Instruction::And:
3336     if (And(N, Mask) == Mask) {
3337       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3338       if ((Mask->getValue().countLeadingZeros() + 
3339            Mask->getValue().countPopulation()) == 
3340           Mask->getValue().getBitWidth())
3341         break;
3342
3343       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3344       // part, we don't need any explicit masks to take them out of A.  If that
3345       // is all N is, ignore it.
3346       uint32_t MB = 0, ME = 0;
3347       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3348         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3349         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3350         if (MaskedValueIsZero(RHS, Mask))
3351           break;
3352       }
3353     }
3354     return 0;
3355   case Instruction::Or:
3356   case Instruction::Xor:
3357     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3358     if ((Mask->getValue().countLeadingZeros() + 
3359          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3360         && And(N, Mask)->isZero())
3361       break;
3362     return 0;
3363   }
3364   
3365   Instruction *New;
3366   if (isSub)
3367     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3368   else
3369     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3370   return InsertNewInstBefore(New, I);
3371 }
3372
3373 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3374   bool Changed = SimplifyCommutative(I);
3375   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3376
3377   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3378     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3379
3380   // and X, X = X
3381   if (Op0 == Op1)
3382     return ReplaceInstUsesWith(I, Op1);
3383
3384   // See if we can simplify any instructions used by the instruction whose sole 
3385   // purpose is to compute bits we don't care about.
3386   if (!isa<VectorType>(I.getType())) {
3387     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3388     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3389     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3390                              KnownZero, KnownOne))
3391       return &I;
3392   } else {
3393     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3394       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3395         return ReplaceInstUsesWith(I, I.getOperand(0));
3396     } else if (isa<ConstantAggregateZero>(Op1)) {
3397       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3398     }
3399   }
3400   
3401   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3402     const APInt& AndRHSMask = AndRHS->getValue();
3403     APInt NotAndRHS(~AndRHSMask);
3404
3405     // Optimize a variety of ((val OP C1) & C2) combinations...
3406     if (isa<BinaryOperator>(Op0)) {
3407       Instruction *Op0I = cast<Instruction>(Op0);
3408       Value *Op0LHS = Op0I->getOperand(0);
3409       Value *Op0RHS = Op0I->getOperand(1);
3410       switch (Op0I->getOpcode()) {
3411       case Instruction::Xor:
3412       case Instruction::Or:
3413         // If the mask is only needed on one incoming arm, push it up.
3414         if (Op0I->hasOneUse()) {
3415           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3416             // Not masking anything out for the LHS, move to RHS.
3417             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3418                                                    Op0RHS->getName()+".masked");
3419             InsertNewInstBefore(NewRHS, I);
3420             return BinaryOperator::Create(
3421                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3422           }
3423           if (!isa<Constant>(Op0RHS) &&
3424               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3425             // Not masking anything out for the RHS, move to LHS.
3426             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3427                                                    Op0LHS->getName()+".masked");
3428             InsertNewInstBefore(NewLHS, I);
3429             return BinaryOperator::Create(
3430                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3431           }
3432         }
3433
3434         break;
3435       case Instruction::Add:
3436         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3437         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3438         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3439         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3440           return BinaryOperator::CreateAnd(V, AndRHS);
3441         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3442           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
3443         break;
3444
3445       case Instruction::Sub:
3446         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3447         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3448         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3449         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3450           return BinaryOperator::CreateAnd(V, AndRHS);
3451
3452         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3453         // has 1's for all bits that the subtraction with A might affect.
3454         if (Op0I->hasOneUse()) {
3455           uint32_t BitWidth = AndRHSMask.getBitWidth();
3456           uint32_t Zeros = AndRHSMask.countLeadingZeros();
3457           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3458
3459           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
3460           if (!(A && A->isZero()) &&               // avoid infinite recursion.
3461               MaskedValueIsZero(Op0LHS, Mask)) {
3462             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3463             InsertNewInstBefore(NewNeg, I);
3464             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3465           }
3466         }
3467         break;
3468
3469       case Instruction::Shl:
3470       case Instruction::LShr:
3471         // (1 << x) & 1 --> zext(x == 0)
3472         // (1 >> x) & 1 --> zext(x == 0)
3473         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
3474           Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3475                                            Constant::getNullValue(I.getType()));
3476           InsertNewInstBefore(NewICmp, I);
3477           return new ZExtInst(NewICmp, I.getType());
3478         }
3479         break;
3480       }
3481
3482       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3483         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3484           return Res;
3485     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3486       // If this is an integer truncation or change from signed-to-unsigned, and
3487       // if the source is an and/or with immediate, transform it.  This
3488       // frequently occurs for bitfield accesses.
3489       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3490         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3491             CastOp->getNumOperands() == 2)
3492           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3493             if (CastOp->getOpcode() == Instruction::And) {
3494               // Change: and (cast (and X, C1) to T), C2
3495               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3496               // This will fold the two constants together, which may allow 
3497               // other simplifications.
3498               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
3499                 CastOp->getOperand(0), I.getType(), 
3500                 CastOp->getName()+".shrunk");
3501               NewCast = InsertNewInstBefore(NewCast, I);
3502               // trunc_or_bitcast(C1)&C2
3503               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3504               C3 = ConstantExpr::getAnd(C3, AndRHS);
3505               return BinaryOperator::CreateAnd(NewCast, C3);
3506             } else if (CastOp->getOpcode() == Instruction::Or) {
3507               // Change: and (cast (or X, C1) to T), C2
3508               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3509               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3510               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3511                 return ReplaceInstUsesWith(I, AndRHS);
3512             }
3513           }
3514       }
3515     }
3516
3517     // Try to fold constant and into select arguments.
3518     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3519       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3520         return R;
3521     if (isa<PHINode>(Op0))
3522       if (Instruction *NV = FoldOpIntoPhi(I))
3523         return NV;
3524   }
3525
3526   Value *Op0NotVal = dyn_castNotVal(Op0);
3527   Value *Op1NotVal = dyn_castNotVal(Op1);
3528
3529   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3530     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3531
3532   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3533   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3534     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
3535                                                I.getName()+".demorgan");
3536     InsertNewInstBefore(Or, I);
3537     return BinaryOperator::CreateNot(Or);
3538   }
3539   
3540   {
3541     Value *A = 0, *B = 0, *C = 0, *D = 0;
3542     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3543       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3544         return ReplaceInstUsesWith(I, Op1);
3545     
3546       // (A|B) & ~(A&B) -> A^B
3547       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3548         if ((A == C && B == D) || (A == D && B == C))
3549           return BinaryOperator::CreateXor(A, B);
3550       }
3551     }
3552     
3553     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3554       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3555         return ReplaceInstUsesWith(I, Op0);
3556
3557       // ~(A&B) & (A|B) -> A^B
3558       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3559         if ((A == C && B == D) || (A == D && B == C))
3560           return BinaryOperator::CreateXor(A, B);
3561       }
3562     }
3563     
3564     if (Op0->hasOneUse() &&
3565         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3566       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3567         I.swapOperands();     // Simplify below
3568         std::swap(Op0, Op1);
3569       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3570         cast<BinaryOperator>(Op0)->swapOperands();
3571         I.swapOperands();     // Simplify below
3572         std::swap(Op0, Op1);
3573       }
3574     }
3575     if (Op1->hasOneUse() &&
3576         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3577       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3578         cast<BinaryOperator>(Op1)->swapOperands();
3579         std::swap(A, B);
3580       }
3581       if (A == Op0) {                                // A&(A^B) -> A & ~B
3582         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
3583         InsertNewInstBefore(NotB, I);
3584         return BinaryOperator::CreateAnd(A, NotB);
3585       }
3586     }
3587   }
3588   
3589   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3590     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3591     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3592       return R;
3593
3594     Value *LHSVal, *RHSVal;
3595     ConstantInt *LHSCst, *RHSCst;
3596     ICmpInst::Predicate LHSCC, RHSCC;
3597     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3598       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3599         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3600             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3601             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3602             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3603             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3604             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3605             
3606             // Don't try to fold ICMP_SLT + ICMP_ULT.
3607             (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3608              ICmpInst::isSignedPredicate(LHSCC) == 
3609                  ICmpInst::isSignedPredicate(RHSCC))) {
3610           // Ensure that the larger constant is on the RHS.
3611           ICmpInst::Predicate GT;
3612           if (ICmpInst::isSignedPredicate(LHSCC) ||
3613               (ICmpInst::isEquality(LHSCC) && 
3614                ICmpInst::isSignedPredicate(RHSCC)))
3615             GT = ICmpInst::ICMP_SGT;
3616           else
3617             GT = ICmpInst::ICMP_UGT;
3618           
3619           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3620           ICmpInst *LHS = cast<ICmpInst>(Op0);
3621           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3622             std::swap(LHS, RHS);
3623             std::swap(LHSCst, RHSCst);
3624             std::swap(LHSCC, RHSCC);
3625           }
3626
3627           // At this point, we know we have have two icmp instructions
3628           // comparing a value against two constants and and'ing the result
3629           // together.  Because of the above check, we know that we only have
3630           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3631           // (from the FoldICmpLogical check above), that the two constants 
3632           // are not equal and that the larger constant is on the RHS
3633           assert(LHSCst != RHSCst && "Compares not folded above?");
3634
3635           switch (LHSCC) {
3636           default: assert(0 && "Unknown integer condition code!");
3637           case ICmpInst::ICMP_EQ:
3638             switch (RHSCC) {
3639             default: assert(0 && "Unknown integer condition code!");
3640             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3641             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3642             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3643               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3644             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3645             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3646             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3647               return ReplaceInstUsesWith(I, LHS);
3648             }
3649           case ICmpInst::ICMP_NE:
3650             switch (RHSCC) {
3651             default: assert(0 && "Unknown integer condition code!");
3652             case ICmpInst::ICMP_ULT:
3653               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3654                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3655               break;                        // (X != 13 & X u< 15) -> no change
3656             case ICmpInst::ICMP_SLT:
3657               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3658                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3659               break;                        // (X != 13 & X s< 15) -> no change
3660             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3661             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3662             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3663               return ReplaceInstUsesWith(I, RHS);
3664             case ICmpInst::ICMP_NE:
3665               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3666                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3667                 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
3668                                                       LHSVal->getName()+".off");
3669                 InsertNewInstBefore(Add, I);
3670                 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3671                                     ConstantInt::get(Add->getType(), 1));
3672               }
3673               break;                        // (X != 13 & X != 15) -> no change
3674             }
3675             break;
3676           case ICmpInst::ICMP_ULT:
3677             switch (RHSCC) {
3678             default: assert(0 && "Unknown integer condition code!");
3679             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3680             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3681               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3682             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3683               break;
3684             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3685             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3686               return ReplaceInstUsesWith(I, LHS);
3687             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3688               break;
3689             }
3690             break;
3691           case ICmpInst::ICMP_SLT:
3692             switch (RHSCC) {
3693             default: assert(0 && "Unknown integer condition code!");
3694             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3695             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3696               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3697             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3698               break;
3699             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3700             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3701               return ReplaceInstUsesWith(I, LHS);
3702             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3703               break;
3704             }
3705             break;
3706           case ICmpInst::ICMP_UGT:
3707             switch (RHSCC) {
3708             default: assert(0 && "Unknown integer condition code!");
3709             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3710             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3711               return ReplaceInstUsesWith(I, RHS);
3712             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3713               break;
3714             case ICmpInst::ICMP_NE:
3715               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3716                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3717               break;                        // (X u> 13 & X != 15) -> no change
3718             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3719               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3720                                      true, I);
3721             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3722               break;
3723             }
3724             break;
3725           case ICmpInst::ICMP_SGT:
3726             switch (RHSCC) {
3727             default: assert(0 && "Unknown integer condition code!");
3728             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3729             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3730               return ReplaceInstUsesWith(I, RHS);
3731             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3732               break;
3733             case ICmpInst::ICMP_NE:
3734               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3735                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3736               break;                        // (X s> 13 & X != 15) -> no change
3737             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3738               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
3739                                      true, I);
3740             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3741               break;
3742             }
3743             break;
3744           }
3745         }
3746   }
3747
3748   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3749   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3750     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3751       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3752         const Type *SrcTy = Op0C->getOperand(0)->getType();
3753         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3754             // Only do this if the casts both really cause code to be generated.
3755             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3756                               I.getType(), TD) &&
3757             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3758                               I.getType(), TD)) {
3759           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
3760                                                          Op1C->getOperand(0),
3761                                                          I.getName());
3762           InsertNewInstBefore(NewOp, I);
3763           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
3764         }
3765       }
3766     
3767   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3768   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3769     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3770       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3771           SI0->getOperand(1) == SI1->getOperand(1) &&
3772           (SI0->hasOneUse() || SI1->hasOneUse())) {
3773         Instruction *NewOp =
3774           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
3775                                                         SI1->getOperand(0),
3776                                                         SI0->getName()), I);
3777         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
3778                                       SI1->getOperand(1));
3779       }
3780   }
3781
3782   // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3783   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3784     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3785       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3786           RHS->getPredicate() == FCmpInst::FCMP_ORD)
3787         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3788           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3789             // If either of the constants are nans, then the whole thing returns
3790             // false.
3791             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3792               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3793             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3794                                 RHS->getOperand(0));
3795           }
3796     }
3797   }
3798
3799   return Changed ? &I : 0;
3800 }
3801
3802 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3803 /// in the result.  If it does, and if the specified byte hasn't been filled in
3804 /// yet, fill it in and return false.
3805 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3806   Instruction *I = dyn_cast<Instruction>(V);
3807   if (I == 0) return true;
3808
3809   // If this is an or instruction, it is an inner node of the bswap.
3810   if (I->getOpcode() == Instruction::Or)
3811     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3812            CollectBSwapParts(I->getOperand(1), ByteValues);
3813   
3814   uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3815   // If this is a shift by a constant int, and it is "24", then its operand
3816   // defines a byte.  We only handle unsigned types here.
3817   if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3818     // Not shifting the entire input by N-1 bytes?
3819     if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3820         8*(ByteValues.size()-1))
3821       return true;
3822     
3823     unsigned DestNo;
3824     if (I->getOpcode() == Instruction::Shl) {
3825       // X << 24 defines the top byte with the lowest of the input bytes.
3826       DestNo = ByteValues.size()-1;
3827     } else {
3828       // X >>u 24 defines the low byte with the highest of the input bytes.
3829       DestNo = 0;
3830     }
3831     
3832     // If the destination byte value is already defined, the values are or'd
3833     // together, which isn't a bswap (unless it's an or of the same bits).
3834     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3835       return true;
3836     ByteValues[DestNo] = I->getOperand(0);
3837     return false;
3838   }
3839   
3840   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3841   // don't have this.
3842   Value *Shift = 0, *ShiftLHS = 0;
3843   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3844   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3845       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3846     return true;
3847   Instruction *SI = cast<Instruction>(Shift);
3848
3849   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3850   if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3851       ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3852     return true;
3853   
3854   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3855   unsigned DestByte;
3856   if (AndAmt->getValue().getActiveBits() > 64)
3857     return true;
3858   uint64_t AndAmtVal = AndAmt->getZExtValue();
3859   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3860     if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3861       break;
3862   // Unknown mask for bswap.
3863   if (DestByte == ByteValues.size()) return true;
3864   
3865   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3866   unsigned SrcByte;
3867   if (SI->getOpcode() == Instruction::Shl)
3868     SrcByte = DestByte - ShiftBytes;
3869   else
3870     SrcByte = DestByte + ShiftBytes;
3871   
3872   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3873   if (SrcByte != ByteValues.size()-DestByte-1)
3874     return true;
3875   
3876   // If the destination byte value is already defined, the values are or'd
3877   // together, which isn't a bswap (unless it's an or of the same bits).
3878   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3879     return true;
3880   ByteValues[DestByte] = SI->getOperand(0);
3881   return false;
3882 }
3883
3884 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3885 /// If so, insert the new bswap intrinsic and return it.
3886 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3887   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3888   if (!ITy || ITy->getBitWidth() % 16) 
3889     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
3890   
3891   /// ByteValues - For each byte of the result, we keep track of which value
3892   /// defines each byte.
3893   SmallVector<Value*, 8> ByteValues;
3894   ByteValues.resize(ITy->getBitWidth()/8);
3895     
3896   // Try to find all the pieces corresponding to the bswap.
3897   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3898       CollectBSwapParts(I.getOperand(1), ByteValues))
3899     return 0;
3900   
3901   // Check to see if all of the bytes come from the same value.
3902   Value *V = ByteValues[0];
3903   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3904   
3905   // Check to make sure that all of the bytes come from the same value.
3906   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3907     if (ByteValues[i] != V)
3908       return 0;
3909   const Type *Tys[] = { ITy };
3910   Module *M = I.getParent()->getParent()->getParent();
3911   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
3912   return CallInst::Create(F, V);
3913 }
3914
3915
3916 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3917   bool Changed = SimplifyCommutative(I);
3918   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3919
3920   if (isa<UndefValue>(Op1))                       // X | undef -> -1
3921     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3922
3923   // or X, X = X
3924   if (Op0 == Op1)
3925     return ReplaceInstUsesWith(I, Op0);
3926
3927   // See if we can simplify any instructions used by the instruction whose sole 
3928   // purpose is to compute bits we don't care about.
3929   if (!isa<VectorType>(I.getType())) {
3930     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3931     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3932     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3933                              KnownZero, KnownOne))
3934       return &I;
3935   } else if (isa<ConstantAggregateZero>(Op1)) {
3936     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
3937   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3938     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
3939       return ReplaceInstUsesWith(I, I.getOperand(1));
3940   }
3941     
3942
3943   
3944   // or X, -1 == -1
3945   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3946     ConstantInt *C1 = 0; Value *X = 0;
3947     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3948     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3949       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
3950       InsertNewInstBefore(Or, I);
3951       Or->takeName(Op0);
3952       return BinaryOperator::CreateAnd(Or, 
3953                ConstantInt::get(RHS->getValue() | C1->getValue()));
3954     }
3955
3956     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3957     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3958       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
3959       InsertNewInstBefore(Or, I);
3960       Or->takeName(Op0);
3961       return BinaryOperator::CreateXor(Or,
3962                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
3963     }
3964
3965     // Try to fold constant and into select arguments.
3966     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3967       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3968         return R;
3969     if (isa<PHINode>(Op0))
3970       if (Instruction *NV = FoldOpIntoPhi(I))
3971         return NV;
3972   }
3973
3974   Value *A = 0, *B = 0;
3975   ConstantInt *C1 = 0, *C2 = 0;
3976
3977   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3978     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3979       return ReplaceInstUsesWith(I, Op1);
3980   if (match(Op1, m_And(m_Value(A), m_Value(B))))
3981     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
3982       return ReplaceInstUsesWith(I, Op0);
3983
3984   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
3985   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
3986   if (match(Op0, m_Or(m_Value(), m_Value())) ||
3987       match(Op1, m_Or(m_Value(), m_Value())) ||
3988       (match(Op0, m_Shift(m_Value(), m_Value())) &&
3989        match(Op1, m_Shift(m_Value(), m_Value())))) {
3990     if (Instruction *BSwap = MatchBSwap(I))
3991       return BSwap;
3992   }
3993   
3994   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3995   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3996       MaskedValueIsZero(Op1, C1->getValue())) {
3997     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
3998     InsertNewInstBefore(NOr, I);
3999     NOr->takeName(Op0);
4000     return BinaryOperator::CreateXor(NOr, C1);
4001   }
4002
4003   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4004   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4005       MaskedValueIsZero(Op0, C1->getValue())) {
4006     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4007     InsertNewInstBefore(NOr, I);
4008     NOr->takeName(Op0);
4009     return BinaryOperator::CreateXor(NOr, C1);
4010   }
4011
4012   // (A & C)|(B & D)
4013   Value *C = 0, *D = 0;
4014   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4015       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4016     Value *V1 = 0, *V2 = 0, *V3 = 0;
4017     C1 = dyn_cast<ConstantInt>(C);
4018     C2 = dyn_cast<ConstantInt>(D);
4019     if (C1 && C2) {  // (A & C1)|(B & C2)
4020       // If we have: ((V + N) & C1) | (V & C2)
4021       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4022       // replace with V+N.
4023       if (C1->getValue() == ~C2->getValue()) {
4024         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4025             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4026           // Add commutes, try both ways.
4027           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4028             return ReplaceInstUsesWith(I, A);
4029           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4030             return ReplaceInstUsesWith(I, A);
4031         }
4032         // Or commutes, try both ways.
4033         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4034             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4035           // Add commutes, try both ways.
4036           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4037             return ReplaceInstUsesWith(I, B);
4038           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4039             return ReplaceInstUsesWith(I, B);
4040         }
4041       }
4042       V1 = 0; V2 = 0; V3 = 0;
4043     }
4044     
4045     // Check to see if we have any common things being and'ed.  If so, find the
4046     // terms for V1 & (V2|V3).
4047     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4048       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4049         V1 = A, V2 = C, V3 = D;
4050       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4051         V1 = A, V2 = B, V3 = C;
4052       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4053         V1 = C, V2 = A, V3 = D;
4054       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4055         V1 = C, V2 = A, V3 = B;
4056       
4057       if (V1) {
4058         Value *Or =
4059           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4060         return BinaryOperator::CreateAnd(V1, Or);
4061       }
4062     }
4063   }
4064   
4065   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4066   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4067     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4068       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4069           SI0->getOperand(1) == SI1->getOperand(1) &&
4070           (SI0->hasOneUse() || SI1->hasOneUse())) {
4071         Instruction *NewOp =
4072         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4073                                                      SI1->getOperand(0),
4074                                                      SI0->getName()), I);
4075         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4076                                       SI1->getOperand(1));
4077       }
4078   }
4079
4080   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4081     if (A == Op1)   // ~A | A == -1
4082       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4083   } else {
4084     A = 0;
4085   }
4086   // Note, A is still live here!
4087   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4088     if (Op0 == B)
4089       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4090
4091     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4092     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4093       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4094                                               I.getName()+".demorgan"), I);
4095       return BinaryOperator::CreateNot(And);
4096     }
4097   }
4098
4099   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4100   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4101     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4102       return R;
4103
4104     Value *LHSVal, *RHSVal;
4105     ConstantInt *LHSCst, *RHSCst;
4106     ICmpInst::Predicate LHSCC, RHSCC;
4107     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4108       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4109         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
4110             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4111             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4112             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4113             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4114             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4115             // We can't fold (ugt x, C) | (sgt x, C2).
4116             PredicatesFoldable(LHSCC, RHSCC)) {
4117           // Ensure that the larger constant is on the RHS.
4118           ICmpInst *LHS = cast<ICmpInst>(Op0);
4119           bool NeedsSwap;
4120           if (ICmpInst::isSignedPredicate(LHSCC))
4121             NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4122           else
4123             NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4124             
4125           if (NeedsSwap) {
4126             std::swap(LHS, RHS);
4127             std::swap(LHSCst, RHSCst);
4128             std::swap(LHSCC, RHSCC);
4129           }
4130
4131           // At this point, we know we have have two icmp instructions
4132           // comparing a value against two constants and or'ing the result
4133           // together.  Because of the above check, we know that we only have
4134           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4135           // FoldICmpLogical check above), that the two constants are not
4136           // equal.
4137           assert(LHSCst != RHSCst && "Compares not folded above?");
4138
4139           switch (LHSCC) {
4140           default: assert(0 && "Unknown integer condition code!");
4141           case ICmpInst::ICMP_EQ:
4142             switch (RHSCC) {
4143             default: assert(0 && "Unknown integer condition code!");
4144             case ICmpInst::ICMP_EQ:
4145               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4146                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4147                 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
4148                                                       LHSVal->getName()+".off");
4149                 InsertNewInstBefore(Add, I);
4150                 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4151                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4152               }
4153               break;                         // (X == 13 | X == 15) -> no change
4154             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4155             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4156               break;
4157             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4158             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4159             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4160               return ReplaceInstUsesWith(I, RHS);
4161             }
4162             break;
4163           case ICmpInst::ICMP_NE:
4164             switch (RHSCC) {
4165             default: assert(0 && "Unknown integer condition code!");
4166             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4167             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4168             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4169               return ReplaceInstUsesWith(I, LHS);
4170             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4171             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4172             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4173               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4174             }
4175             break;
4176           case ICmpInst::ICMP_ULT:
4177             switch (RHSCC) {
4178             default: assert(0 && "Unknown integer condition code!");
4179             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4180               break;
4181             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
4182               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4183               // this can cause overflow.
4184               if (RHSCst->isMaxValue(false))
4185                 return ReplaceInstUsesWith(I, LHS);
4186               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
4187                                      false, I);
4188             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4189               break;
4190             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4191             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4192               return ReplaceInstUsesWith(I, RHS);
4193             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4194               break;
4195             }
4196             break;
4197           case ICmpInst::ICMP_SLT:
4198             switch (RHSCC) {
4199             default: assert(0 && "Unknown integer condition code!");
4200             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4201               break;
4202             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
4203               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4204               // this can cause overflow.
4205               if (RHSCst->isMaxValue(true))
4206                 return ReplaceInstUsesWith(I, LHS);
4207               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
4208                                      false, I);
4209             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4210               break;
4211             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4212             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4213               return ReplaceInstUsesWith(I, RHS);
4214             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4215               break;
4216             }
4217             break;
4218           case ICmpInst::ICMP_UGT:
4219             switch (RHSCC) {
4220             default: assert(0 && "Unknown integer condition code!");
4221             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4222             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4223               return ReplaceInstUsesWith(I, LHS);
4224             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4225               break;
4226             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4227             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4228               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4229             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4230               break;
4231             }
4232             break;
4233           case ICmpInst::ICMP_SGT:
4234             switch (RHSCC) {
4235             default: assert(0 && "Unknown integer condition code!");
4236             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4237             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4238               return ReplaceInstUsesWith(I, LHS);
4239             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4240               break;
4241             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4242             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4243               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4244             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4245               break;
4246             }
4247             break;
4248           }
4249         }
4250   }
4251     
4252   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4253   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4254     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4255       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4256         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4257             !isa<ICmpInst>(Op1C->getOperand(0))) {
4258           const Type *SrcTy = Op0C->getOperand(0)->getType();
4259           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4260               // Only do this if the casts both really cause code to be
4261               // generated.
4262               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4263                                 I.getType(), TD) &&
4264               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4265                                 I.getType(), TD)) {
4266             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4267                                                           Op1C->getOperand(0),
4268                                                           I.getName());
4269             InsertNewInstBefore(NewOp, I);
4270             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4271           }
4272         }
4273       }
4274   }
4275   
4276     
4277   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4278   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4279     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4280       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4281           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4282           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
4283         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4284           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4285             // If either of the constants are nans, then the whole thing returns
4286             // true.
4287             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4288               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4289             
4290             // Otherwise, no need to compare the two constants, compare the
4291             // rest.
4292             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4293                                 RHS->getOperand(0));
4294           }
4295     }
4296   }
4297
4298   return Changed ? &I : 0;
4299 }
4300
4301 namespace {
4302
4303 // XorSelf - Implements: X ^ X --> 0
4304 struct XorSelf {
4305   Value *RHS;
4306   XorSelf(Value *rhs) : RHS(rhs) {}
4307   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4308   Instruction *apply(BinaryOperator &Xor) const {
4309     return &Xor;
4310   }
4311 };
4312
4313 }
4314
4315 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4316   bool Changed = SimplifyCommutative(I);
4317   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4318
4319   if (isa<UndefValue>(Op1)) {
4320     if (isa<UndefValue>(Op0))
4321       // Handle undef ^ undef -> 0 special case. This is a common
4322       // idiom (misuse).
4323       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4324     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4325   }
4326
4327   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4328   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4329     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4330     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4331   }
4332   
4333   // See if we can simplify any instructions used by the instruction whose sole 
4334   // purpose is to compute bits we don't care about.
4335   if (!isa<VectorType>(I.getType())) {
4336     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4337     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4338     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4339                              KnownZero, KnownOne))
4340       return &I;
4341   } else if (isa<ConstantAggregateZero>(Op1)) {
4342     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4343   }
4344
4345   // Is this a ~ operation?
4346   if (Value *NotOp = dyn_castNotVal(&I)) {
4347     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4348     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4349     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4350       if (Op0I->getOpcode() == Instruction::And || 
4351           Op0I->getOpcode() == Instruction::Or) {
4352         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4353         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4354           Instruction *NotY =
4355             BinaryOperator::CreateNot(Op0I->getOperand(1),
4356                                       Op0I->getOperand(1)->getName()+".not");
4357           InsertNewInstBefore(NotY, I);
4358           if (Op0I->getOpcode() == Instruction::And)
4359             return BinaryOperator::CreateOr(Op0NotVal, NotY);
4360           else
4361             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4362         }
4363       }
4364     }
4365   }
4366   
4367   
4368   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4369     // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4370     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4371       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4372         return new ICmpInst(ICI->getInversePredicate(),
4373                             ICI->getOperand(0), ICI->getOperand(1));
4374
4375       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4376         return new FCmpInst(FCI->getInversePredicate(),
4377                             FCI->getOperand(0), FCI->getOperand(1));
4378     }
4379
4380     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4381     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4382       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4383         if (CI->hasOneUse() && Op0C->hasOneUse()) {
4384           Instruction::CastOps Opcode = Op0C->getOpcode();
4385           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4386             if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4387                                              Op0C->getDestTy())) {
4388               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4389                                      CI->getOpcode(), CI->getInversePredicate(),
4390                                      CI->getOperand(0), CI->getOperand(1)), I);
4391               NewCI->takeName(CI);
4392               return CastInst::Create(Opcode, NewCI, Op0C->getType());
4393             }
4394           }
4395         }
4396       }
4397     }
4398
4399     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4400       // ~(c-X) == X-c-1 == X+(-c-1)
4401       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4402         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4403           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4404           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4405                                               ConstantInt::get(I.getType(), 1));
4406           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
4407         }
4408           
4409       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4410         if (Op0I->getOpcode() == Instruction::Add) {
4411           // ~(X-c) --> (-c-1)-X
4412           if (RHS->isAllOnesValue()) {
4413             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4414             return BinaryOperator::CreateSub(
4415                            ConstantExpr::getSub(NegOp0CI,
4416                                              ConstantInt::get(I.getType(), 1)),
4417                                           Op0I->getOperand(0));
4418           } else if (RHS->getValue().isSignBit()) {
4419             // (X + C) ^ signbit -> (X + C + signbit)
4420             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4421             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
4422
4423           }
4424         } else if (Op0I->getOpcode() == Instruction::Or) {
4425           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4426           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4427             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4428             // Anything in both C1 and C2 is known to be zero, remove it from
4429             // NewRHS.
4430             Constant *CommonBits = And(Op0CI, RHS);
4431             NewRHS = ConstantExpr::getAnd(NewRHS, 
4432                                           ConstantExpr::getNot(CommonBits));
4433             AddToWorkList(Op0I);
4434             I.setOperand(0, Op0I->getOperand(0));
4435             I.setOperand(1, NewRHS);
4436             return &I;
4437           }
4438         }
4439       }
4440     }
4441
4442     // Try to fold constant and into select arguments.
4443     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4444       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4445         return R;
4446     if (isa<PHINode>(Op0))
4447       if (Instruction *NV = FoldOpIntoPhi(I))
4448         return NV;
4449   }
4450
4451   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4452     if (X == Op1)
4453       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4454
4455   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4456     if (X == Op0)
4457       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4458
4459   
4460   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4461   if (Op1I) {
4462     Value *A, *B;
4463     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4464       if (A == Op0) {              // B^(B|A) == (A|B)^B
4465         Op1I->swapOperands();
4466         I.swapOperands();
4467         std::swap(Op0, Op1);
4468       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
4469         I.swapOperands();     // Simplified below.
4470         std::swap(Op0, Op1);
4471       }
4472     } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4473       if (Op0 == A)                                          // A^(A^B) == B
4474         return ReplaceInstUsesWith(I, B);
4475       else if (Op0 == B)                                     // A^(B^A) == B
4476         return ReplaceInstUsesWith(I, A);
4477     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4478       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
4479         Op1I->swapOperands();
4480         std::swap(A, B);
4481       }
4482       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
4483         I.swapOperands();     // Simplified below.
4484         std::swap(Op0, Op1);
4485       }
4486     }
4487   }
4488   
4489   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4490   if (Op0I) {
4491     Value *A, *B;
4492     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4493       if (A == Op1)                                  // (B|A)^B == (A|B)^B
4494         std::swap(A, B);
4495       if (B == Op1) {                                // (A|B)^B == A & ~B
4496         Instruction *NotB =
4497           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4498         return BinaryOperator::CreateAnd(A, NotB);
4499       }
4500     } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4501       if (Op1 == A)                                          // (A^B)^A == B
4502         return ReplaceInstUsesWith(I, B);
4503       else if (Op1 == B)                                     // (B^A)^A == B
4504         return ReplaceInstUsesWith(I, A);
4505     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4506       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
4507         std::swap(A, B);
4508       if (B == Op1 &&                                      // (B&A)^A == ~B & A
4509           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4510         Instruction *N =
4511           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4512         return BinaryOperator::CreateAnd(N, Op1);
4513       }
4514     }
4515   }
4516   
4517   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4518   if (Op0I && Op1I && Op0I->isShift() && 
4519       Op0I->getOpcode() == Op1I->getOpcode() && 
4520       Op0I->getOperand(1) == Op1I->getOperand(1) &&
4521       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4522     Instruction *NewOp =
4523       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
4524                                                     Op1I->getOperand(0),
4525                                                     Op0I->getName()), I);
4526     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
4527                                   Op1I->getOperand(1));
4528   }
4529     
4530   if (Op0I && Op1I) {
4531     Value *A, *B, *C, *D;
4532     // (A & B)^(A | B) -> A ^ B
4533     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4534         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4535       if ((A == C && B == D) || (A == D && B == C)) 
4536         return BinaryOperator::CreateXor(A, B);
4537     }
4538     // (A | B)^(A & B) -> A ^ B
4539     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4540         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4541       if ((A == C && B == D) || (A == D && B == C)) 
4542         return BinaryOperator::CreateXor(A, B);
4543     }
4544     
4545     // (A & B)^(C & D)
4546     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4547         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4548         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4549       // (X & Y)^(X & Y) -> (Y^Z) & X
4550       Value *X = 0, *Y = 0, *Z = 0;
4551       if (A == C)
4552         X = A, Y = B, Z = D;
4553       else if (A == D)
4554         X = A, Y = B, Z = C;
4555       else if (B == C)
4556         X = B, Y = A, Z = D;
4557       else if (B == D)
4558         X = B, Y = A, Z = C;
4559       
4560       if (X) {
4561         Instruction *NewOp =
4562         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4563         return BinaryOperator::CreateAnd(NewOp, X);
4564       }
4565     }
4566   }
4567     
4568   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4569   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4570     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4571       return R;
4572
4573   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4574   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4575     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4576       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4577         const Type *SrcTy = Op0C->getOperand(0)->getType();
4578         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4579             // Only do this if the casts both really cause code to be generated.
4580             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4581                               I.getType(), TD) &&
4582             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4583                               I.getType(), TD)) {
4584           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
4585                                                          Op1C->getOperand(0),
4586                                                          I.getName());
4587           InsertNewInstBefore(NewOp, I);
4588           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4589         }
4590       }
4591   }
4592
4593   return Changed ? &I : 0;
4594 }
4595
4596 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4597 /// overflowed for this type.
4598 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4599                             ConstantInt *In2, bool IsSigned = false) {
4600   Result = cast<ConstantInt>(Add(In1, In2));
4601
4602   if (IsSigned)
4603     if (In2->getValue().isNegative())
4604       return Result->getValue().sgt(In1->getValue());
4605     else
4606       return Result->getValue().slt(In1->getValue());
4607   else
4608     return Result->getValue().ult(In1->getValue());
4609 }
4610
4611 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4612 /// code necessary to compute the offset from the base pointer (without adding
4613 /// in the base pointer).  Return the result as a signed integer of intptr size.
4614 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4615   TargetData &TD = IC.getTargetData();
4616   gep_type_iterator GTI = gep_type_begin(GEP);
4617   const Type *IntPtrTy = TD.getIntPtrType();
4618   Value *Result = Constant::getNullValue(IntPtrTy);
4619
4620   // Build a mask for high order bits.
4621   unsigned IntPtrWidth = TD.getPointerSizeInBits();
4622   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4623
4624   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
4625        ++i, ++GTI) {
4626     Value *Op = *i;
4627     uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
4628     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4629       if (OpC->isZero()) continue;
4630       
4631       // Handle a struct index, which adds its field offset to the pointer.
4632       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4633         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4634         
4635         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4636           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4637         else
4638           Result = IC.InsertNewInstBefore(
4639                    BinaryOperator::CreateAdd(Result,
4640                                              ConstantInt::get(IntPtrTy, Size),
4641                                              GEP->getName()+".offs"), I);
4642         continue;
4643       }
4644       
4645       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4646       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4647       Scale = ConstantExpr::getMul(OC, Scale);
4648       if (Constant *RC = dyn_cast<Constant>(Result))
4649         Result = ConstantExpr::getAdd(RC, Scale);
4650       else {
4651         // Emit an add instruction.
4652         Result = IC.InsertNewInstBefore(
4653            BinaryOperator::CreateAdd(Result, Scale,
4654                                      GEP->getName()+".offs"), I);
4655       }
4656       continue;
4657     }
4658     // Convert to correct type.
4659     if (Op->getType() != IntPtrTy) {
4660       if (Constant *OpC = dyn_cast<Constant>(Op))
4661         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4662       else
4663         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4664                                                  Op->getName()+".c"), I);
4665     }
4666     if (Size != 1) {
4667       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4668       if (Constant *OpC = dyn_cast<Constant>(Op))
4669         Op = ConstantExpr::getMul(OpC, Scale);
4670       else    // We'll let instcombine(mul) convert this to a shl if possible.
4671         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
4672                                                   GEP->getName()+".idx"), I);
4673     }
4674
4675     // Emit an add instruction.
4676     if (isa<Constant>(Op) && isa<Constant>(Result))
4677       Result = ConstantExpr::getAdd(cast<Constant>(Op),
4678                                     cast<Constant>(Result));
4679     else
4680       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
4681                                                   GEP->getName()+".offs"), I);
4682   }
4683   return Result;
4684 }
4685
4686
4687 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
4688 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
4689 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
4690 /// complex, and scales are involved.  The above expression would also be legal
4691 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
4692 /// later form is less amenable to optimization though, and we are allowed to
4693 /// generate the first by knowing that pointer arithmetic doesn't overflow.
4694 ///
4695 /// If we can't emit an optimized form for this expression, this returns null.
4696 /// 
4697 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
4698                                           InstCombiner &IC) {
4699   TargetData &TD = IC.getTargetData();
4700   gep_type_iterator GTI = gep_type_begin(GEP);
4701
4702   // Check to see if this gep only has a single variable index.  If so, and if
4703   // any constant indices are a multiple of its scale, then we can compute this
4704   // in terms of the scale of the variable index.  For example, if the GEP
4705   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
4706   // because the expression will cross zero at the same point.
4707   unsigned i, e = GEP->getNumOperands();
4708   int64_t Offset = 0;
4709   for (i = 1; i != e; ++i, ++GTI) {
4710     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4711       // Compute the aggregate offset of constant indices.
4712       if (CI->isZero()) continue;
4713
4714       // Handle a struct index, which adds its field offset to the pointer.
4715       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4716         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4717       } else {
4718         uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4719         Offset += Size*CI->getSExtValue();
4720       }
4721     } else {
4722       // Found our variable index.
4723       break;
4724     }
4725   }
4726   
4727   // If there are no variable indices, we must have a constant offset, just
4728   // evaluate it the general way.
4729   if (i == e) return 0;
4730   
4731   Value *VariableIdx = GEP->getOperand(i);
4732   // Determine the scale factor of the variable element.  For example, this is
4733   // 4 if the variable index is into an array of i32.
4734   uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
4735   
4736   // Verify that there are no other variable indices.  If so, emit the hard way.
4737   for (++i, ++GTI; i != e; ++i, ++GTI) {
4738     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
4739     if (!CI) return 0;
4740    
4741     // Compute the aggregate offset of constant indices.
4742     if (CI->isZero()) continue;
4743     
4744     // Handle a struct index, which adds its field offset to the pointer.
4745     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4746       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4747     } else {
4748       uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4749       Offset += Size*CI->getSExtValue();
4750     }
4751   }
4752   
4753   // Okay, we know we have a single variable index, which must be a
4754   // pointer/array/vector index.  If there is no offset, life is simple, return
4755   // the index.
4756   unsigned IntPtrWidth = TD.getPointerSizeInBits();
4757   if (Offset == 0) {
4758     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
4759     // we don't need to bother extending: the extension won't affect where the
4760     // computation crosses zero.
4761     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
4762       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
4763                                   VariableIdx->getNameStart(), &I);
4764     return VariableIdx;
4765   }
4766   
4767   // Otherwise, there is an index.  The computation we will do will be modulo
4768   // the pointer size, so get it.
4769   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4770   
4771   Offset &= PtrSizeMask;
4772   VariableScale &= PtrSizeMask;
4773
4774   // To do this transformation, any constant index must be a multiple of the
4775   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
4776   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
4777   // multiple of the variable scale.
4778   int64_t NewOffs = Offset / (int64_t)VariableScale;
4779   if (Offset != NewOffs*(int64_t)VariableScale)
4780     return 0;
4781
4782   // Okay, we can do this evaluation.  Start by converting the index to intptr.
4783   const Type *IntPtrTy = TD.getIntPtrType();
4784   if (VariableIdx->getType() != IntPtrTy)
4785     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
4786                                               true /*SExt*/, 
4787                                               VariableIdx->getNameStart(), &I);
4788   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
4789   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
4790 }
4791
4792
4793 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4794 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4795 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4796                                        ICmpInst::Predicate Cond,
4797                                        Instruction &I) {
4798   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4799
4800   // Look through bitcasts.
4801   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
4802     RHS = BCI->getOperand(0);
4803
4804   Value *PtrBase = GEPLHS->getOperand(0);
4805   if (PtrBase == RHS) {
4806     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4807     // This transformation (ignoring the base and scales) is valid because we
4808     // know pointers can't overflow.  See if we can output an optimized form.
4809     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
4810     
4811     // If not, synthesize the offset the hard way.
4812     if (Offset == 0)
4813       Offset = EmitGEPOffset(GEPLHS, I, *this);
4814     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4815                         Constant::getNullValue(Offset->getType()));
4816   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4817     // If the base pointers are different, but the indices are the same, just
4818     // compare the base pointer.
4819     if (PtrBase != GEPRHS->getOperand(0)) {
4820       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4821       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4822                         GEPRHS->getOperand(0)->getType();
4823       if (IndicesTheSame)
4824         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4825           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4826             IndicesTheSame = false;
4827             break;
4828           }
4829
4830       // If all indices are the same, just compare the base pointers.
4831       if (IndicesTheSame)
4832         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4833                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4834
4835       // Otherwise, the base pointers are different and the indices are
4836       // different, bail out.
4837       return 0;
4838     }
4839
4840     // If one of the GEPs has all zero indices, recurse.
4841     bool AllZeros = true;
4842     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4843       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4844           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4845         AllZeros = false;
4846         break;
4847       }
4848     if (AllZeros)
4849       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4850                           ICmpInst::getSwappedPredicate(Cond), I);
4851
4852     // If the other GEP has all zero indices, recurse.
4853     AllZeros = true;
4854     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4855       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4856           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4857         AllZeros = false;
4858         break;
4859       }
4860     if (AllZeros)
4861       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4862
4863     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4864       // If the GEPs only differ by one index, compare it.
4865       unsigned NumDifferences = 0;  // Keep track of # differences.
4866       unsigned DiffOperand = 0;     // The operand that differs.
4867       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4868         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4869           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4870                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4871             // Irreconcilable differences.
4872             NumDifferences = 2;
4873             break;
4874           } else {
4875             if (NumDifferences++) break;
4876             DiffOperand = i;
4877           }
4878         }
4879
4880       if (NumDifferences == 0)   // SAME GEP?
4881         return ReplaceInstUsesWith(I, // No comparison is needed here.
4882                                    ConstantInt::get(Type::Int1Ty,
4883                                              ICmpInst::isTrueWhenEqual(Cond)));
4884
4885       else if (NumDifferences == 1) {
4886         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4887         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4888         // Make sure we do a signed comparison here.
4889         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4890       }
4891     }
4892
4893     // Only lower this if the icmp is the only user of the GEP or if we expect
4894     // the result to fold to a constant!
4895     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4896         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4897       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4898       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4899       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4900       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4901     }
4902   }
4903   return 0;
4904 }
4905
4906 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
4907 ///
4908 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
4909                                                 Instruction *LHSI,
4910                                                 Constant *RHSC) {
4911   if (!isa<ConstantFP>(RHSC)) return 0;
4912   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
4913   
4914   // Get the width of the mantissa.  We don't want to hack on conversions that
4915   // might lose information from the integer, e.g. "i64 -> float"
4916   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
4917   if (MantissaWidth == -1) return 0;  // Unknown.
4918   
4919   // Check to see that the input is converted from an integer type that is small
4920   // enough that preserves all bits.  TODO: check here for "known" sign bits.
4921   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4922   unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
4923   
4924   // If this is a uitofp instruction, we need an extra bit to hold the sign.
4925   if (isa<UIToFPInst>(LHSI))
4926     ++InputSize;
4927   
4928   // If the conversion would lose info, don't hack on this.
4929   if ((int)InputSize > MantissaWidth)
4930     return 0;
4931   
4932   // Otherwise, we can potentially simplify the comparison.  We know that it
4933   // will always come through as an integer value and we know the constant is
4934   // not a NAN (it would have been previously simplified).
4935   assert(!RHS.isNaN() && "NaN comparison not already folded!");
4936   
4937   ICmpInst::Predicate Pred;
4938   switch (I.getPredicate()) {
4939   default: assert(0 && "Unexpected predicate!");
4940   case FCmpInst::FCMP_UEQ:
4941   case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
4942   case FCmpInst::FCMP_UGT:
4943   case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
4944   case FCmpInst::FCMP_UGE:
4945   case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
4946   case FCmpInst::FCMP_ULT:
4947   case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
4948   case FCmpInst::FCMP_ULE:
4949   case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
4950   case FCmpInst::FCMP_UNE:
4951   case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
4952   case FCmpInst::FCMP_ORD:
4953     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4954   case FCmpInst::FCMP_UNO:
4955     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4956   }
4957   
4958   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4959   
4960   // Now we know that the APFloat is a normal number, zero or inf.
4961   
4962   // See if the FP constant is too large for the integer.  For example,
4963   // comparing an i8 to 300.0.
4964   unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
4965   
4966   // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
4967   // and large values. 
4968   APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
4969   SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4970                         APFloat::rmNearestTiesToEven);
4971   if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
4972     if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4973         Pred == ICmpInst::ICMP_SLE)
4974       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4975     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4976   }
4977   
4978   // See if the RHS value is < SignedMin.
4979   APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
4980   SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4981                         APFloat::rmNearestTiesToEven);
4982   if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
4983     if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4984         Pred == ICmpInst::ICMP_SGE)
4985       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4986     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4987   }
4988
4989   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
4990   // it may still be fractional.  See if it is fractional by casting the FP
4991   // value to the integer value and back, checking for equality.  Don't do this
4992   // for zero, because -0.0 is not fractional.
4993   Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
4994   if (!RHS.isZero() &&
4995       ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
4996     // If we had a comparison against a fractional value, we have to adjust
4997     // the compare predicate and sometimes the value.  RHSC is rounded towards
4998     // zero at this point.
4999     switch (Pred) {
5000     default: assert(0 && "Unexpected integer comparison!");
5001     case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5002       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5003     case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5004       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5005     case ICmpInst::ICMP_SLE:
5006       // (float)int <= 4.4   --> int <= 4
5007       // (float)int <= -4.4  --> int < -4
5008       if (RHS.isNegative())
5009         Pred = ICmpInst::ICMP_SLT;
5010       break;
5011     case ICmpInst::ICMP_SLT:
5012       // (float)int < -4.4   --> int < -4
5013       // (float)int < 4.4    --> int <= 4
5014       if (!RHS.isNegative())
5015         Pred = ICmpInst::ICMP_SLE;
5016       break;
5017     case ICmpInst::ICMP_SGT:
5018       // (float)int > 4.4    --> int > 4
5019       // (float)int > -4.4   --> int >= -4
5020       if (RHS.isNegative())
5021         Pred = ICmpInst::ICMP_SGE;
5022       break;
5023     case ICmpInst::ICMP_SGE:
5024       // (float)int >= -4.4   --> int >= -4
5025       // (float)int >= 4.4    --> int > 4
5026       if (!RHS.isNegative())
5027         Pred = ICmpInst::ICMP_SGT;
5028       break;
5029     }
5030   }
5031
5032   // Lower this FP comparison into an appropriate integer version of the
5033   // comparison.
5034   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5035 }
5036
5037 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5038   bool Changed = SimplifyCompare(I);
5039   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5040
5041   // Fold trivial predicates.
5042   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5043     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5044   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5045     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5046   
5047   // Simplify 'fcmp pred X, X'
5048   if (Op0 == Op1) {
5049     switch (I.getPredicate()) {
5050     default: assert(0 && "Unknown predicate!");
5051     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5052     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5053     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5054       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5055     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5056     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5057     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5058       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5059       
5060     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5061     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5062     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5063     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5064       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5065       I.setPredicate(FCmpInst::FCMP_UNO);
5066       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5067       return &I;
5068       
5069     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5070     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5071     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5072     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5073       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5074       I.setPredicate(FCmpInst::FCMP_ORD);
5075       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5076       return &I;
5077     }
5078   }
5079     
5080   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5081     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5082
5083   // Handle fcmp with constant RHS
5084   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5085     // If the constant is a nan, see if we can fold the comparison based on it.
5086     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5087       if (CFP->getValueAPF().isNaN()) {
5088         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5089           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5090         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5091                "Comparison must be either ordered or unordered!");
5092         // True if unordered.
5093         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5094       }
5095     }
5096     
5097     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5098       switch (LHSI->getOpcode()) {
5099       case Instruction::PHI:
5100         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5101         // block.  If in the same block, we're encouraging jump threading.  If
5102         // not, we are just pessimizing the code by making an i1 phi.
5103         if (LHSI->getParent() == I.getParent())
5104           if (Instruction *NV = FoldOpIntoPhi(I))
5105             return NV;
5106         break;
5107       case Instruction::SIToFP:
5108       case Instruction::UIToFP:
5109         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5110           return NV;
5111         break;
5112       case Instruction::Select:
5113         // If either operand of the select is a constant, we can fold the
5114         // comparison into the select arms, which will cause one to be
5115         // constant folded and the select turned into a bitwise or.
5116         Value *Op1 = 0, *Op2 = 0;
5117         if (LHSI->hasOneUse()) {
5118           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5119             // Fold the known value into the constant operand.
5120             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5121             // Insert a new FCmp of the other select operand.
5122             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5123                                                       LHSI->getOperand(2), RHSC,
5124                                                       I.getName()), I);
5125           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5126             // Fold the known value into the constant operand.
5127             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5128             // Insert a new FCmp of the other select operand.
5129             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5130                                                       LHSI->getOperand(1), RHSC,
5131                                                       I.getName()), I);
5132           }
5133         }
5134
5135         if (Op1)
5136           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5137         break;
5138       }
5139   }
5140
5141   return Changed ? &I : 0;
5142 }
5143
5144 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5145   bool Changed = SimplifyCompare(I);
5146   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5147   const Type *Ty = Op0->getType();
5148
5149   // icmp X, X
5150   if (Op0 == Op1)
5151     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5152                                                    I.isTrueWhenEqual()));
5153
5154   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5155     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5156   
5157   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5158   // addresses never equal each other!  We already know that Op0 != Op1.
5159   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5160        isa<ConstantPointerNull>(Op0)) &&
5161       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5162        isa<ConstantPointerNull>(Op1)))
5163     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5164                                                    !I.isTrueWhenEqual()));
5165
5166   // icmp's with boolean values can always be turned into bitwise operations
5167   if (Ty == Type::Int1Ty) {
5168     switch (I.getPredicate()) {
5169     default: assert(0 && "Invalid icmp instruction!");
5170     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5171       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5172       InsertNewInstBefore(Xor, I);
5173       return BinaryOperator::CreateNot(Xor);
5174     }
5175     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5176       return BinaryOperator::CreateXor(Op0, Op1);
5177
5178     case ICmpInst::ICMP_UGT:
5179       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5180       // FALL THROUGH
5181     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5182       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5183       InsertNewInstBefore(Not, I);
5184       return BinaryOperator::CreateAnd(Not, Op1);
5185     }
5186     case ICmpInst::ICMP_SGT:
5187       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5188       // FALL THROUGH
5189     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5190       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5191       InsertNewInstBefore(Not, I);
5192       return BinaryOperator::CreateAnd(Not, Op0);
5193     }
5194     case ICmpInst::ICMP_UGE:
5195       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
5196       // FALL THROUGH
5197     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
5198       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5199       InsertNewInstBefore(Not, I);
5200       return BinaryOperator::CreateOr(Not, Op1);
5201     }
5202     case ICmpInst::ICMP_SGE:
5203       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
5204       // FALL THROUGH
5205     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
5206       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5207       InsertNewInstBefore(Not, I);
5208       return BinaryOperator::CreateOr(Not, Op0);
5209     }
5210     }
5211   }
5212
5213   // See if we are doing a comparison between a constant and an instruction that
5214   // can be folded into the comparison.
5215   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5216     Value *A, *B;
5217     
5218     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5219     if (I.isEquality() && CI->isNullValue() &&
5220         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5221       // (icmp cond A B) if cond is equality
5222       return new ICmpInst(I.getPredicate(), A, B);
5223     }
5224     
5225     // If we have a icmp le or icmp ge instruction, turn it into the appropriate
5226     // icmp lt or icmp gt instruction.  This allows us to rely on them being
5227     // folded in the code below.
5228     switch (I.getPredicate()) {
5229     default: break;
5230     case ICmpInst::ICMP_ULE:
5231       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5232         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5233       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5234     case ICmpInst::ICMP_SLE:
5235       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5236         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5237       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5238     case ICmpInst::ICMP_UGE:
5239       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5240         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5241       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5242     case ICmpInst::ICMP_SGE:
5243       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5244         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5245       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5246     }
5247     
5248     // See if we can fold the comparison based on range information we can get
5249     // by checking whether bits are known to be zero or one in the input.
5250     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5251     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5252     
5253     // If this comparison is a normal comparison, it demands all
5254     // bits, if it is a sign bit comparison, it only demands the sign bit.
5255     bool UnusedBit;
5256     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5257     
5258     if (SimplifyDemandedBits(Op0, 
5259                              isSignBit ? APInt::getSignBit(BitWidth)
5260                                        : APInt::getAllOnesValue(BitWidth),
5261                              KnownZero, KnownOne, 0))
5262       return &I;
5263         
5264     // Given the known and unknown bits, compute a range that the LHS could be
5265     // in.  Compute the Min, Max and RHS values based on the known bits. For the
5266     // EQ and NE we use unsigned values.
5267     APInt Min(BitWidth, 0), Max(BitWidth, 0);
5268     if (ICmpInst::isSignedPredicate(I.getPredicate()))
5269       ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5270     else
5271       ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5272     
5273     // If Min and Max are known to be the same, then SimplifyDemandedBits
5274     // figured out that the LHS is a constant.  Just constant fold this now so
5275     // that code below can assume that Min != Max.
5276     if (Min == Max)
5277       return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5278                                                           ConstantInt::get(Min),
5279                                                           CI));
5280     
5281     // Based on the range information we know about the LHS, see if we can
5282     // simplify this comparison.  For example, (x&4) < 8  is always true.
5283     const APInt &RHSVal = CI->getValue();
5284     switch (I.getPredicate()) {  // LE/GE have been folded already.
5285     default: assert(0 && "Unknown icmp opcode!");
5286     case ICmpInst::ICMP_EQ:
5287       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5288         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5289       break;
5290     case ICmpInst::ICMP_NE:
5291       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5292         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5293       break;
5294     case ICmpInst::ICMP_ULT:
5295       if (Max.ult(RHSVal))                    // A <u C -> true iff max(A) < C
5296         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5297       if (Min.uge(RHSVal))                    // A <u C -> false iff min(A) >= C
5298         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5299       if (RHSVal == Max)                      // A <u MAX -> A != MAX
5300         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5301       if (RHSVal == Min+1)                    // A <u MIN+1 -> A == MIN
5302         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5303         
5304       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
5305       if (CI->isMinValue(true))
5306         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5307                             ConstantInt::getAllOnesValue(Op0->getType()));
5308       break;
5309     case ICmpInst::ICMP_UGT:
5310       if (Min.ugt(RHSVal))                    // A >u C -> true iff min(A) > C
5311         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5312       if (Max.ule(RHSVal))                    // A >u C -> false iff max(A) <= C
5313         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5314         
5315       if (RHSVal == Min)                      // A >u MIN -> A != MIN
5316         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5317       if (RHSVal == Max-1)                    // A >u MAX-1 -> A == MAX
5318         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5319       
5320       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
5321       if (CI->isMaxValue(true))
5322         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5323                             ConstantInt::getNullValue(Op0->getType()));
5324       break;
5325     case ICmpInst::ICMP_SLT:
5326       if (Max.slt(RHSVal))                    // A <s C -> true iff max(A) < C
5327         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5328       if (Min.sge(RHSVal))                    // A <s C -> false iff min(A) >= C
5329         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5330       if (RHSVal == Max)                      // A <s MAX -> A != MAX
5331         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5332       if (RHSVal == Min+1)                    // A <s MIN+1 -> A == MIN
5333         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5334       break;
5335     case ICmpInst::ICMP_SGT: 
5336       if (Min.sgt(RHSVal))                    // A >s C -> true iff min(A) > C
5337         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5338       if (Max.sle(RHSVal))                    // A >s C -> false iff max(A) <= C
5339         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5340         
5341       if (RHSVal == Min)                      // A >s MIN -> A != MIN
5342         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5343       if (RHSVal == Max-1)                    // A >s MAX-1 -> A == MAX
5344         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5345       break;
5346     }
5347           
5348     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5349     // instruction, see if that instruction also has constants so that the 
5350     // instruction can be folded into the icmp 
5351     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5352       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5353         return Res;
5354   }
5355
5356   // Handle icmp with constant (but not simple integer constant) RHS
5357   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5358     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5359       switch (LHSI->getOpcode()) {
5360       case Instruction::GetElementPtr:
5361         if (RHSC->isNullValue()) {
5362           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5363           bool isAllZeros = true;
5364           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5365             if (!isa<Constant>(LHSI->getOperand(i)) ||
5366                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5367               isAllZeros = false;
5368               break;
5369             }
5370           if (isAllZeros)
5371             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5372                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5373         }
5374         break;
5375
5376       case Instruction::PHI:
5377         // Only fold icmp into the PHI if the phi and fcmp are in the same
5378         // block.  If in the same block, we're encouraging jump threading.  If
5379         // not, we are just pessimizing the code by making an i1 phi.
5380         if (LHSI->getParent() == I.getParent())
5381           if (Instruction *NV = FoldOpIntoPhi(I))
5382             return NV;
5383         break;
5384       case Instruction::Select: {
5385         // If either operand of the select is a constant, we can fold the
5386         // comparison into the select arms, which will cause one to be
5387         // constant folded and the select turned into a bitwise or.
5388         Value *Op1 = 0, *Op2 = 0;
5389         if (LHSI->hasOneUse()) {
5390           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5391             // Fold the known value into the constant operand.
5392             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5393             // Insert a new ICmp of the other select operand.
5394             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5395                                                    LHSI->getOperand(2), RHSC,
5396                                                    I.getName()), I);
5397           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5398             // Fold the known value into the constant operand.
5399             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5400             // Insert a new ICmp of the other select operand.
5401             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5402                                                    LHSI->getOperand(1), RHSC,
5403                                                    I.getName()), I);
5404           }
5405         }
5406
5407         if (Op1)
5408           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5409         break;
5410       }
5411       case Instruction::Malloc:
5412         // If we have (malloc != null), and if the malloc has a single use, we
5413         // can assume it is successful and remove the malloc.
5414         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5415           AddToWorkList(LHSI);
5416           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5417                                                          !I.isTrueWhenEqual()));
5418         }
5419         break;
5420       }
5421   }
5422
5423   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5424   if (User *GEP = dyn_castGetElementPtr(Op0))
5425     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5426       return NI;
5427   if (User *GEP = dyn_castGetElementPtr(Op1))
5428     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5429                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5430       return NI;
5431
5432   // Test to see if the operands of the icmp are casted versions of other
5433   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5434   // now.
5435   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5436     if (isa<PointerType>(Op0->getType()) && 
5437         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5438       // We keep moving the cast from the left operand over to the right
5439       // operand, where it can often be eliminated completely.
5440       Op0 = CI->getOperand(0);
5441
5442       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5443       // so eliminate it as well.
5444       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5445         Op1 = CI2->getOperand(0);
5446
5447       // If Op1 is a constant, we can fold the cast into the constant.
5448       if (Op0->getType() != Op1->getType()) {
5449         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5450           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5451         } else {
5452           // Otherwise, cast the RHS right before the icmp
5453           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
5454         }
5455       }
5456       return new ICmpInst(I.getPredicate(), Op0, Op1);
5457     }
5458   }
5459   
5460   if (isa<CastInst>(Op0)) {
5461     // Handle the special case of: icmp (cast bool to X), <cst>
5462     // This comes up when you have code like
5463     //   int X = A < B;
5464     //   if (X) ...
5465     // For generality, we handle any zero-extension of any operand comparison
5466     // with a constant or another cast from the same type.
5467     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5468       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5469         return R;
5470   }
5471   
5472   // See if it's the same type of instruction on the left and right.
5473   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5474     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
5475       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
5476           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1) &&
5477           I.isEquality()) {
5478         switch (Op0I->getOpcode()) {
5479         default: break;
5480         case Instruction::Add:
5481         case Instruction::Sub:
5482         case Instruction::Xor:
5483           // a+x icmp eq/ne b+x --> a icmp b
5484           return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
5485                               Op1I->getOperand(0));
5486           break;
5487         case Instruction::Mul:
5488           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5489             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
5490             // Mask = -1 >> count-trailing-zeros(Cst).
5491             if (!CI->isZero() && !CI->isOne()) {
5492               const APInt &AP = CI->getValue();
5493               ConstantInt *Mask = ConstantInt::get(
5494                                       APInt::getLowBitsSet(AP.getBitWidth(),
5495                                                            AP.getBitWidth() -
5496                                                       AP.countTrailingZeros()));
5497               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
5498                                                             Mask);
5499               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
5500                                                             Mask);
5501               InsertNewInstBefore(And1, I);
5502               InsertNewInstBefore(And2, I);
5503               return new ICmpInst(I.getPredicate(), And1, And2);
5504             }
5505           }
5506           break;
5507         }
5508       }
5509     }
5510   }
5511   
5512   // ~x < ~y --> y < x
5513   { Value *A, *B;
5514     if (match(Op0, m_Not(m_Value(A))) &&
5515         match(Op1, m_Not(m_Value(B))))
5516       return new ICmpInst(I.getPredicate(), B, A);
5517   }
5518   
5519   if (I.isEquality()) {
5520     Value *A, *B, *C, *D;
5521     
5522     // -x == -y --> x == y
5523     if (match(Op0, m_Neg(m_Value(A))) &&
5524         match(Op1, m_Neg(m_Value(B))))
5525       return new ICmpInst(I.getPredicate(), A, B);
5526     
5527     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5528       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
5529         Value *OtherVal = A == Op1 ? B : A;
5530         return new ICmpInst(I.getPredicate(), OtherVal,
5531                             Constant::getNullValue(A->getType()));
5532       }
5533
5534       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5535         // A^c1 == C^c2 --> A == C^(c1^c2)
5536         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5537           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5538             if (Op1->hasOneUse()) {
5539               Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
5540               Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
5541               return new ICmpInst(I.getPredicate(), A,
5542                                   InsertNewInstBefore(Xor, I));
5543             }
5544         
5545         // A^B == A^D -> B == D
5546         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5547         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5548         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5549         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5550       }
5551     }
5552     
5553     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5554         (A == Op0 || B == Op0)) {
5555       // A == (A^B)  ->  B == 0
5556       Value *OtherVal = A == Op0 ? B : A;
5557       return new ICmpInst(I.getPredicate(), OtherVal,
5558                           Constant::getNullValue(A->getType()));
5559     }
5560     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5561       // (A-B) == A  ->  B == 0
5562       return new ICmpInst(I.getPredicate(), B,
5563                           Constant::getNullValue(B->getType()));
5564     }
5565     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5566       // A == (A-B)  ->  B == 0
5567       return new ICmpInst(I.getPredicate(), B,
5568                           Constant::getNullValue(B->getType()));
5569     }
5570     
5571     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5572     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5573         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5574         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5575       Value *X = 0, *Y = 0, *Z = 0;
5576       
5577       if (A == C) {
5578         X = B; Y = D; Z = A;
5579       } else if (A == D) {
5580         X = B; Y = C; Z = A;
5581       } else if (B == C) {
5582         X = A; Y = D; Z = B;
5583       } else if (B == D) {
5584         X = A; Y = C; Z = B;
5585       }
5586       
5587       if (X) {   // Build (X^Y) & Z
5588         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5589         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
5590         I.setOperand(0, Op1);
5591         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5592         return &I;
5593       }
5594     }
5595   }
5596   return Changed ? &I : 0;
5597 }
5598
5599
5600 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5601 /// and CmpRHS are both known to be integer constants.
5602 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5603                                           ConstantInt *DivRHS) {
5604   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5605   const APInt &CmpRHSV = CmpRHS->getValue();
5606   
5607   // FIXME: If the operand types don't match the type of the divide 
5608   // then don't attempt this transform. The code below doesn't have the
5609   // logic to deal with a signed divide and an unsigned compare (and
5610   // vice versa). This is because (x /s C1) <s C2  produces different 
5611   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5612   // (x /u C1) <u C2.  Simply casting the operands and result won't 
5613   // work. :(  The if statement below tests that condition and bails 
5614   // if it finds it. 
5615   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5616   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5617     return 0;
5618   if (DivRHS->isZero())
5619     return 0; // The ProdOV computation fails on divide by zero.
5620
5621   // Compute Prod = CI * DivRHS. We are essentially solving an equation
5622   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
5623   // C2 (CI). By solving for X we can turn this into a range check 
5624   // instead of computing a divide. 
5625   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5626
5627   // Determine if the product overflows by seeing if the product is
5628   // not equal to the divide. Make sure we do the same kind of divide
5629   // as in the LHS instruction that we're folding. 
5630   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5631                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5632
5633   // Get the ICmp opcode
5634   ICmpInst::Predicate Pred = ICI.getPredicate();
5635
5636   // Figure out the interval that is being checked.  For example, a comparison
5637   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
5638   // Compute this interval based on the constants involved and the signedness of
5639   // the compare/divide.  This computes a half-open interval, keeping track of
5640   // whether either value in the interval overflows.  After analysis each
5641   // overflow variable is set to 0 if it's corresponding bound variable is valid
5642   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5643   int LoOverflow = 0, HiOverflow = 0;
5644   ConstantInt *LoBound = 0, *HiBound = 0;
5645   
5646   
5647   if (!DivIsSigned) {  // udiv
5648     // e.g. X/5 op 3  --> [15, 20)
5649     LoBound = Prod;
5650     HiOverflow = LoOverflow = ProdOV;
5651     if (!HiOverflow)
5652       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
5653   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
5654     if (CmpRHSV == 0) {       // (X / pos) op 0
5655       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
5656       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5657       HiBound = DivRHS;
5658     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
5659       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
5660       HiOverflow = LoOverflow = ProdOV;
5661       if (!HiOverflow)
5662         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5663     } else {                       // (X / pos) op neg
5664       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
5665       Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5666       LoOverflow = AddWithOverflow(LoBound, Prod,
5667                                    cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5668       HiBound = AddOne(Prod);
5669       HiOverflow = ProdOV ? -1 : 0;
5670     }
5671   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
5672     if (CmpRHSV == 0) {       // (X / neg) op 0
5673       // e.g. X/-5 op 0  --> [-4, 5)
5674       LoBound = AddOne(DivRHS);
5675       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5676       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
5677         HiOverflow = 1;            // [INTMIN+1, overflow)
5678         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
5679       }
5680     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
5681       // e.g. X/-5 op 3  --> [-19, -14)
5682       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5683       if (!LoOverflow)
5684         LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5685       HiBound = AddOne(Prod);
5686     } else {                       // (X / neg) op neg
5687       // e.g. X/-5 op -3  --> [15, 20)
5688       LoBound = Prod;
5689       LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5690       HiBound = Subtract(Prod, DivRHS);
5691     }
5692     
5693     // Dividing by a negative swaps the condition.  LT <-> GT
5694     Pred = ICmpInst::getSwappedPredicate(Pred);
5695   }
5696
5697   Value *X = DivI->getOperand(0);
5698   switch (Pred) {
5699   default: assert(0 && "Unhandled icmp opcode!");
5700   case ICmpInst::ICMP_EQ:
5701     if (LoOverflow && HiOverflow)
5702       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5703     else if (HiOverflow)
5704       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5705                           ICmpInst::ICMP_UGE, X, LoBound);
5706     else if (LoOverflow)
5707       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5708                           ICmpInst::ICMP_ULT, X, HiBound);
5709     else
5710       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5711   case ICmpInst::ICMP_NE:
5712     if (LoOverflow && HiOverflow)
5713       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5714     else if (HiOverflow)
5715       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5716                           ICmpInst::ICMP_ULT, X, LoBound);
5717     else if (LoOverflow)
5718       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5719                           ICmpInst::ICMP_UGE, X, HiBound);
5720     else
5721       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5722   case ICmpInst::ICMP_ULT:
5723   case ICmpInst::ICMP_SLT:
5724     if (LoOverflow == +1)   // Low bound is greater than input range.
5725       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5726     if (LoOverflow == -1)   // Low bound is less than input range.
5727       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5728     return new ICmpInst(Pred, X, LoBound);
5729   case ICmpInst::ICMP_UGT:
5730   case ICmpInst::ICMP_SGT:
5731     if (HiOverflow == +1)       // High bound greater than input range.
5732       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5733     else if (HiOverflow == -1)  // High bound less than input range.
5734       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5735     if (Pred == ICmpInst::ICMP_UGT)
5736       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5737     else
5738       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5739   }
5740 }
5741
5742
5743 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5744 ///
5745 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5746                                                           Instruction *LHSI,
5747                                                           ConstantInt *RHS) {
5748   const APInt &RHSV = RHS->getValue();
5749   
5750   switch (LHSI->getOpcode()) {
5751   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
5752     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5753       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5754       // fold the xor.
5755       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5756           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
5757         Value *CompareVal = LHSI->getOperand(0);
5758         
5759         // If the sign bit of the XorCST is not set, there is no change to
5760         // the operation, just stop using the Xor.
5761         if (!XorCST->getValue().isNegative()) {
5762           ICI.setOperand(0, CompareVal);
5763           AddToWorkList(LHSI);
5764           return &ICI;
5765         }
5766         
5767         // Was the old condition true if the operand is positive?
5768         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5769         
5770         // If so, the new one isn't.
5771         isTrueIfPositive ^= true;
5772         
5773         if (isTrueIfPositive)
5774           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5775         else
5776           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5777       }
5778     }
5779     break;
5780   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
5781     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5782         LHSI->getOperand(0)->hasOneUse()) {
5783       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5784       
5785       // If the LHS is an AND of a truncating cast, we can widen the
5786       // and/compare to be the input width without changing the value
5787       // produced, eliminating a cast.
5788       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5789         // We can do this transformation if either the AND constant does not
5790         // have its sign bit set or if it is an equality comparison. 
5791         // Extending a relational comparison when we're checking the sign
5792         // bit would not work.
5793         if (Cast->hasOneUse() &&
5794             (ICI.isEquality() ||
5795              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
5796           uint32_t BitWidth = 
5797             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5798           APInt NewCST = AndCST->getValue();
5799           NewCST.zext(BitWidth);
5800           APInt NewCI = RHSV;
5801           NewCI.zext(BitWidth);
5802           Instruction *NewAnd = 
5803             BinaryOperator::CreateAnd(Cast->getOperand(0),
5804                                       ConstantInt::get(NewCST),LHSI->getName());
5805           InsertNewInstBefore(NewAnd, ICI);
5806           return new ICmpInst(ICI.getPredicate(), NewAnd,
5807                               ConstantInt::get(NewCI));
5808         }
5809       }
5810       
5811       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5812       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
5813       // happens a LOT in code produced by the C front-end, for bitfield
5814       // access.
5815       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5816       if (Shift && !Shift->isShift())
5817         Shift = 0;
5818       
5819       ConstantInt *ShAmt;
5820       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5821       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
5822       const Type *AndTy = AndCST->getType();          // Type of the and.
5823       
5824       // We can fold this as long as we can't shift unknown bits
5825       // into the mask.  This can only happen with signed shift
5826       // rights, as they sign-extend.
5827       if (ShAmt) {
5828         bool CanFold = Shift->isLogicalShift();
5829         if (!CanFold) {
5830           // To test for the bad case of the signed shr, see if any
5831           // of the bits shifted in could be tested after the mask.
5832           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5833           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5834           
5835           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5836           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
5837                AndCST->getValue()) == 0)
5838             CanFold = true;
5839         }
5840         
5841         if (CanFold) {
5842           Constant *NewCst;
5843           if (Shift->getOpcode() == Instruction::Shl)
5844             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5845           else
5846             NewCst = ConstantExpr::getShl(RHS, ShAmt);
5847           
5848           // Check to see if we are shifting out any of the bits being
5849           // compared.
5850           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5851             // If we shifted bits out, the fold is not going to work out.
5852             // As a special case, check to see if this means that the
5853             // result is always true or false now.
5854             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5855               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5856             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5857               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5858           } else {
5859             ICI.setOperand(1, NewCst);
5860             Constant *NewAndCST;
5861             if (Shift->getOpcode() == Instruction::Shl)
5862               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5863             else
5864               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5865             LHSI->setOperand(1, NewAndCST);
5866             LHSI->setOperand(0, Shift->getOperand(0));
5867             AddToWorkList(Shift); // Shift is dead.
5868             AddUsesToWorkList(ICI);
5869             return &ICI;
5870           }
5871         }
5872       }
5873       
5874       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
5875       // preferable because it allows the C<<Y expression to be hoisted out
5876       // of a loop if Y is invariant and X is not.
5877       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5878           ICI.isEquality() && !Shift->isArithmeticShift() &&
5879           isa<Instruction>(Shift->getOperand(0))) {
5880         // Compute C << Y.
5881         Value *NS;
5882         if (Shift->getOpcode() == Instruction::LShr) {
5883           NS = BinaryOperator::CreateShl(AndCST, 
5884                                          Shift->getOperand(1), "tmp");
5885         } else {
5886           // Insert a logical shift.
5887           NS = BinaryOperator::CreateLShr(AndCST,
5888                                           Shift->getOperand(1), "tmp");
5889         }
5890         InsertNewInstBefore(cast<Instruction>(NS), ICI);
5891         
5892         // Compute X & (C << Y).
5893         Instruction *NewAnd = 
5894           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
5895         InsertNewInstBefore(NewAnd, ICI);
5896         
5897         ICI.setOperand(0, NewAnd);
5898         return &ICI;
5899       }
5900     }
5901     break;
5902     
5903   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
5904     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5905     if (!ShAmt) break;
5906     
5907     uint32_t TypeBits = RHSV.getBitWidth();
5908     
5909     // Check that the shift amount is in range.  If not, don't perform
5910     // undefined shifts.  When the shift is visited it will be
5911     // simplified.
5912     if (ShAmt->uge(TypeBits))
5913       break;
5914     
5915     if (ICI.isEquality()) {
5916       // If we are comparing against bits always shifted out, the
5917       // comparison cannot succeed.
5918       Constant *Comp =
5919         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5920       if (Comp != RHS) {// Comparing against a bit that we know is zero.
5921         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5922         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5923         return ReplaceInstUsesWith(ICI, Cst);
5924       }
5925       
5926       if (LHSI->hasOneUse()) {
5927         // Otherwise strength reduce the shift into an and.
5928         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5929         Constant *Mask =
5930           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5931         
5932         Instruction *AndI =
5933           BinaryOperator::CreateAnd(LHSI->getOperand(0),
5934                                     Mask, LHSI->getName()+".mask");
5935         Value *And = InsertNewInstBefore(AndI, ICI);
5936         return new ICmpInst(ICI.getPredicate(), And,
5937                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
5938       }
5939     }
5940     
5941     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5942     bool TrueIfSigned = false;
5943     if (LHSI->hasOneUse() &&
5944         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5945       // (X << 31) <s 0  --> (X&1) != 0
5946       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5947                                            (TypeBits-ShAmt->getZExtValue()-1));
5948       Instruction *AndI =
5949         BinaryOperator::CreateAnd(LHSI->getOperand(0),
5950                                   Mask, LHSI->getName()+".mask");
5951       Value *And = InsertNewInstBefore(AndI, ICI);
5952       
5953       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5954                           And, Constant::getNullValue(And->getType()));
5955     }
5956     break;
5957   }
5958     
5959   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
5960   case Instruction::AShr: {
5961     // Only handle equality comparisons of shift-by-constant.
5962     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5963     if (!ShAmt || !ICI.isEquality()) break;
5964
5965     // Check that the shift amount is in range.  If not, don't perform
5966     // undefined shifts.  When the shift is visited it will be
5967     // simplified.
5968     uint32_t TypeBits = RHSV.getBitWidth();
5969     if (ShAmt->uge(TypeBits))
5970       break;
5971     
5972     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5973       
5974     // If we are comparing against bits always shifted out, the
5975     // comparison cannot succeed.
5976     APInt Comp = RHSV << ShAmtVal;
5977     if (LHSI->getOpcode() == Instruction::LShr)
5978       Comp = Comp.lshr(ShAmtVal);
5979     else
5980       Comp = Comp.ashr(ShAmtVal);
5981     
5982     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5983       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5984       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5985       return ReplaceInstUsesWith(ICI, Cst);
5986     }
5987     
5988     // Otherwise, check to see if the bits shifted out are known to be zero.
5989     // If so, we can compare against the unshifted value:
5990     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
5991     if (LHSI->hasOneUse() &&
5992         MaskedValueIsZero(LHSI->getOperand(0), 
5993                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
5994       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
5995                           ConstantExpr::getShl(RHS, ShAmt));
5996     }
5997       
5998     if (LHSI->hasOneUse()) {
5999       // Otherwise strength reduce the shift into an and.
6000       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6001       Constant *Mask = ConstantInt::get(Val);
6002       
6003       Instruction *AndI =
6004         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6005                                   Mask, LHSI->getName()+".mask");
6006       Value *And = InsertNewInstBefore(AndI, ICI);
6007       return new ICmpInst(ICI.getPredicate(), And,
6008                           ConstantExpr::getShl(RHS, ShAmt));
6009     }
6010     break;
6011   }
6012     
6013   case Instruction::SDiv:
6014   case Instruction::UDiv:
6015     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6016     // Fold this div into the comparison, producing a range check. 
6017     // Determine, based on the divide type, what the range is being 
6018     // checked.  If there is an overflow on the low or high side, remember 
6019     // it, otherwise compute the range [low, hi) bounding the new value.
6020     // See: InsertRangeTest above for the kinds of replacements possible.
6021     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6022       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6023                                           DivRHS))
6024         return R;
6025     break;
6026
6027   case Instruction::Add:
6028     // Fold: icmp pred (add, X, C1), C2
6029
6030     if (!ICI.isEquality()) {
6031       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6032       if (!LHSC) break;
6033       const APInt &LHSV = LHSC->getValue();
6034
6035       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6036                             .subtract(LHSV);
6037
6038       if (ICI.isSignedPredicate()) {
6039         if (CR.getLower().isSignBit()) {
6040           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6041                               ConstantInt::get(CR.getUpper()));
6042         } else if (CR.getUpper().isSignBit()) {
6043           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6044                               ConstantInt::get(CR.getLower()));
6045         }
6046       } else {
6047         if (CR.getLower().isMinValue()) {
6048           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6049                               ConstantInt::get(CR.getUpper()));
6050         } else if (CR.getUpper().isMinValue()) {
6051           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6052                               ConstantInt::get(CR.getLower()));
6053         }
6054       }
6055     }
6056     break;
6057   }
6058   
6059   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6060   if (ICI.isEquality()) {
6061     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6062     
6063     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6064     // the second operand is a constant, simplify a bit.
6065     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6066       switch (BO->getOpcode()) {
6067       case Instruction::SRem:
6068         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6069         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6070           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6071           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6072             Instruction *NewRem =
6073               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6074                                          BO->getName());
6075             InsertNewInstBefore(NewRem, ICI);
6076             return new ICmpInst(ICI.getPredicate(), NewRem, 
6077                                 Constant::getNullValue(BO->getType()));
6078           }
6079         }
6080         break;
6081       case Instruction::Add:
6082         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6083         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6084           if (BO->hasOneUse())
6085             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6086                                 Subtract(RHS, BOp1C));
6087         } else if (RHSV == 0) {
6088           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6089           // efficiently invertible, or if the add has just this one use.
6090           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6091           
6092           if (Value *NegVal = dyn_castNegVal(BOp1))
6093             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6094           else if (Value *NegVal = dyn_castNegVal(BOp0))
6095             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6096           else if (BO->hasOneUse()) {
6097             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6098             InsertNewInstBefore(Neg, ICI);
6099             Neg->takeName(BO);
6100             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6101           }
6102         }
6103         break;
6104       case Instruction::Xor:
6105         // For the xor case, we can xor two constants together, eliminating
6106         // the explicit xor.
6107         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6108           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6109                               ConstantExpr::getXor(RHS, BOC));
6110         
6111         // FALLTHROUGH
6112       case Instruction::Sub:
6113         // Replace (([sub|xor] A, B) != 0) with (A != B)
6114         if (RHSV == 0)
6115           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6116                               BO->getOperand(1));
6117         break;
6118         
6119       case Instruction::Or:
6120         // If bits are being or'd in that are not present in the constant we
6121         // are comparing against, then the comparison could never succeed!
6122         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6123           Constant *NotCI = ConstantExpr::getNot(RHS);
6124           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6125             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
6126                                                              isICMP_NE));
6127         }
6128         break;
6129         
6130       case Instruction::And:
6131         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6132           // If bits are being compared against that are and'd out, then the
6133           // comparison can never succeed!
6134           if ((RHSV & ~BOC->getValue()) != 0)
6135             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6136                                                              isICMP_NE));
6137           
6138           // If we have ((X & C) == C), turn it into ((X & C) != 0).
6139           if (RHS == BOC && RHSV.isPowerOf2())
6140             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6141                                 ICmpInst::ICMP_NE, LHSI,
6142                                 Constant::getNullValue(RHS->getType()));
6143           
6144           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6145           if (BOC->getValue().isSignBit()) {
6146             Value *X = BO->getOperand(0);
6147             Constant *Zero = Constant::getNullValue(X->getType());
6148             ICmpInst::Predicate pred = isICMP_NE ? 
6149               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6150             return new ICmpInst(pred, X, Zero);
6151           }
6152           
6153           // ((X & ~7) == 0) --> X < 8
6154           if (RHSV == 0 && isHighOnes(BOC)) {
6155             Value *X = BO->getOperand(0);
6156             Constant *NegX = ConstantExpr::getNeg(BOC);
6157             ICmpInst::Predicate pred = isICMP_NE ? 
6158               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6159             return new ICmpInst(pred, X, NegX);
6160           }
6161         }
6162       default: break;
6163       }
6164     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6165       // Handle icmp {eq|ne} <intrinsic>, intcst.
6166       if (II->getIntrinsicID() == Intrinsic::bswap) {
6167         AddToWorkList(II);
6168         ICI.setOperand(0, II->getOperand(1));
6169         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6170         return &ICI;
6171       }
6172     }
6173   } else {  // Not a ICMP_EQ/ICMP_NE
6174             // If the LHS is a cast from an integral value of the same size, 
6175             // then since we know the RHS is a constant, try to simlify.
6176     if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6177       Value *CastOp = Cast->getOperand(0);
6178       const Type *SrcTy = CastOp->getType();
6179       uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6180       if (SrcTy->isInteger() && 
6181           SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6182         // If this is an unsigned comparison, try to make the comparison use
6183         // smaller constant values.
6184         if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6185           // X u< 128 => X s> -1
6186           return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
6187                            ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6188         } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6189                    RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6190           // X u> 127 => X s< 0
6191           return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
6192                               Constant::getNullValue(SrcTy));
6193         }
6194       }
6195     }
6196   }
6197   return 0;
6198 }
6199
6200 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6201 /// We only handle extending casts so far.
6202 ///
6203 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6204   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6205   Value *LHSCIOp        = LHSCI->getOperand(0);
6206   const Type *SrcTy     = LHSCIOp->getType();
6207   const Type *DestTy    = LHSCI->getType();
6208   Value *RHSCIOp;
6209
6210   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
6211   // integer type is the same size as the pointer type.
6212   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6213       getTargetData().getPointerSizeInBits() == 
6214          cast<IntegerType>(DestTy)->getBitWidth()) {
6215     Value *RHSOp = 0;
6216     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6217       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6218     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6219       RHSOp = RHSC->getOperand(0);
6220       // If the pointer types don't match, insert a bitcast.
6221       if (LHSCIOp->getType() != RHSOp->getType())
6222         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6223     }
6224
6225     if (RHSOp)
6226       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6227   }
6228   
6229   // The code below only handles extension cast instructions, so far.
6230   // Enforce this.
6231   if (LHSCI->getOpcode() != Instruction::ZExt &&
6232       LHSCI->getOpcode() != Instruction::SExt)
6233     return 0;
6234
6235   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6236   bool isSignedCmp = ICI.isSignedPredicate();
6237
6238   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6239     // Not an extension from the same type?
6240     RHSCIOp = CI->getOperand(0);
6241     if (RHSCIOp->getType() != LHSCIOp->getType()) 
6242       return 0;
6243     
6244     // If the signedness of the two casts doesn't agree (i.e. one is a sext
6245     // and the other is a zext), then we can't handle this.
6246     if (CI->getOpcode() != LHSCI->getOpcode())
6247       return 0;
6248
6249     // Deal with equality cases early.
6250     if (ICI.isEquality())
6251       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6252
6253     // A signed comparison of sign extended values simplifies into a
6254     // signed comparison.
6255     if (isSignedCmp && isSignedExt)
6256       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6257
6258     // The other three cases all fold into an unsigned comparison.
6259     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6260   }
6261
6262   // If we aren't dealing with a constant on the RHS, exit early
6263   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6264   if (!CI)
6265     return 0;
6266
6267   // Compute the constant that would happen if we truncated to SrcTy then
6268   // reextended to DestTy.
6269   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6270   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6271
6272   // If the re-extended constant didn't change...
6273   if (Res2 == CI) {
6274     // Make sure that sign of the Cmp and the sign of the Cast are the same.
6275     // For example, we might have:
6276     //    %A = sext short %X to uint
6277     //    %B = icmp ugt uint %A, 1330
6278     // It is incorrect to transform this into 
6279     //    %B = icmp ugt short %X, 1330 
6280     // because %A may have negative value. 
6281     //
6282     // However, we allow this when the compare is EQ/NE, because they are
6283     // signless.
6284     if (isSignedExt == isSignedCmp || ICI.isEquality())
6285       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6286     return 0;
6287   }
6288
6289   // The re-extended constant changed so the constant cannot be represented 
6290   // in the shorter type. Consequently, we cannot emit a simple comparison.
6291
6292   // First, handle some easy cases. We know the result cannot be equal at this
6293   // point so handle the ICI.isEquality() cases
6294   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6295     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6296   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6297     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6298
6299   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6300   // should have been folded away previously and not enter in here.
6301   Value *Result;
6302   if (isSignedCmp) {
6303     // We're performing a signed comparison.
6304     if (cast<ConstantInt>(CI)->getValue().isNegative())
6305       Result = ConstantInt::getFalse();          // X < (small) --> false
6306     else
6307       Result = ConstantInt::getTrue();           // X < (large) --> true
6308   } else {
6309     // We're performing an unsigned comparison.
6310     if (isSignedExt) {
6311       // We're performing an unsigned comp with a sign extended value.
6312       // This is true if the input is >= 0. [aka >s -1]
6313       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6314       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6315                                    NegOne, ICI.getName()), ICI);
6316     } else {
6317       // Unsigned extend & unsigned compare -> always true.
6318       Result = ConstantInt::getTrue();
6319     }
6320   }
6321
6322   // Finally, return the value computed.
6323   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6324       ICI.getPredicate() == ICmpInst::ICMP_SLT)
6325     return ReplaceInstUsesWith(ICI, Result);
6326
6327   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
6328           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6329          "ICmp should be folded!");
6330   if (Constant *CI = dyn_cast<Constant>(Result))
6331     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6332   return BinaryOperator::CreateNot(Result);
6333 }
6334
6335 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6336   return commonShiftTransforms(I);
6337 }
6338
6339 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6340   return commonShiftTransforms(I);
6341 }
6342
6343 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6344   if (Instruction *R = commonShiftTransforms(I))
6345     return R;
6346   
6347   Value *Op0 = I.getOperand(0);
6348   
6349   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
6350   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6351     if (CSI->isAllOnesValue())
6352       return ReplaceInstUsesWith(I, CSI);
6353   
6354   // See if we can turn a signed shr into an unsigned shr.
6355   if (!isa<VectorType>(I.getType()) &&
6356       MaskedValueIsZero(Op0,
6357                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6358     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
6359   
6360   return 0;
6361 }
6362
6363 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6364   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6365   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6366
6367   // shl X, 0 == X and shr X, 0 == X
6368   // shl 0, X == 0 and shr 0, X == 0
6369   if (Op1 == Constant::getNullValue(Op1->getType()) ||
6370       Op0 == Constant::getNullValue(Op0->getType()))
6371     return ReplaceInstUsesWith(I, Op0);
6372   
6373   if (isa<UndefValue>(Op0)) {            
6374     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6375       return ReplaceInstUsesWith(I, Op0);
6376     else                                    // undef << X -> 0, undef >>u X -> 0
6377       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6378   }
6379   if (isa<UndefValue>(Op1)) {
6380     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
6381       return ReplaceInstUsesWith(I, Op0);          
6382     else                                     // X << undef, X >>u undef -> 0
6383       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6384   }
6385
6386   // Try to fold constant and into select arguments.
6387   if (isa<Constant>(Op0))
6388     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6389       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6390         return R;
6391
6392   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6393     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6394       return Res;
6395   return 0;
6396 }
6397
6398 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6399                                                BinaryOperator &I) {
6400   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
6401
6402   // See if we can simplify any instructions used by the instruction whose sole 
6403   // purpose is to compute bits we don't care about.
6404   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6405   APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6406   if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6407                            KnownZero, KnownOne))
6408     return &I;
6409   
6410   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6411   // of a signed value.
6412   //
6413   if (Op1->uge(TypeBits)) {
6414     if (I.getOpcode() != Instruction::AShr)
6415       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6416     else {
6417       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6418       return &I;
6419     }
6420   }
6421   
6422   // ((X*C1) << C2) == (X * (C1 << C2))
6423   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6424     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6425       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6426         return BinaryOperator::CreateMul(BO->getOperand(0),
6427                                          ConstantExpr::getShl(BOOp, Op1));
6428   
6429   // Try to fold constant and into select arguments.
6430   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6431     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6432       return R;
6433   if (isa<PHINode>(Op0))
6434     if (Instruction *NV = FoldOpIntoPhi(I))
6435       return NV;
6436   
6437   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6438   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6439     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6440     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6441     // place.  Don't try to do this transformation in this case.  Also, we
6442     // require that the input operand is a shift-by-constant so that we have
6443     // confidence that the shifts will get folded together.  We could do this
6444     // xform in more cases, but it is unlikely to be profitable.
6445     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
6446         isa<ConstantInt>(TrOp->getOperand(1))) {
6447       // Okay, we'll do this xform.  Make the shift of shift.
6448       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6449       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
6450                                                 I.getName());
6451       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6452
6453       // For logical shifts, the truncation has the effect of making the high
6454       // part of the register be zeros.  Emulate this by inserting an AND to
6455       // clear the top bits as needed.  This 'and' will usually be zapped by
6456       // other xforms later if dead.
6457       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6458       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6459       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6460       
6461       // The mask we constructed says what the trunc would do if occurring
6462       // between the shifts.  We want to know the effect *after* the second
6463       // shift.  We know that it is a logical shift by a constant, so adjust the
6464       // mask as appropriate.
6465       if (I.getOpcode() == Instruction::Shl)
6466         MaskV <<= Op1->getZExtValue();
6467       else {
6468         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6469         MaskV = MaskV.lshr(Op1->getZExtValue());
6470       }
6471
6472       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
6473                                                    TI->getName());
6474       InsertNewInstBefore(And, I); // shift1 & 0x00FF
6475
6476       // Return the value truncated to the interesting size.
6477       return new TruncInst(And, I.getType());
6478     }
6479   }
6480   
6481   if (Op0->hasOneUse()) {
6482     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6483       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6484       Value *V1, *V2;
6485       ConstantInt *CC;
6486       switch (Op0BO->getOpcode()) {
6487         default: break;
6488         case Instruction::Add:
6489         case Instruction::And:
6490         case Instruction::Or:
6491         case Instruction::Xor: {
6492           // These operators commute.
6493           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
6494           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6495               match(Op0BO->getOperand(1),
6496                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6497             Instruction *YS = BinaryOperator::CreateShl(
6498                                             Op0BO->getOperand(0), Op1,
6499                                             Op0BO->getName());
6500             InsertNewInstBefore(YS, I); // (Y << C)
6501             Instruction *X = 
6502               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
6503                                      Op0BO->getOperand(1)->getName());
6504             InsertNewInstBefore(X, I);  // (X + (Y << C))
6505             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6506             return BinaryOperator::CreateAnd(X, ConstantInt::get(
6507                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6508           }
6509           
6510           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
6511           Value *Op0BOOp1 = Op0BO->getOperand(1);
6512           if (isLeftShift && Op0BOOp1->hasOneUse() &&
6513               match(Op0BOOp1, 
6514                     m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6515               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6516               V2 == Op1) {
6517             Instruction *YS = BinaryOperator::CreateShl(
6518                                                      Op0BO->getOperand(0), Op1,
6519                                                      Op0BO->getName());
6520             InsertNewInstBefore(YS, I); // (Y << C)
6521             Instruction *XM =
6522               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
6523                                         V1->getName()+".mask");
6524             InsertNewInstBefore(XM, I); // X & (CC << C)
6525             
6526             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
6527           }
6528         }
6529           
6530         // FALL THROUGH.
6531         case Instruction::Sub: {
6532           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6533           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6534               match(Op0BO->getOperand(0),
6535                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6536             Instruction *YS = BinaryOperator::CreateShl(
6537                                                      Op0BO->getOperand(1), Op1,
6538                                                      Op0BO->getName());
6539             InsertNewInstBefore(YS, I); // (Y << C)
6540             Instruction *X =
6541               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
6542                                      Op0BO->getOperand(0)->getName());
6543             InsertNewInstBefore(X, I);  // (X + (Y << C))
6544             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6545             return BinaryOperator::CreateAnd(X, ConstantInt::get(
6546                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6547           }
6548           
6549           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
6550           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6551               match(Op0BO->getOperand(0),
6552                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
6553                           m_ConstantInt(CC))) && V2 == Op1 &&
6554               cast<BinaryOperator>(Op0BO->getOperand(0))
6555                   ->getOperand(0)->hasOneUse()) {
6556             Instruction *YS = BinaryOperator::CreateShl(
6557                                                      Op0BO->getOperand(1), Op1,
6558                                                      Op0BO->getName());
6559             InsertNewInstBefore(YS, I); // (Y << C)
6560             Instruction *XM =
6561               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
6562                                         V1->getName()+".mask");
6563             InsertNewInstBefore(XM, I); // X & (CC << C)
6564             
6565             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
6566           }
6567           
6568           break;
6569         }
6570       }
6571       
6572       
6573       // If the operand is an bitwise operator with a constant RHS, and the
6574       // shift is the only use, we can pull it out of the shift.
6575       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6576         bool isValid = true;     // Valid only for And, Or, Xor
6577         bool highBitSet = false; // Transform if high bit of constant set?
6578         
6579         switch (Op0BO->getOpcode()) {
6580           default: isValid = false; break;   // Do not perform transform!
6581           case Instruction::Add:
6582             isValid = isLeftShift;
6583             break;
6584           case Instruction::Or:
6585           case Instruction::Xor:
6586             highBitSet = false;
6587             break;
6588           case Instruction::And:
6589             highBitSet = true;
6590             break;
6591         }
6592         
6593         // If this is a signed shift right, and the high bit is modified
6594         // by the logical operation, do not perform the transformation.
6595         // The highBitSet boolean indicates the value of the high bit of
6596         // the constant which would cause it to be modified for this
6597         // operation.
6598         //
6599         if (isValid && I.getOpcode() == Instruction::AShr)
6600           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
6601         
6602         if (isValid) {
6603           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6604           
6605           Instruction *NewShift =
6606             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6607           InsertNewInstBefore(NewShift, I);
6608           NewShift->takeName(Op0BO);
6609           
6610           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
6611                                         NewRHS);
6612         }
6613       }
6614     }
6615   }
6616   
6617   // Find out if this is a shift of a shift by a constant.
6618   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6619   if (ShiftOp && !ShiftOp->isShift())
6620     ShiftOp = 0;
6621   
6622   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6623     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6624     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6625     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6626     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6627     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
6628     Value *X = ShiftOp->getOperand(0);
6629     
6630     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
6631     if (AmtSum > TypeBits)
6632       AmtSum = TypeBits;
6633     
6634     const IntegerType *Ty = cast<IntegerType>(I.getType());
6635     
6636     // Check for (X << c1) << c2  and  (X >> c1) >> c2
6637     if (I.getOpcode() == ShiftOp->getOpcode()) {
6638       return BinaryOperator::Create(I.getOpcode(), X,
6639                                     ConstantInt::get(Ty, AmtSum));
6640     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6641                I.getOpcode() == Instruction::AShr) {
6642       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
6643       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
6644     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6645                I.getOpcode() == Instruction::LShr) {
6646       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6647       Instruction *Shift =
6648         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
6649       InsertNewInstBefore(Shift, I);
6650
6651       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6652       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6653     }
6654     
6655     // Okay, if we get here, one shift must be left, and the other shift must be
6656     // right.  See if the amounts are equal.
6657     if (ShiftAmt1 == ShiftAmt2) {
6658       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6659       if (I.getOpcode() == Instruction::Shl) {
6660         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
6661         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
6662       }
6663       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6664       if (I.getOpcode() == Instruction::LShr) {
6665         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
6666         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
6667       }
6668       // We can simplify ((X << C) >>s C) into a trunc + sext.
6669       // NOTE: we could do this for any C, but that would make 'unusual' integer
6670       // types.  For now, just stick to ones well-supported by the code
6671       // generators.
6672       const Type *SExtType = 0;
6673       switch (Ty->getBitWidth() - ShiftAmt1) {
6674       case 1  :
6675       case 8  :
6676       case 16 :
6677       case 32 :
6678       case 64 :
6679       case 128:
6680         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6681         break;
6682       default: break;
6683       }
6684       if (SExtType) {
6685         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6686         InsertNewInstBefore(NewTrunc, I);
6687         return new SExtInst(NewTrunc, Ty);
6688       }
6689       // Otherwise, we can't handle it yet.
6690     } else if (ShiftAmt1 < ShiftAmt2) {
6691       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6692       
6693       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6694       if (I.getOpcode() == Instruction::Shl) {
6695         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6696                ShiftOp->getOpcode() == Instruction::AShr);
6697         Instruction *Shift =
6698           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
6699         InsertNewInstBefore(Shift, I);
6700         
6701         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6702         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6703       }
6704       
6705       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
6706       if (I.getOpcode() == Instruction::LShr) {
6707         assert(ShiftOp->getOpcode() == Instruction::Shl);
6708         Instruction *Shift =
6709           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
6710         InsertNewInstBefore(Shift, I);
6711         
6712         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6713         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6714       }
6715       
6716       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6717     } else {
6718       assert(ShiftAmt2 < ShiftAmt1);
6719       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6720
6721       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6722       if (I.getOpcode() == Instruction::Shl) {
6723         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6724                ShiftOp->getOpcode() == Instruction::AShr);
6725         Instruction *Shift =
6726           BinaryOperator::Create(ShiftOp->getOpcode(), X,
6727                                  ConstantInt::get(Ty, ShiftDiff));
6728         InsertNewInstBefore(Shift, I);
6729         
6730         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6731         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6732       }
6733       
6734       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
6735       if (I.getOpcode() == Instruction::LShr) {
6736         assert(ShiftOp->getOpcode() == Instruction::Shl);
6737         Instruction *Shift =
6738           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
6739         InsertNewInstBefore(Shift, I);
6740         
6741         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6742         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6743       }
6744       
6745       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6746     }
6747   }
6748   return 0;
6749 }
6750
6751
6752 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6753 /// expression.  If so, decompose it, returning some value X, such that Val is
6754 /// X*Scale+Offset.
6755 ///
6756 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6757                                         int &Offset) {
6758   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6759   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6760     Offset = CI->getZExtValue();
6761     Scale  = 0;
6762     return ConstantInt::get(Type::Int32Ty, 0);
6763   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6764     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6765       if (I->getOpcode() == Instruction::Shl) {
6766         // This is a value scaled by '1 << the shift amt'.
6767         Scale = 1U << RHS->getZExtValue();
6768         Offset = 0;
6769         return I->getOperand(0);
6770       } else if (I->getOpcode() == Instruction::Mul) {
6771         // This value is scaled by 'RHS'.
6772         Scale = RHS->getZExtValue();
6773         Offset = 0;
6774         return I->getOperand(0);
6775       } else if (I->getOpcode() == Instruction::Add) {
6776         // We have X+C.  Check to see if we really have (X*C2)+C1, 
6777         // where C1 is divisible by C2.
6778         unsigned SubScale;
6779         Value *SubVal = 
6780           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6781         Offset += RHS->getZExtValue();
6782         Scale = SubScale;
6783         return SubVal;
6784       }
6785     }
6786   }
6787
6788   // Otherwise, we can't look past this.
6789   Scale = 1;
6790   Offset = 0;
6791   return Val;
6792 }
6793
6794
6795 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6796 /// try to eliminate the cast by moving the type information into the alloc.
6797 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6798                                                    AllocationInst &AI) {
6799   const PointerType *PTy = cast<PointerType>(CI.getType());
6800   
6801   // Remove any uses of AI that are dead.
6802   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6803   
6804   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6805     Instruction *User = cast<Instruction>(*UI++);
6806     if (isInstructionTriviallyDead(User)) {
6807       while (UI != E && *UI == User)
6808         ++UI; // If this instruction uses AI more than once, don't break UI.
6809       
6810       ++NumDeadInst;
6811       DOUT << "IC: DCE: " << *User;
6812       EraseInstFromFunction(*User);
6813     }
6814   }
6815   
6816   // Get the type really allocated and the type casted to.
6817   const Type *AllocElTy = AI.getAllocatedType();
6818   const Type *CastElTy = PTy->getElementType();
6819   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6820
6821   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6822   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6823   if (CastElTyAlign < AllocElTyAlign) return 0;
6824
6825   // If the allocation has multiple uses, only promote it if we are strictly
6826   // increasing the alignment of the resultant allocation.  If we keep it the
6827   // same, we open the door to infinite loops of various kinds.
6828   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6829
6830   uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6831   uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
6832   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6833
6834   // See if we can satisfy the modulus by pulling a scale out of the array
6835   // size argument.
6836   unsigned ArraySizeScale;
6837   int ArrayOffset;
6838   Value *NumElements = // See if the array size is a decomposable linear expr.
6839     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6840  
6841   // If we can now satisfy the modulus, by using a non-1 scale, we really can
6842   // do the xform.
6843   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6844       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
6845
6846   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6847   Value *Amt = 0;
6848   if (Scale == 1) {
6849     Amt = NumElements;
6850   } else {
6851     // If the allocation size is constant, form a constant mul expression
6852     Amt = ConstantInt::get(Type::Int32Ty, Scale);
6853     if (isa<ConstantInt>(NumElements))
6854       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6855     // otherwise multiply the amount and the number of elements
6856     else if (Scale != 1) {
6857       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
6858       Amt = InsertNewInstBefore(Tmp, AI);
6859     }
6860   }
6861   
6862   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6863     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
6864     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
6865     Amt = InsertNewInstBefore(Tmp, AI);
6866   }
6867   
6868   AllocationInst *New;
6869   if (isa<MallocInst>(AI))
6870     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6871   else
6872     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6873   InsertNewInstBefore(New, AI);
6874   New->takeName(&AI);
6875   
6876   // If the allocation has multiple uses, insert a cast and change all things
6877   // that used it to use the new cast.  This will also hack on CI, but it will
6878   // die soon.
6879   if (!AI.hasOneUse()) {
6880     AddUsesToWorkList(AI);
6881     // New is the allocation instruction, pointer typed. AI is the original
6882     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6883     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6884     InsertNewInstBefore(NewCast, AI);
6885     AI.replaceAllUsesWith(NewCast);
6886   }
6887   return ReplaceInstUsesWith(CI, New);
6888 }
6889
6890 /// CanEvaluateInDifferentType - Return true if we can take the specified value
6891 /// and return it as type Ty without inserting any new casts and without
6892 /// changing the computed value.  This is used by code that tries to decide
6893 /// whether promoting or shrinking integer operations to wider or smaller types
6894 /// will allow us to eliminate a truncate or extend.
6895 ///
6896 /// This is a truncation operation if Ty is smaller than V->getType(), or an
6897 /// extension operation if Ty is larger.
6898 ///
6899 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
6900 /// should return true if trunc(V) can be computed by computing V in the smaller
6901 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
6902 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
6903 /// efficiently truncated.
6904 ///
6905 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
6906 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
6907 /// the final result.
6908 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6909                                               unsigned CastOpc,
6910                                               int &NumCastsRemoved) {
6911   // We can always evaluate constants in another type.
6912   if (isa<ConstantInt>(V))
6913     return true;
6914   
6915   Instruction *I = dyn_cast<Instruction>(V);
6916   if (!I) return false;
6917   
6918   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6919   
6920   // If this is an extension or truncate, we can often eliminate it.
6921   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6922     // If this is a cast from the destination type, we can trivially eliminate
6923     // it, and this will remove a cast overall.
6924     if (I->getOperand(0)->getType() == Ty) {
6925       // If the first operand is itself a cast, and is eliminable, do not count
6926       // this as an eliminable cast.  We would prefer to eliminate those two
6927       // casts first.
6928       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
6929         ++NumCastsRemoved;
6930       return true;
6931     }
6932   }
6933
6934   // We can't extend or shrink something that has multiple uses: doing so would
6935   // require duplicating the instruction in general, which isn't profitable.
6936   if (!I->hasOneUse()) return false;
6937
6938   switch (I->getOpcode()) {
6939   case Instruction::Add:
6940   case Instruction::Sub:
6941   case Instruction::Mul:
6942   case Instruction::And:
6943   case Instruction::Or:
6944   case Instruction::Xor:
6945     // These operators can all arbitrarily be extended or truncated.
6946     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6947                                       NumCastsRemoved) &&
6948            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6949                                       NumCastsRemoved);
6950
6951   case Instruction::Shl:
6952     // If we are truncating the result of this SHL, and if it's a shift of a
6953     // constant amount, we can always perform a SHL in a smaller type.
6954     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6955       uint32_t BitWidth = Ty->getBitWidth();
6956       if (BitWidth < OrigTy->getBitWidth() && 
6957           CI->getLimitedValue(BitWidth) < BitWidth)
6958         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6959                                           NumCastsRemoved);
6960     }
6961     break;
6962   case Instruction::LShr:
6963     // If this is a truncate of a logical shr, we can truncate it to a smaller
6964     // lshr iff we know that the bits we would otherwise be shifting in are
6965     // already zeros.
6966     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6967       uint32_t OrigBitWidth = OrigTy->getBitWidth();
6968       uint32_t BitWidth = Ty->getBitWidth();
6969       if (BitWidth < OrigBitWidth &&
6970           MaskedValueIsZero(I->getOperand(0),
6971             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6972           CI->getLimitedValue(BitWidth) < BitWidth) {
6973         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6974                                           NumCastsRemoved);
6975       }
6976     }
6977     break;
6978   case Instruction::ZExt:
6979   case Instruction::SExt:
6980   case Instruction::Trunc:
6981     // If this is the same kind of case as our original (e.g. zext+zext), we
6982     // can safely replace it.  Note that replacing it does not reduce the number
6983     // of casts in the input.
6984     if (I->getOpcode() == CastOpc)
6985       return true;
6986     break;
6987   case Instruction::Select: {
6988     SelectInst *SI = cast<SelectInst>(I);
6989     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
6990                                       NumCastsRemoved) &&
6991            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
6992                                       NumCastsRemoved);
6993   }
6994   case Instruction::PHI: {
6995     // We can change a phi if we can change all operands.
6996     PHINode *PN = cast<PHINode>(I);
6997     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
6998       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
6999                                       NumCastsRemoved))
7000         return false;
7001     return true;
7002   }
7003   default:
7004     // TODO: Can handle more cases here.
7005     break;
7006   }
7007   
7008   return false;
7009 }
7010
7011 /// EvaluateInDifferentType - Given an expression that 
7012 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7013 /// evaluate the expression.
7014 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7015                                              bool isSigned) {
7016   if (Constant *C = dyn_cast<Constant>(V))
7017     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7018
7019   // Otherwise, it must be an instruction.
7020   Instruction *I = cast<Instruction>(V);
7021   Instruction *Res = 0;
7022   switch (I->getOpcode()) {
7023   case Instruction::Add:
7024   case Instruction::Sub:
7025   case Instruction::Mul:
7026   case Instruction::And:
7027   case Instruction::Or:
7028   case Instruction::Xor:
7029   case Instruction::AShr:
7030   case Instruction::LShr:
7031   case Instruction::Shl: {
7032     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7033     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7034     Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
7035                                  LHS, RHS);
7036     break;
7037   }    
7038   case Instruction::Trunc:
7039   case Instruction::ZExt:
7040   case Instruction::SExt:
7041     // If the source type of the cast is the type we're trying for then we can
7042     // just return the source.  There's no need to insert it because it is not
7043     // new.
7044     if (I->getOperand(0)->getType() == Ty)
7045       return I->getOperand(0);
7046     
7047     // Otherwise, must be the same type of cast, so just reinsert a new one.
7048     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7049                            Ty);
7050     break;
7051   case Instruction::Select: {
7052     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7053     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7054     Res = SelectInst::Create(I->getOperand(0), True, False);
7055     break;
7056   }
7057   case Instruction::PHI: {
7058     PHINode *OPN = cast<PHINode>(I);
7059     PHINode *NPN = PHINode::Create(Ty);
7060     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7061       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7062       NPN->addIncoming(V, OPN->getIncomingBlock(i));
7063     }
7064     Res = NPN;
7065     break;
7066   }
7067   default: 
7068     // TODO: Can handle more cases here.
7069     assert(0 && "Unreachable!");
7070     break;
7071   }
7072   
7073   Res->takeName(I);
7074   return InsertNewInstBefore(Res, *I);
7075 }
7076
7077 /// @brief Implement the transforms common to all CastInst visitors.
7078 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7079   Value *Src = CI.getOperand(0);
7080
7081   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7082   // eliminate it now.
7083   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7084     if (Instruction::CastOps opc = 
7085         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7086       // The first cast (CSrc) is eliminable so we need to fix up or replace
7087       // the second cast (CI). CSrc will then have a good chance of being dead.
7088       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7089     }
7090   }
7091
7092   // If we are casting a select then fold the cast into the select
7093   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7094     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7095       return NV;
7096
7097   // If we are casting a PHI then fold the cast into the PHI
7098   if (isa<PHINode>(Src))
7099     if (Instruction *NV = FoldOpIntoPhi(CI))
7100       return NV;
7101   
7102   return 0;
7103 }
7104
7105 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7106 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7107   Value *Src = CI.getOperand(0);
7108   
7109   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7110     // If casting the result of a getelementptr instruction with no offset, turn
7111     // this into a cast of the original pointer!
7112     if (GEP->hasAllZeroIndices()) {
7113       // Changing the cast operand is usually not a good idea but it is safe
7114       // here because the pointer operand is being replaced with another 
7115       // pointer operand so the opcode doesn't need to change.
7116       AddToWorkList(GEP);
7117       CI.setOperand(0, GEP->getOperand(0));
7118       return &CI;
7119     }
7120     
7121     // If the GEP has a single use, and the base pointer is a bitcast, and the
7122     // GEP computes a constant offset, see if we can convert these three
7123     // instructions into fewer.  This typically happens with unions and other
7124     // non-type-safe code.
7125     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7126       if (GEP->hasAllConstantIndices()) {
7127         // We are guaranteed to get a constant from EmitGEPOffset.
7128         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7129         int64_t Offset = OffsetV->getSExtValue();
7130         
7131         // Get the base pointer input of the bitcast, and the type it points to.
7132         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7133         const Type *GEPIdxTy =
7134           cast<PointerType>(OrigBase->getType())->getElementType();
7135         if (GEPIdxTy->isSized()) {
7136           SmallVector<Value*, 8> NewIndices;
7137           
7138           // Start with the index over the outer type.  Note that the type size
7139           // might be zero (even if the offset isn't zero) if the indexed type
7140           // is something like [0 x {int, int}]
7141           const Type *IntPtrTy = TD->getIntPtrType();
7142           int64_t FirstIdx = 0;
7143           if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
7144             FirstIdx = Offset/TySize;
7145             Offset %= TySize;
7146           
7147             // Handle silly modulus not returning values values [0..TySize).
7148             if (Offset < 0) {
7149               --FirstIdx;
7150               Offset += TySize;
7151               assert(Offset >= 0);
7152             }
7153             assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7154           }
7155           
7156           NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7157
7158           // Index into the types.  If we fail, set OrigBase to null.
7159           while (Offset) {
7160             if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7161               const StructLayout *SL = TD->getStructLayout(STy);
7162               if (Offset < (int64_t)SL->getSizeInBytes()) {
7163                 unsigned Elt = SL->getElementContainingOffset(Offset);
7164                 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7165               
7166                 Offset -= SL->getElementOffset(Elt);
7167                 GEPIdxTy = STy->getElementType(Elt);
7168               } else {
7169                 // Otherwise, we can't index into this, bail out.
7170                 Offset = 0;
7171                 OrigBase = 0;
7172               }
7173             } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7174               const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
7175               if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
7176                 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7177                 Offset %= EltSize;
7178               } else {
7179                 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7180               }
7181               GEPIdxTy = STy->getElementType();
7182             } else {
7183               // Otherwise, we can't index into this, bail out.
7184               Offset = 0;
7185               OrigBase = 0;
7186             }
7187           }
7188           if (OrigBase) {
7189             // If we were able to index down into an element, create the GEP
7190             // and bitcast the result.  This eliminates one bitcast, potentially
7191             // two.
7192             Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
7193                                                           NewIndices.begin(),
7194                                                           NewIndices.end(), "");
7195             InsertNewInstBefore(NGEP, CI);
7196             NGEP->takeName(GEP);
7197             
7198             if (isa<BitCastInst>(CI))
7199               return new BitCastInst(NGEP, CI.getType());
7200             assert(isa<PtrToIntInst>(CI));
7201             return new PtrToIntInst(NGEP, CI.getType());
7202           }
7203         }
7204       }      
7205     }
7206   }
7207     
7208   return commonCastTransforms(CI);
7209 }
7210
7211
7212
7213 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7214 /// integer types. This function implements the common transforms for all those
7215 /// cases.
7216 /// @brief Implement the transforms common to CastInst with integer operands
7217 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7218   if (Instruction *Result = commonCastTransforms(CI))
7219     return Result;
7220
7221   Value *Src = CI.getOperand(0);
7222   const Type *SrcTy = Src->getType();
7223   const Type *DestTy = CI.getType();
7224   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7225   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7226
7227   // See if we can simplify any instructions used by the LHS whose sole 
7228   // purpose is to compute bits we don't care about.
7229   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7230   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7231                            KnownZero, KnownOne))
7232     return &CI;
7233
7234   // If the source isn't an instruction or has more than one use then we
7235   // can't do anything more. 
7236   Instruction *SrcI = dyn_cast<Instruction>(Src);
7237   if (!SrcI || !Src->hasOneUse())
7238     return 0;
7239
7240   // Attempt to propagate the cast into the instruction for int->int casts.
7241   int NumCastsRemoved = 0;
7242   if (!isa<BitCastInst>(CI) &&
7243       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7244                                  CI.getOpcode(), NumCastsRemoved)) {
7245     // If this cast is a truncate, evaluting in a different type always
7246     // eliminates the cast, so it is always a win.  If this is a zero-extension,
7247     // we need to do an AND to maintain the clear top-part of the computation,
7248     // so we require that the input have eliminated at least one cast.  If this
7249     // is a sign extension, we insert two new casts (to do the extension) so we
7250     // require that two casts have been eliminated.
7251     bool DoXForm;
7252     switch (CI.getOpcode()) {
7253     default:
7254       // All the others use floating point so we shouldn't actually 
7255       // get here because of the check above.
7256       assert(0 && "Unknown cast type");
7257     case Instruction::Trunc:
7258       DoXForm = true;
7259       break;
7260     case Instruction::ZExt:
7261       DoXForm = NumCastsRemoved >= 1;
7262       break;
7263     case Instruction::SExt:
7264       DoXForm = NumCastsRemoved >= 2;
7265       break;
7266     }
7267     
7268     if (DoXForm) {
7269       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
7270                                            CI.getOpcode() == Instruction::SExt);
7271       assert(Res->getType() == DestTy);
7272       switch (CI.getOpcode()) {
7273       default: assert(0 && "Unknown cast type!");
7274       case Instruction::Trunc:
7275       case Instruction::BitCast:
7276         // Just replace this cast with the result.
7277         return ReplaceInstUsesWith(CI, Res);
7278       case Instruction::ZExt: {
7279         // We need to emit an AND to clear the high bits.
7280         assert(SrcBitSize < DestBitSize && "Not a zext?");
7281         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7282                                                             SrcBitSize));
7283         return BinaryOperator::CreateAnd(Res, C);
7284       }
7285       case Instruction::SExt:
7286         // We need to emit a cast to truncate, then a cast to sext.
7287         return CastInst::Create(Instruction::SExt,
7288             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
7289                              CI), DestTy);
7290       }
7291     }
7292   }
7293   
7294   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7295   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7296
7297   switch (SrcI->getOpcode()) {
7298   case Instruction::Add:
7299   case Instruction::Mul:
7300   case Instruction::And:
7301   case Instruction::Or:
7302   case Instruction::Xor:
7303     // If we are discarding information, rewrite.
7304     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7305       // Don't insert two casts if they cannot be eliminated.  We allow 
7306       // two casts to be inserted if the sizes are the same.  This could 
7307       // only be converting signedness, which is a noop.
7308       if (DestBitSize == SrcBitSize || 
7309           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7310           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7311         Instruction::CastOps opcode = CI.getOpcode();
7312         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7313         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7314         return BinaryOperator::Create(
7315             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7316       }
7317     }
7318
7319     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
7320     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
7321         SrcI->getOpcode() == Instruction::Xor &&
7322         Op1 == ConstantInt::getTrue() &&
7323         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7324       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
7325       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
7326     }
7327     break;
7328   case Instruction::SDiv:
7329   case Instruction::UDiv:
7330   case Instruction::SRem:
7331   case Instruction::URem:
7332     // If we are just changing the sign, rewrite.
7333     if (DestBitSize == SrcBitSize) {
7334       // Don't insert two casts if they cannot be eliminated.  We allow 
7335       // two casts to be inserted if the sizes are the same.  This could 
7336       // only be converting signedness, which is a noop.
7337       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
7338           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7339         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
7340                                               Op0, DestTy, SrcI);
7341         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
7342                                               Op1, DestTy, SrcI);
7343         return BinaryOperator::Create(
7344           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7345       }
7346     }
7347     break;
7348
7349   case Instruction::Shl:
7350     // Allow changing the sign of the source operand.  Do not allow 
7351     // changing the size of the shift, UNLESS the shift amount is a 
7352     // constant.  We must not change variable sized shifts to a smaller 
7353     // size, because it is undefined to shift more bits out than exist 
7354     // in the value.
7355     if (DestBitSize == SrcBitSize ||
7356         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7357       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7358           Instruction::BitCast : Instruction::Trunc);
7359       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7360       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7361       return BinaryOperator::CreateShl(Op0c, Op1c);
7362     }
7363     break;
7364   case Instruction::AShr:
7365     // If this is a signed shr, and if all bits shifted in are about to be
7366     // truncated off, turn it into an unsigned shr to allow greater
7367     // simplifications.
7368     if (DestBitSize < SrcBitSize &&
7369         isa<ConstantInt>(Op1)) {
7370       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7371       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7372         // Insert the new logical shift right.
7373         return BinaryOperator::CreateLShr(Op0, Op1);
7374       }
7375     }
7376     break;
7377   }
7378   return 0;
7379 }
7380
7381 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7382   if (Instruction *Result = commonIntCastTransforms(CI))
7383     return Result;
7384   
7385   Value *Src = CI.getOperand(0);
7386   const Type *Ty = CI.getType();
7387   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7388   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7389   
7390   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7391     switch (SrcI->getOpcode()) {
7392     default: break;
7393     case Instruction::LShr:
7394       // We can shrink lshr to something smaller if we know the bits shifted in
7395       // are already zeros.
7396       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7397         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7398         
7399         // Get a mask for the bits shifting in.
7400         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7401         Value* SrcIOp0 = SrcI->getOperand(0);
7402         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7403           if (ShAmt >= DestBitWidth)        // All zeros.
7404             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7405
7406           // Okay, we can shrink this.  Truncate the input, then return a new
7407           // shift.
7408           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7409           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7410                                        Ty, CI);
7411           return BinaryOperator::CreateLShr(V1, V2);
7412         }
7413       } else {     // This is a variable shr.
7414         
7415         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
7416         // more LLVM instructions, but allows '1 << Y' to be hoisted if
7417         // loop-invariant and CSE'd.
7418         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7419           Value *One = ConstantInt::get(SrcI->getType(), 1);
7420
7421           Value *V = InsertNewInstBefore(
7422               BinaryOperator::CreateShl(One, SrcI->getOperand(1),
7423                                      "tmp"), CI);
7424           V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
7425                                                             SrcI->getOperand(0),
7426                                                             "tmp"), CI);
7427           Value *Zero = Constant::getNullValue(V->getType());
7428           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7429         }
7430       }
7431       break;
7432     }
7433   }
7434   
7435   return 0;
7436 }
7437
7438 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7439 /// in order to eliminate the icmp.
7440 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7441                                              bool DoXform) {
7442   // If we are just checking for a icmp eq of a single bit and zext'ing it
7443   // to an integer, then shift the bit to the appropriate place and then
7444   // cast to integer to avoid the comparison.
7445   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7446     const APInt &Op1CV = Op1C->getValue();
7447       
7448     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
7449     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
7450     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7451         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7452       if (!DoXform) return ICI;
7453
7454       Value *In = ICI->getOperand(0);
7455       Value *Sh = ConstantInt::get(In->getType(),
7456                                    In->getType()->getPrimitiveSizeInBits()-1);
7457       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
7458                                                         In->getName()+".lobit"),
7459                                CI);
7460       if (In->getType() != CI.getType())
7461         In = CastInst::CreateIntegerCast(In, CI.getType(),
7462                                          false/*ZExt*/, "tmp", &CI);
7463
7464       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7465         Constant *One = ConstantInt::get(In->getType(), 1);
7466         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
7467                                                          In->getName()+".not"),
7468                                  CI);
7469       }
7470
7471       return ReplaceInstUsesWith(CI, In);
7472     }
7473       
7474       
7475       
7476     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
7477     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7478     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
7479     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
7480     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
7481     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
7482     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
7483     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7484     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
7485         // This only works for EQ and NE
7486         ICI->isEquality()) {
7487       // If Op1C some other power of two, convert:
7488       uint32_t BitWidth = Op1C->getType()->getBitWidth();
7489       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7490       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7491       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7492         
7493       APInt KnownZeroMask(~KnownZero);
7494       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7495         if (!DoXform) return ICI;
7496
7497         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7498         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7499           // (X&4) == 2 --> false
7500           // (X&4) != 2 --> true
7501           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7502           Res = ConstantExpr::getZExt(Res, CI.getType());
7503           return ReplaceInstUsesWith(CI, Res);
7504         }
7505           
7506         uint32_t ShiftAmt = KnownZeroMask.logBase2();
7507         Value *In = ICI->getOperand(0);
7508         if (ShiftAmt) {
7509           // Perform a logical shr by shiftamt.
7510           // Insert the shift to put the result in the low bit.
7511           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
7512                                   ConstantInt::get(In->getType(), ShiftAmt),
7513                                                    In->getName()+".lobit"), CI);
7514         }
7515           
7516         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7517           Constant *One = ConstantInt::get(In->getType(), 1);
7518           In = BinaryOperator::CreateXor(In, One, "tmp");
7519           InsertNewInstBefore(cast<Instruction>(In), CI);
7520         }
7521           
7522         if (CI.getType() == In->getType())
7523           return ReplaceInstUsesWith(CI, In);
7524         else
7525           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
7526       }
7527     }
7528   }
7529
7530   return 0;
7531 }
7532
7533 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7534   // If one of the common conversion will work ..
7535   if (Instruction *Result = commonIntCastTransforms(CI))
7536     return Result;
7537
7538   Value *Src = CI.getOperand(0);
7539
7540   // If this is a cast of a cast
7541   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7542     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7543     // types and if the sizes are just right we can convert this into a logical
7544     // 'and' which will be much cheaper than the pair of casts.
7545     if (isa<TruncInst>(CSrc)) {
7546       // Get the sizes of the types involved
7547       Value *A = CSrc->getOperand(0);
7548       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7549       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7550       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7551       // If we're actually extending zero bits and the trunc is a no-op
7552       if (MidSize < DstSize && SrcSize == DstSize) {
7553         // Replace both of the casts with an And of the type mask.
7554         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7555         Constant *AndConst = ConstantInt::get(AndValue);
7556         Instruction *And = 
7557           BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
7558         // Unfortunately, if the type changed, we need to cast it back.
7559         if (And->getType() != CI.getType()) {
7560           And->setName(CSrc->getName()+".mask");
7561           InsertNewInstBefore(And, CI);
7562           And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
7563         }
7564         return And;
7565       }
7566     }
7567   }
7568
7569   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7570     return transformZExtICmp(ICI, CI);
7571
7572   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7573   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7574     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7575     // of the (zext icmp) will be transformed.
7576     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7577     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7578     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7579         (transformZExtICmp(LHS, CI, false) ||
7580          transformZExtICmp(RHS, CI, false))) {
7581       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7582       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
7583       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
7584     }
7585   }
7586
7587   return 0;
7588 }
7589
7590 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7591   if (Instruction *I = commonIntCastTransforms(CI))
7592     return I;
7593   
7594   Value *Src = CI.getOperand(0);
7595   
7596   // sext (x <s 0) -> ashr x, 31   -> all ones if signed
7597   // sext (x >s -1) -> ashr x, 31  -> all ones if not signed
7598   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7599     // If we are just checking for a icmp eq of a single bit and zext'ing it
7600     // to an integer, then shift the bit to the appropriate place and then
7601     // cast to integer to avoid the comparison.
7602     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7603       const APInt &Op1CV = Op1C->getValue();
7604       
7605       // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
7606       // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
7607       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7608           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7609         Value *In = ICI->getOperand(0);
7610         Value *Sh = ConstantInt::get(In->getType(),
7611                                      In->getType()->getPrimitiveSizeInBits()-1);
7612         In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
7613                                                         In->getName()+".lobit"),
7614                                  CI);
7615         if (In->getType() != CI.getType())
7616           In = CastInst::CreateIntegerCast(In, CI.getType(),
7617                                            true/*SExt*/, "tmp", &CI);
7618         
7619         if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7620           In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
7621                                      In->getName()+".not"), CI);
7622         
7623         return ReplaceInstUsesWith(CI, In);
7624       }
7625     }
7626   }
7627
7628   // See if the value being truncated is already sign extended.  If so, just
7629   // eliminate the trunc/sext pair.
7630   if (getOpcode(Src) == Instruction::Trunc) {
7631     Value *Op = cast<User>(Src)->getOperand(0);
7632     unsigned OpBits   = cast<IntegerType>(Op->getType())->getBitWidth();
7633     unsigned MidBits  = cast<IntegerType>(Src->getType())->getBitWidth();
7634     unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
7635     unsigned NumSignBits = ComputeNumSignBits(Op);
7636
7637     if (OpBits == DestBits) {
7638       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
7639       // bits, it is already ready.
7640       if (NumSignBits > DestBits-MidBits)
7641         return ReplaceInstUsesWith(CI, Op);
7642     } else if (OpBits < DestBits) {
7643       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
7644       // bits, just sext from i32.
7645       if (NumSignBits > OpBits-MidBits)
7646         return new SExtInst(Op, CI.getType(), "tmp");
7647     } else {
7648       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
7649       // bits, just truncate to i32.
7650       if (NumSignBits > OpBits-MidBits)
7651         return new TruncInst(Op, CI.getType(), "tmp");
7652     }
7653   }
7654       
7655   return 0;
7656 }
7657
7658 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7659 /// in the specified FP type without changing its value.
7660 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
7661   APFloat F = CFP->getValueAPF();
7662   if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7663     return ConstantFP::get(F);
7664   return 0;
7665 }
7666
7667 /// LookThroughFPExtensions - If this is an fp extension instruction, look
7668 /// through it until we get the source value.
7669 static Value *LookThroughFPExtensions(Value *V) {
7670   if (Instruction *I = dyn_cast<Instruction>(V))
7671     if (I->getOpcode() == Instruction::FPExt)
7672       return LookThroughFPExtensions(I->getOperand(0));
7673   
7674   // If this value is a constant, return the constant in the smallest FP type
7675   // that can accurately represent it.  This allows us to turn
7676   // (float)((double)X+2.0) into x+2.0f.
7677   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7678     if (CFP->getType() == Type::PPC_FP128Ty)
7679       return V;  // No constant folding of this.
7680     // See if the value can be truncated to float and then reextended.
7681     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
7682       return V;
7683     if (CFP->getType() == Type::DoubleTy)
7684       return V;  // Won't shrink.
7685     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
7686       return V;
7687     // Don't try to shrink to various long double types.
7688   }
7689   
7690   return V;
7691 }
7692
7693 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7694   if (Instruction *I = commonCastTransforms(CI))
7695     return I;
7696   
7697   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7698   // smaller than the destination type, we can eliminate the truncate by doing
7699   // the add as the smaller type.  This applies to add/sub/mul/div as well as
7700   // many builtins (sqrt, etc).
7701   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7702   if (OpI && OpI->hasOneUse()) {
7703     switch (OpI->getOpcode()) {
7704     default: break;
7705     case Instruction::Add:
7706     case Instruction::Sub:
7707     case Instruction::Mul:
7708     case Instruction::FDiv:
7709     case Instruction::FRem:
7710       const Type *SrcTy = OpI->getType();
7711       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7712       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7713       if (LHSTrunc->getType() != SrcTy && 
7714           RHSTrunc->getType() != SrcTy) {
7715         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7716         // If the source types were both smaller than the destination type of
7717         // the cast, do this xform.
7718         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7719             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7720           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7721                                       CI.getType(), CI);
7722           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7723                                       CI.getType(), CI);
7724           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7725         }
7726       }
7727       break;  
7728     }
7729   }
7730   return 0;
7731 }
7732
7733 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7734   return commonCastTransforms(CI);
7735 }
7736
7737 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
7738   // fptoui(uitofp(X)) --> X  if the intermediate type has enough bits in its
7739   // mantissa to accurately represent all values of X.  For example, do not
7740   // do this with i64->float->i64.
7741   if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
7742     if (SrcI->getOperand(0)->getType() == FI.getType() &&
7743         (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
7744                     SrcI->getType()->getFPMantissaWidth())
7745       return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7746
7747   return commonCastTransforms(FI);
7748 }
7749
7750 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
7751   // fptosi(sitofp(X)) --> X  if the intermediate type has enough bits in its
7752   // mantissa to accurately represent all values of X.  For example, do not
7753   // do this with i64->float->i64.
7754   if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
7755     if (SrcI->getOperand(0)->getType() == FI.getType() &&
7756         (int)FI.getType()->getPrimitiveSizeInBits() <= 
7757                     SrcI->getType()->getFPMantissaWidth())
7758       return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7759   
7760   return commonCastTransforms(FI);
7761 }
7762
7763 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7764   return commonCastTransforms(CI);
7765 }
7766
7767 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7768   return commonCastTransforms(CI);
7769 }
7770
7771 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7772   return commonPointerCastTransforms(CI);
7773 }
7774
7775 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7776   if (Instruction *I = commonCastTransforms(CI))
7777     return I;
7778   
7779   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7780   if (!DestPointee->isSized()) return 0;
7781
7782   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7783   ConstantInt *Cst;
7784   Value *X;
7785   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7786                                     m_ConstantInt(Cst)))) {
7787     // If the source and destination operands have the same type, see if this
7788     // is a single-index GEP.
7789     if (X->getType() == CI.getType()) {
7790       // Get the size of the pointee type.
7791       uint64_t Size = TD->getABITypeSize(DestPointee);
7792
7793       // Convert the constant to intptr type.
7794       APInt Offset = Cst->getValue();
7795       Offset.sextOrTrunc(TD->getPointerSizeInBits());
7796
7797       // If Offset is evenly divisible by Size, we can do this xform.
7798       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7799         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7800         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
7801       }
7802     }
7803     // TODO: Could handle other cases, e.g. where add is indexing into field of
7804     // struct etc.
7805   } else if (CI.getOperand(0)->hasOneUse() &&
7806              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7807     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7808     // "inttoptr+GEP" instead of "add+intptr".
7809     
7810     // Get the size of the pointee type.
7811     uint64_t Size = TD->getABITypeSize(DestPointee);
7812     
7813     // Convert the constant to intptr type.
7814     APInt Offset = Cst->getValue();
7815     Offset.sextOrTrunc(TD->getPointerSizeInBits());
7816     
7817     // If Offset is evenly divisible by Size, we can do this xform.
7818     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7819       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7820       
7821       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7822                                                             "tmp"), CI);
7823       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
7824     }
7825   }
7826   return 0;
7827 }
7828
7829 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7830   // If the operands are integer typed then apply the integer transforms,
7831   // otherwise just apply the common ones.
7832   Value *Src = CI.getOperand(0);
7833   const Type *SrcTy = Src->getType();
7834   const Type *DestTy = CI.getType();
7835
7836   if (SrcTy->isInteger() && DestTy->isInteger()) {
7837     if (Instruction *Result = commonIntCastTransforms(CI))
7838       return Result;
7839   } else if (isa<PointerType>(SrcTy)) {
7840     if (Instruction *I = commonPointerCastTransforms(CI))
7841       return I;
7842   } else {
7843     if (Instruction *Result = commonCastTransforms(CI))
7844       return Result;
7845   }
7846
7847
7848   // Get rid of casts from one type to the same type. These are useless and can
7849   // be replaced by the operand.
7850   if (DestTy == Src->getType())
7851     return ReplaceInstUsesWith(CI, Src);
7852
7853   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7854     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7855     const Type *DstElTy = DstPTy->getElementType();
7856     const Type *SrcElTy = SrcPTy->getElementType();
7857     
7858     // If the address spaces don't match, don't eliminate the bitcast, which is
7859     // required for changing types.
7860     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7861       return 0;
7862     
7863     // If we are casting a malloc or alloca to a pointer to a type of the same
7864     // size, rewrite the allocation instruction to allocate the "right" type.
7865     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7866       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7867         return V;
7868     
7869     // If the source and destination are pointers, and this cast is equivalent
7870     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
7871     // This can enhance SROA and other transforms that want type-safe pointers.
7872     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7873     unsigned NumZeros = 0;
7874     while (SrcElTy != DstElTy && 
7875            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7876            SrcElTy->getNumContainedTypes() /* not "{}" */) {
7877       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7878       ++NumZeros;
7879     }
7880
7881     // If we found a path from the src to dest, create the getelementptr now.
7882     if (SrcElTy == DstElTy) {
7883       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
7884       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
7885                                        ((Instruction*) NULL));
7886     }
7887   }
7888
7889   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7890     if (SVI->hasOneUse()) {
7891       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
7892       // a bitconvert to a vector with the same # elts.
7893       if (isa<VectorType>(DestTy) && 
7894           cast<VectorType>(DestTy)->getNumElements() == 
7895                 SVI->getType()->getNumElements()) {
7896         CastInst *Tmp;
7897         // If either of the operands is a cast from CI.getType(), then
7898         // evaluating the shuffle in the casted destination's type will allow
7899         // us to eliminate at least one cast.
7900         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
7901              Tmp->getOperand(0)->getType() == DestTy) ||
7902             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
7903              Tmp->getOperand(0)->getType() == DestTy)) {
7904           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7905                                                SVI->getOperand(0), DestTy, &CI);
7906           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7907                                                SVI->getOperand(1), DestTy, &CI);
7908           // Return a new shuffle vector.  Use the same element ID's, as we
7909           // know the vector types match #elts.
7910           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7911         }
7912       }
7913     }
7914   }
7915   return 0;
7916 }
7917
7918 /// GetSelectFoldableOperands - We want to turn code that looks like this:
7919 ///   %C = or %A, %B
7920 ///   %D = select %cond, %C, %A
7921 /// into:
7922 ///   %C = select %cond, %B, 0
7923 ///   %D = or %A, %C
7924 ///
7925 /// Assuming that the specified instruction is an operand to the select, return
7926 /// a bitmask indicating which operands of this instruction are foldable if they
7927 /// equal the other incoming value of the select.
7928 ///
7929 static unsigned GetSelectFoldableOperands(Instruction *I) {
7930   switch (I->getOpcode()) {
7931   case Instruction::Add:
7932   case Instruction::Mul:
7933   case Instruction::And:
7934   case Instruction::Or:
7935   case Instruction::Xor:
7936     return 3;              // Can fold through either operand.
7937   case Instruction::Sub:   // Can only fold on the amount subtracted.
7938   case Instruction::Shl:   // Can only fold on the shift amount.
7939   case Instruction::LShr:
7940   case Instruction::AShr:
7941     return 1;
7942   default:
7943     return 0;              // Cannot fold
7944   }
7945 }
7946
7947 /// GetSelectFoldableConstant - For the same transformation as the previous
7948 /// function, return the identity constant that goes into the select.
7949 static Constant *GetSelectFoldableConstant(Instruction *I) {
7950   switch (I->getOpcode()) {
7951   default: assert(0 && "This cannot happen!"); abort();
7952   case Instruction::Add:
7953   case Instruction::Sub:
7954   case Instruction::Or:
7955   case Instruction::Xor:
7956   case Instruction::Shl:
7957   case Instruction::LShr:
7958   case Instruction::AShr:
7959     return Constant::getNullValue(I->getType());
7960   case Instruction::And:
7961     return Constant::getAllOnesValue(I->getType());
7962   case Instruction::Mul:
7963     return ConstantInt::get(I->getType(), 1);
7964   }
7965 }
7966
7967 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7968 /// have the same opcode and only one use each.  Try to simplify this.
7969 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7970                                           Instruction *FI) {
7971   if (TI->getNumOperands() == 1) {
7972     // If this is a non-volatile load or a cast from the same type,
7973     // merge.
7974     if (TI->isCast()) {
7975       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7976         return 0;
7977     } else {
7978       return 0;  // unknown unary op.
7979     }
7980
7981     // Fold this by inserting a select from the input values.
7982     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
7983                                            FI->getOperand(0), SI.getName()+".v");
7984     InsertNewInstBefore(NewSI, SI);
7985     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
7986                             TI->getType());
7987   }
7988
7989   // Only handle binary operators here.
7990   if (!isa<BinaryOperator>(TI))
7991     return 0;
7992
7993   // Figure out if the operations have any operands in common.
7994   Value *MatchOp, *OtherOpT, *OtherOpF;
7995   bool MatchIsOpZero;
7996   if (TI->getOperand(0) == FI->getOperand(0)) {
7997     MatchOp  = TI->getOperand(0);
7998     OtherOpT = TI->getOperand(1);
7999     OtherOpF = FI->getOperand(1);
8000     MatchIsOpZero = true;
8001   } else if (TI->getOperand(1) == FI->getOperand(1)) {
8002     MatchOp  = TI->getOperand(1);
8003     OtherOpT = TI->getOperand(0);
8004     OtherOpF = FI->getOperand(0);
8005     MatchIsOpZero = false;
8006   } else if (!TI->isCommutative()) {
8007     return 0;
8008   } else if (TI->getOperand(0) == FI->getOperand(1)) {
8009     MatchOp  = TI->getOperand(0);
8010     OtherOpT = TI->getOperand(1);
8011     OtherOpF = FI->getOperand(0);
8012     MatchIsOpZero = true;
8013   } else if (TI->getOperand(1) == FI->getOperand(0)) {
8014     MatchOp  = TI->getOperand(1);
8015     OtherOpT = TI->getOperand(0);
8016     OtherOpF = FI->getOperand(1);
8017     MatchIsOpZero = true;
8018   } else {
8019     return 0;
8020   }
8021
8022   // If we reach here, they do have operations in common.
8023   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8024                                          OtherOpF, SI.getName()+".v");
8025   InsertNewInstBefore(NewSI, SI);
8026
8027   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8028     if (MatchIsOpZero)
8029       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8030     else
8031       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8032   }
8033   assert(0 && "Shouldn't get here");
8034   return 0;
8035 }
8036
8037 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8038   Value *CondVal = SI.getCondition();
8039   Value *TrueVal = SI.getTrueValue();
8040   Value *FalseVal = SI.getFalseValue();
8041
8042   // select true, X, Y  -> X
8043   // select false, X, Y -> Y
8044   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8045     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8046
8047   // select C, X, X -> X
8048   if (TrueVal == FalseVal)
8049     return ReplaceInstUsesWith(SI, TrueVal);
8050
8051   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
8052     return ReplaceInstUsesWith(SI, FalseVal);
8053   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
8054     return ReplaceInstUsesWith(SI, TrueVal);
8055   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
8056     if (isa<Constant>(TrueVal))
8057       return ReplaceInstUsesWith(SI, TrueVal);
8058     else
8059       return ReplaceInstUsesWith(SI, FalseVal);
8060   }
8061
8062   if (SI.getType() == Type::Int1Ty) {
8063     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8064       if (C->getZExtValue()) {
8065         // Change: A = select B, true, C --> A = or B, C
8066         return BinaryOperator::CreateOr(CondVal, FalseVal);
8067       } else {
8068         // Change: A = select B, false, C --> A = and !B, C
8069         Value *NotCond =
8070           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8071                                              "not."+CondVal->getName()), SI);
8072         return BinaryOperator::CreateAnd(NotCond, FalseVal);
8073       }
8074     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8075       if (C->getZExtValue() == false) {
8076         // Change: A = select B, C, false --> A = and B, C
8077         return BinaryOperator::CreateAnd(CondVal, TrueVal);
8078       } else {
8079         // Change: A = select B, C, true --> A = or !B, C
8080         Value *NotCond =
8081           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8082                                              "not."+CondVal->getName()), SI);
8083         return BinaryOperator::CreateOr(NotCond, TrueVal);
8084       }
8085     }
8086     
8087     // select a, b, a  -> a&b
8088     // select a, a, b  -> a|b
8089     if (CondVal == TrueVal)
8090       return BinaryOperator::CreateOr(CondVal, FalseVal);
8091     else if (CondVal == FalseVal)
8092       return BinaryOperator::CreateAnd(CondVal, TrueVal);
8093   }
8094
8095   // Selecting between two integer constants?
8096   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8097     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8098       // select C, 1, 0 -> zext C to int
8099       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8100         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
8101       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8102         // select C, 0, 1 -> zext !C to int
8103         Value *NotCond =
8104           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8105                                                "not."+CondVal->getName()), SI);
8106         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
8107       }
8108       
8109       // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8110
8111       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8112
8113         // (x <s 0) ? -1 : 0 -> ashr x, 31
8114         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8115           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8116             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8117               // The comparison constant and the result are not neccessarily the
8118               // same width. Make an all-ones value by inserting a AShr.
8119               Value *X = IC->getOperand(0);
8120               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8121               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8122               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
8123                                                         ShAmt, "ones");
8124               InsertNewInstBefore(SRA, SI);
8125               
8126               // Finally, convert to the type of the select RHS.  We figure out
8127               // if this requires a SExt, Trunc or BitCast based on the sizes.
8128               Instruction::CastOps opc = Instruction::BitCast;
8129               uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8130               uint32_t SISize  = SI.getType()->getPrimitiveSizeInBits();
8131               if (SRASize < SISize)
8132                 opc = Instruction::SExt;
8133               else if (SRASize > SISize)
8134                 opc = Instruction::Trunc;
8135               return CastInst::Create(opc, SRA, SI.getType());
8136             }
8137           }
8138
8139
8140         // If one of the constants is zero (we know they can't both be) and we
8141         // have an icmp instruction with zero, and we have an 'and' with the
8142         // non-constant value, eliminate this whole mess.  This corresponds to
8143         // cases like this: ((X & 27) ? 27 : 0)
8144         if (TrueValC->isZero() || FalseValC->isZero())
8145           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8146               cast<Constant>(IC->getOperand(1))->isNullValue())
8147             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8148               if (ICA->getOpcode() == Instruction::And &&
8149                   isa<ConstantInt>(ICA->getOperand(1)) &&
8150                   (ICA->getOperand(1) == TrueValC ||
8151                    ICA->getOperand(1) == FalseValC) &&
8152                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8153                 // Okay, now we know that everything is set up, we just don't
8154                 // know whether we have a icmp_ne or icmp_eq and whether the 
8155                 // true or false val is the zero.
8156                 bool ShouldNotVal = !TrueValC->isZero();
8157                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8158                 Value *V = ICA;
8159                 if (ShouldNotVal)
8160                   V = InsertNewInstBefore(BinaryOperator::Create(
8161                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
8162                 return ReplaceInstUsesWith(SI, V);
8163               }
8164       }
8165     }
8166
8167   // See if we are selecting two values based on a comparison of the two values.
8168   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8169     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8170       // Transform (X == Y) ? X : Y  -> Y
8171       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8172         // This is not safe in general for floating point:  
8173         // consider X== -0, Y== +0.
8174         // It becomes safe if either operand is a nonzero constant.
8175         ConstantFP *CFPt, *CFPf;
8176         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8177               !CFPt->getValueAPF().isZero()) ||
8178             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8179              !CFPf->getValueAPF().isZero()))
8180         return ReplaceInstUsesWith(SI, FalseVal);
8181       }
8182       // Transform (X != Y) ? X : Y  -> X
8183       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8184         return ReplaceInstUsesWith(SI, TrueVal);
8185       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8186
8187     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8188       // Transform (X == Y) ? Y : X  -> X
8189       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8190         // This is not safe in general for floating point:  
8191         // consider X== -0, Y== +0.
8192         // It becomes safe if either operand is a nonzero constant.
8193         ConstantFP *CFPt, *CFPf;
8194         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8195               !CFPt->getValueAPF().isZero()) ||
8196             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8197              !CFPf->getValueAPF().isZero()))
8198           return ReplaceInstUsesWith(SI, FalseVal);
8199       }
8200       // Transform (X != Y) ? Y : X  -> Y
8201       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8202         return ReplaceInstUsesWith(SI, TrueVal);
8203       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8204     }
8205   }
8206
8207   // See if we are selecting two values based on a comparison of the two values.
8208   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8209     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8210       // Transform (X == Y) ? X : Y  -> Y
8211       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8212         return ReplaceInstUsesWith(SI, FalseVal);
8213       // Transform (X != Y) ? X : Y  -> X
8214       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8215         return ReplaceInstUsesWith(SI, TrueVal);
8216       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8217
8218     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8219       // Transform (X == Y) ? Y : X  -> X
8220       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8221         return ReplaceInstUsesWith(SI, FalseVal);
8222       // Transform (X != Y) ? Y : X  -> Y
8223       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8224         return ReplaceInstUsesWith(SI, TrueVal);
8225       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8226     }
8227   }
8228
8229   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8230     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8231       if (TI->hasOneUse() && FI->hasOneUse()) {
8232         Instruction *AddOp = 0, *SubOp = 0;
8233
8234         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8235         if (TI->getOpcode() == FI->getOpcode())
8236           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8237             return IV;
8238
8239         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
8240         // even legal for FP.
8241         if (TI->getOpcode() == Instruction::Sub &&
8242             FI->getOpcode() == Instruction::Add) {
8243           AddOp = FI; SubOp = TI;
8244         } else if (FI->getOpcode() == Instruction::Sub &&
8245                    TI->getOpcode() == Instruction::Add) {
8246           AddOp = TI; SubOp = FI;
8247         }
8248
8249         if (AddOp) {
8250           Value *OtherAddOp = 0;
8251           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8252             OtherAddOp = AddOp->getOperand(1);
8253           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8254             OtherAddOp = AddOp->getOperand(0);
8255           }
8256
8257           if (OtherAddOp) {
8258             // So at this point we know we have (Y -> OtherAddOp):
8259             //        select C, (add X, Y), (sub X, Z)
8260             Value *NegVal;  // Compute -Z
8261             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8262               NegVal = ConstantExpr::getNeg(C);
8263             } else {
8264               NegVal = InsertNewInstBefore(
8265                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
8266             }
8267
8268             Value *NewTrueOp = OtherAddOp;
8269             Value *NewFalseOp = NegVal;
8270             if (AddOp != TI)
8271               std::swap(NewTrueOp, NewFalseOp);
8272             Instruction *NewSel =
8273               SelectInst::Create(CondVal, NewTrueOp,
8274                                  NewFalseOp, SI.getName() + ".p");
8275
8276             NewSel = InsertNewInstBefore(NewSel, SI);
8277             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
8278           }
8279         }
8280       }
8281
8282   // See if we can fold the select into one of our operands.
8283   if (SI.getType()->isInteger()) {
8284     // See the comment above GetSelectFoldableOperands for a description of the
8285     // transformation we are doing here.
8286     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8287       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8288           !isa<Constant>(FalseVal))
8289         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8290           unsigned OpToFold = 0;
8291           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8292             OpToFold = 1;
8293           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8294             OpToFold = 2;
8295           }
8296
8297           if (OpToFold) {
8298             Constant *C = GetSelectFoldableConstant(TVI);
8299             Instruction *NewSel =
8300               SelectInst::Create(SI.getCondition(),
8301                                  TVI->getOperand(2-OpToFold), C);
8302             InsertNewInstBefore(NewSel, SI);
8303             NewSel->takeName(TVI);
8304             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8305               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
8306             else {
8307               assert(0 && "Unknown instruction!!");
8308             }
8309           }
8310         }
8311
8312     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8313       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8314           !isa<Constant>(TrueVal))
8315         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8316           unsigned OpToFold = 0;
8317           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8318             OpToFold = 1;
8319           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8320             OpToFold = 2;
8321           }
8322
8323           if (OpToFold) {
8324             Constant *C = GetSelectFoldableConstant(FVI);
8325             Instruction *NewSel =
8326               SelectInst::Create(SI.getCondition(), C,
8327                                  FVI->getOperand(2-OpToFold));
8328             InsertNewInstBefore(NewSel, SI);
8329             NewSel->takeName(FVI);
8330             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8331               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
8332             else
8333               assert(0 && "Unknown instruction!!");
8334           }
8335         }
8336   }
8337
8338   if (BinaryOperator::isNot(CondVal)) {
8339     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8340     SI.setOperand(1, FalseVal);
8341     SI.setOperand(2, TrueVal);
8342     return &SI;
8343   }
8344
8345   return 0;
8346 }
8347
8348 /// EnforceKnownAlignment - If the specified pointer points to an object that
8349 /// we control, modify the object's alignment to PrefAlign. This isn't
8350 /// often possible though. If alignment is important, a more reliable approach
8351 /// is to simply align all global variables and allocation instructions to
8352 /// their preferred alignment from the beginning.
8353 ///
8354 static unsigned EnforceKnownAlignment(Value *V,
8355                                       unsigned Align, unsigned PrefAlign) {
8356
8357   User *U = dyn_cast<User>(V);
8358   if (!U) return Align;
8359
8360   switch (getOpcode(U)) {
8361   default: break;
8362   case Instruction::BitCast:
8363     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8364   case Instruction::GetElementPtr: {
8365     // If all indexes are zero, it is just the alignment of the base pointer.
8366     bool AllZeroOperands = true;
8367     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
8368       if (!isa<Constant>(*i) ||
8369           !cast<Constant>(*i)->isNullValue()) {
8370         AllZeroOperands = false;
8371         break;
8372       }
8373
8374     if (AllZeroOperands) {
8375       // Treat this like a bitcast.
8376       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8377     }
8378     break;
8379   }
8380   }
8381
8382   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8383     // If there is a large requested alignment and we can, bump up the alignment
8384     // of the global.
8385     if (!GV->isDeclaration()) {
8386       GV->setAlignment(PrefAlign);
8387       Align = PrefAlign;
8388     }
8389   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8390     // If there is a requested alignment and if this is an alloca, round up.  We
8391     // don't do this for malloc, because some systems can't respect the request.
8392     if (isa<AllocaInst>(AI)) {
8393       AI->setAlignment(PrefAlign);
8394       Align = PrefAlign;
8395     }
8396   }
8397
8398   return Align;
8399 }
8400
8401 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8402 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
8403 /// and it is more than the alignment of the ultimate object, see if we can
8404 /// increase the alignment of the ultimate object, making this check succeed.
8405 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8406                                                   unsigned PrefAlign) {
8407   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8408                       sizeof(PrefAlign) * CHAR_BIT;
8409   APInt Mask = APInt::getAllOnesValue(BitWidth);
8410   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8411   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8412   unsigned TrailZ = KnownZero.countTrailingOnes();
8413   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8414
8415   if (PrefAlign > Align)
8416     Align = EnforceKnownAlignment(V, Align, PrefAlign);
8417   
8418     // We don't need to make any adjustment.
8419   return Align;
8420 }
8421
8422 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
8423   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8424   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
8425   unsigned MinAlign = std::min(DstAlign, SrcAlign);
8426   unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8427
8428   if (CopyAlign < MinAlign) {
8429     MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8430     return MI;
8431   }
8432   
8433   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8434   // load/store.
8435   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8436   if (MemOpLength == 0) return 0;
8437   
8438   // Source and destination pointer types are always "i8*" for intrinsic.  See
8439   // if the size is something we can handle with a single primitive load/store.
8440   // A single load+store correctly handles overlapping memory in the memmove
8441   // case.
8442   unsigned Size = MemOpLength->getZExtValue();
8443   if (Size == 0) return MI;  // Delete this mem transfer.
8444   
8445   if (Size > 8 || (Size&(Size-1)))
8446     return 0;  // If not 1/2/4/8 bytes, exit.
8447   
8448   // Use an integer load+store unless we can find something better.
8449   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
8450   
8451   // Memcpy forces the use of i8* for the source and destination.  That means
8452   // that if you're using memcpy to move one double around, you'll get a cast
8453   // from double* to i8*.  We'd much rather use a double load+store rather than
8454   // an i64 load+store, here because this improves the odds that the source or
8455   // dest address will be promotable.  See if we can find a better type than the
8456   // integer datatype.
8457   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8458     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8459     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8460       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
8461       // down through these levels if so.
8462       while (!SrcETy->isSingleValueType()) {
8463         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8464           if (STy->getNumElements() == 1)
8465             SrcETy = STy->getElementType(0);
8466           else
8467             break;
8468         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8469           if (ATy->getNumElements() == 1)
8470             SrcETy = ATy->getElementType();
8471           else
8472             break;
8473         } else
8474           break;
8475       }
8476       
8477       if (SrcETy->isSingleValueType())
8478         NewPtrTy = PointerType::getUnqual(SrcETy);
8479     }
8480   }
8481   
8482   
8483   // If the memcpy/memmove provides better alignment info than we can
8484   // infer, use it.
8485   SrcAlign = std::max(SrcAlign, CopyAlign);
8486   DstAlign = std::max(DstAlign, CopyAlign);
8487   
8488   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8489   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
8490   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8491   InsertNewInstBefore(L, *MI);
8492   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8493
8494   // Set the size of the copy to 0, it will be deleted on the next iteration.
8495   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8496   return MI;
8497 }
8498
8499 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8500   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8501   if (MI->getAlignment()->getZExtValue() < Alignment) {
8502     MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8503     return MI;
8504   }
8505   
8506   // Extract the length and alignment and fill if they are constant.
8507   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8508   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8509   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8510     return 0;
8511   uint64_t Len = LenC->getZExtValue();
8512   Alignment = MI->getAlignment()->getZExtValue();
8513   
8514   // If the length is zero, this is a no-op
8515   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8516   
8517   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8518   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8519     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
8520     
8521     Value *Dest = MI->getDest();
8522     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8523
8524     // Alignment 0 is identity for alignment 1 for memset, but not store.
8525     if (Alignment == 0) Alignment = 1;
8526     
8527     // Extract the fill value and store.
8528     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8529     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8530                                       Alignment), *MI);
8531     
8532     // Set the size of the copy to 0, it will be deleted on the next iteration.
8533     MI->setLength(Constant::getNullValue(LenC->getType()));
8534     return MI;
8535   }
8536
8537   return 0;
8538 }
8539
8540
8541 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
8542 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
8543 /// the heavy lifting.
8544 ///
8545 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8546   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8547   if (!II) return visitCallSite(&CI);
8548   
8549   // Intrinsics cannot occur in an invoke, so handle them here instead of in
8550   // visitCallSite.
8551   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8552     bool Changed = false;
8553
8554     // memmove/cpy/set of zero bytes is a noop.
8555     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8556       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8557
8558       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8559         if (CI->getZExtValue() == 1) {
8560           // Replace the instruction with just byte operations.  We would
8561           // transform other cases to loads/stores, but we don't know if
8562           // alignment is sufficient.
8563         }
8564     }
8565
8566     // If we have a memmove and the source operation is a constant global,
8567     // then the source and dest pointers can't alias, so we can change this
8568     // into a call to memcpy.
8569     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
8570       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8571         if (GVSrc->isConstant()) {
8572           Module *M = CI.getParent()->getParent()->getParent();
8573           Intrinsic::ID MemCpyID;
8574           if (CI.getOperand(3)->getType() == Type::Int32Ty)
8575             MemCpyID = Intrinsic::memcpy_i32;
8576           else
8577             MemCpyID = Intrinsic::memcpy_i64;
8578           CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
8579           Changed = true;
8580         }
8581
8582       // memmove(x,x,size) -> noop.
8583       if (MMI->getSource() == MMI->getDest())
8584         return EraseInstFromFunction(CI);
8585     }
8586
8587     // If we can determine a pointer alignment that is bigger than currently
8588     // set, update the alignment.
8589     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
8590       if (Instruction *I = SimplifyMemTransfer(MI))
8591         return I;
8592     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8593       if (Instruction *I = SimplifyMemSet(MSI))
8594         return I;
8595     }
8596           
8597     if (Changed) return II;
8598   }
8599   
8600   switch (II->getIntrinsicID()) {
8601   default: break;
8602   case Intrinsic::bswap:
8603     // bswap(bswap(x)) -> x
8604     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
8605       if (Operand->getIntrinsicID() == Intrinsic::bswap)
8606         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
8607     break;
8608   case Intrinsic::ppc_altivec_lvx:
8609   case Intrinsic::ppc_altivec_lvxl:
8610   case Intrinsic::x86_sse_loadu_ps:
8611   case Intrinsic::x86_sse2_loadu_pd:
8612   case Intrinsic::x86_sse2_loadu_dq:
8613     // Turn PPC lvx     -> load if the pointer is known aligned.
8614     // Turn X86 loadups -> load if the pointer is known aligned.
8615     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8616       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8617                                        PointerType::getUnqual(II->getType()),
8618                                        CI);
8619       return new LoadInst(Ptr);
8620     }
8621     break;
8622   case Intrinsic::ppc_altivec_stvx:
8623   case Intrinsic::ppc_altivec_stvxl:
8624     // Turn stvx -> store if the pointer is known aligned.
8625     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
8626       const Type *OpPtrTy = 
8627         PointerType::getUnqual(II->getOperand(1)->getType());
8628       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
8629       return new StoreInst(II->getOperand(1), Ptr);
8630     }
8631     break;
8632   case Intrinsic::x86_sse_storeu_ps:
8633   case Intrinsic::x86_sse2_storeu_pd:
8634   case Intrinsic::x86_sse2_storeu_dq:
8635     // Turn X86 storeu -> store if the pointer is known aligned.
8636     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8637       const Type *OpPtrTy = 
8638         PointerType::getUnqual(II->getOperand(2)->getType());
8639       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
8640       return new StoreInst(II->getOperand(2), Ptr);
8641     }
8642     break;
8643     
8644   case Intrinsic::x86_sse_cvttss2si: {
8645     // These intrinsics only demands the 0th element of its input vector.  If
8646     // we can simplify the input based on that, do so now.
8647     uint64_t UndefElts;
8648     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
8649                                               UndefElts)) {
8650       II->setOperand(1, V);
8651       return II;
8652     }
8653     break;
8654   }
8655     
8656   case Intrinsic::ppc_altivec_vperm:
8657     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8658     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8659       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8660       
8661       // Check that all of the elements are integer constants or undefs.
8662       bool AllEltsOk = true;
8663       for (unsigned i = 0; i != 16; ++i) {
8664         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
8665             !isa<UndefValue>(Mask->getOperand(i))) {
8666           AllEltsOk = false;
8667           break;
8668         }
8669       }
8670       
8671       if (AllEltsOk) {
8672         // Cast the input vectors to byte vectors.
8673         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8674         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
8675         Value *Result = UndefValue::get(Op0->getType());
8676         
8677         // Only extract each element once.
8678         Value *ExtractedElts[32];
8679         memset(ExtractedElts, 0, sizeof(ExtractedElts));
8680         
8681         for (unsigned i = 0; i != 16; ++i) {
8682           if (isa<UndefValue>(Mask->getOperand(i)))
8683             continue;
8684           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8685           Idx &= 31;  // Match the hardware behavior.
8686           
8687           if (ExtractedElts[Idx] == 0) {
8688             Instruction *Elt = 
8689               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8690             InsertNewInstBefore(Elt, CI);
8691             ExtractedElts[Idx] = Elt;
8692           }
8693         
8694           // Insert this value into the result vector.
8695           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8696                                              i, "tmp");
8697           InsertNewInstBefore(cast<Instruction>(Result), CI);
8698         }
8699         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
8700       }
8701     }
8702     break;
8703
8704   case Intrinsic::stackrestore: {
8705     // If the save is right next to the restore, remove the restore.  This can
8706     // happen when variable allocas are DCE'd.
8707     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8708       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8709         BasicBlock::iterator BI = SS;
8710         if (&*++BI == II)
8711           return EraseInstFromFunction(CI);
8712       }
8713     }
8714     
8715     // Scan down this block to see if there is another stack restore in the
8716     // same block without an intervening call/alloca.
8717     BasicBlock::iterator BI = II;
8718     TerminatorInst *TI = II->getParent()->getTerminator();
8719     bool CannotRemove = false;
8720     for (++BI; &*BI != TI; ++BI) {
8721       if (isa<AllocaInst>(BI)) {
8722         CannotRemove = true;
8723         break;
8724       }
8725       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
8726         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
8727           // If there is a stackrestore below this one, remove this one.
8728           if (II->getIntrinsicID() == Intrinsic::stackrestore)
8729             return EraseInstFromFunction(CI);
8730           // Otherwise, ignore the intrinsic.
8731         } else {
8732           // If we found a non-intrinsic call, we can't remove the stack
8733           // restore.
8734           CannotRemove = true;
8735           break;
8736         }
8737       }
8738     }
8739     
8740     // If the stack restore is in a return/unwind block and if there are no
8741     // allocas or calls between the restore and the return, nuke the restore.
8742     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8743       return EraseInstFromFunction(CI);
8744     break;
8745   }
8746   }
8747
8748   return visitCallSite(II);
8749 }
8750
8751 // InvokeInst simplification
8752 //
8753 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8754   return visitCallSite(&II);
8755 }
8756
8757 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
8758 /// passed through the varargs area, we can eliminate the use of the cast.
8759 static bool isSafeToEliminateVarargsCast(const CallSite CS,
8760                                          const CastInst * const CI,
8761                                          const TargetData * const TD,
8762                                          const int ix) {
8763   if (!CI->isLosslessCast())
8764     return false;
8765
8766   // The size of ByVal arguments is derived from the type, so we
8767   // can't change to a type with a different size.  If the size were
8768   // passed explicitly we could avoid this check.
8769   if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8770     return true;
8771
8772   const Type* SrcTy = 
8773             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
8774   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
8775   if (!SrcTy->isSized() || !DstTy->isSized())
8776     return false;
8777   if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
8778     return false;
8779   return true;
8780 }
8781
8782 // visitCallSite - Improvements for call and invoke instructions.
8783 //
8784 Instruction *InstCombiner::visitCallSite(CallSite CS) {
8785   bool Changed = false;
8786
8787   // If the callee is a constexpr cast of a function, attempt to move the cast
8788   // to the arguments of the call/invoke.
8789   if (transformConstExprCastCall(CS)) return 0;
8790
8791   Value *Callee = CS.getCalledValue();
8792
8793   if (Function *CalleeF = dyn_cast<Function>(Callee))
8794     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8795       Instruction *OldCall = CS.getInstruction();
8796       // If the call and callee calling conventions don't match, this call must
8797       // be unreachable, as the call is undefined.
8798       new StoreInst(ConstantInt::getTrue(),
8799                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
8800                                     OldCall);
8801       if (!OldCall->use_empty())
8802         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8803       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
8804         return EraseInstFromFunction(*OldCall);
8805       return 0;
8806     }
8807
8808   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8809     // This instruction is not reachable, just remove it.  We insert a store to
8810     // undef so that we know that this code is not reachable, despite the fact
8811     // that we can't modify the CFG here.
8812     new StoreInst(ConstantInt::getTrue(),
8813                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8814                   CS.getInstruction());
8815
8816     if (!CS.getInstruction()->use_empty())
8817       CS.getInstruction()->
8818         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8819
8820     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8821       // Don't break the CFG, insert a dummy cond branch.
8822       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8823                          ConstantInt::getTrue(), II);
8824     }
8825     return EraseInstFromFunction(*CS.getInstruction());
8826   }
8827
8828   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8829     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8830       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8831         return transformCallThroughTrampoline(CS);
8832
8833   const PointerType *PTy = cast<PointerType>(Callee->getType());
8834   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8835   if (FTy->isVarArg()) {
8836     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
8837     // See if we can optimize any arguments passed through the varargs area of
8838     // the call.
8839     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8840            E = CS.arg_end(); I != E; ++I, ++ix) {
8841       CastInst *CI = dyn_cast<CastInst>(*I);
8842       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
8843         *I = CI->getOperand(0);
8844         Changed = true;
8845       }
8846     }
8847   }
8848
8849   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
8850     // Inline asm calls cannot throw - mark them 'nounwind'.
8851     CS.setDoesNotThrow();
8852     Changed = true;
8853   }
8854
8855   return Changed ? CS.getInstruction() : 0;
8856 }
8857
8858 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
8859 // attempt to move the cast to the arguments of the call/invoke.
8860 //
8861 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8862   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8863   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8864   if (CE->getOpcode() != Instruction::BitCast || 
8865       !isa<Function>(CE->getOperand(0)))
8866     return false;
8867   Function *Callee = cast<Function>(CE->getOperand(0));
8868   Instruction *Caller = CS.getInstruction();
8869   const PAListPtr &CallerPAL = CS.getParamAttrs();
8870
8871   // Okay, this is a cast from a function to a different type.  Unless doing so
8872   // would cause a type conversion of one of our arguments, change this call to
8873   // be a direct call with arguments casted to the appropriate types.
8874   //
8875   const FunctionType *FT = Callee->getFunctionType();
8876   const Type *OldRetTy = Caller->getType();
8877   const Type *NewRetTy = FT->getReturnType();
8878
8879   if (isa<StructType>(NewRetTy))
8880     return false; // TODO: Handle multiple return values.
8881
8882   // Check to see if we are changing the return type...
8883   if (OldRetTy != NewRetTy) {
8884     if (Callee->isDeclaration() &&
8885         // Conversion is ok if changing from one pointer type to another or from
8886         // a pointer to an integer of the same size.
8887         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
8888           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
8889       return false;   // Cannot transform this return value.
8890
8891     if (!Caller->use_empty() &&
8892         // void -> non-void is handled specially
8893         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
8894       return false;   // Cannot transform this return value.
8895
8896     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8897       ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
8898       if (RAttrs & ParamAttr::typeIncompatible(NewRetTy))
8899         return false;   // Attribute not compatible with transformed value.
8900     }
8901
8902     // If the callsite is an invoke instruction, and the return value is used by
8903     // a PHI node in a successor, we cannot change the return type of the call
8904     // because there is no place to put the cast instruction (without breaking
8905     // the critical edge).  Bail out in this case.
8906     if (!Caller->use_empty())
8907       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8908         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8909              UI != E; ++UI)
8910           if (PHINode *PN = dyn_cast<PHINode>(*UI))
8911             if (PN->getParent() == II->getNormalDest() ||
8912                 PN->getParent() == II->getUnwindDest())
8913               return false;
8914   }
8915
8916   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8917   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8918
8919   CallSite::arg_iterator AI = CS.arg_begin();
8920   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8921     const Type *ParamTy = FT->getParamType(i);
8922     const Type *ActTy = (*AI)->getType();
8923
8924     if (!CastInst::isCastable(ActTy, ParamTy))
8925       return false;   // Cannot transform this parameter value.
8926
8927     if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8928       return false;   // Attribute not compatible with transformed value.
8929
8930     // Converting from one pointer type to another or between a pointer and an
8931     // integer of the same size is safe even if we do not have a body.
8932     bool isConvertible = ActTy == ParamTy ||
8933       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
8934        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
8935     if (Callee->isDeclaration() && !isConvertible) return false;
8936   }
8937
8938   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
8939       Callee->isDeclaration())
8940     return false;   // Do not delete arguments unless we have a function body.
8941
8942   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8943       !CallerPAL.isEmpty())
8944     // In this case we have more arguments than the new function type, but we
8945     // won't be dropping them.  Check that these extra arguments have attributes
8946     // that are compatible with being a vararg call argument.
8947     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8948       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
8949         break;
8950       ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
8951       if (PAttrs & ParamAttr::VarArgsIncompatible)
8952         return false;
8953     }
8954
8955   // Okay, we decided that this is a safe thing to do: go ahead and start
8956   // inserting cast instructions as necessary...
8957   std::vector<Value*> Args;
8958   Args.reserve(NumActualArgs);
8959   SmallVector<ParamAttrsWithIndex, 8> attrVec;
8960   attrVec.reserve(NumCommonArgs);
8961
8962   // Get any return attributes.
8963   ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
8964
8965   // If the return value is not being used, the type may not be compatible
8966   // with the existing attributes.  Wipe out any problematic attributes.
8967   RAttrs &= ~ParamAttr::typeIncompatible(NewRetTy);
8968
8969   // Add the new return attributes.
8970   if (RAttrs)
8971     attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
8972
8973   AI = CS.arg_begin();
8974   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8975     const Type *ParamTy = FT->getParamType(i);
8976     if ((*AI)->getType() == ParamTy) {
8977       Args.push_back(*AI);
8978     } else {
8979       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
8980           false, ParamTy, false);
8981       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
8982       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
8983     }
8984
8985     // Add any parameter attributes.
8986     if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
8987       attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8988   }
8989
8990   // If the function takes more arguments than the call was taking, add them
8991   // now...
8992   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8993     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8994
8995   // If we are removing arguments to the function, emit an obnoxious warning...
8996   if (FT->getNumParams() < NumActualArgs) {
8997     if (!FT->isVarArg()) {
8998       cerr << "WARNING: While resolving call to function '"
8999            << Callee->getName() << "' arguments were dropped!\n";
9000     } else {
9001       // Add all of the arguments in their promoted form to the arg list...
9002       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9003         const Type *PTy = getPromotedType((*AI)->getType());
9004         if (PTy != (*AI)->getType()) {
9005           // Must promote to pass through va_arg area!
9006           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
9007                                                                 PTy, false);
9008           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
9009           InsertNewInstBefore(Cast, *Caller);
9010           Args.push_back(Cast);
9011         } else {
9012           Args.push_back(*AI);
9013         }
9014
9015         // Add any parameter attributes.
9016         if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
9017           attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9018       }
9019     }
9020   }
9021
9022   if (NewRetTy == Type::VoidTy)
9023     Caller->setName("");   // Void type should not have a name.
9024
9025   const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
9026
9027   Instruction *NC;
9028   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9029     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9030                             Args.begin(), Args.end(),
9031                             Caller->getName(), Caller);
9032     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
9033     cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
9034   } else {
9035     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9036                           Caller->getName(), Caller);
9037     CallInst *CI = cast<CallInst>(Caller);
9038     if (CI->isTailCall())
9039       cast<CallInst>(NC)->setTailCall();
9040     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
9041     cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
9042   }
9043
9044   // Insert a cast of the return type as necessary.
9045   Value *NV = NC;
9046   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
9047     if (NV->getType() != Type::VoidTy) {
9048       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
9049                                                             OldRetTy, false);
9050       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
9051
9052       // If this is an invoke instruction, we should insert it after the first
9053       // non-phi, instruction in the normal successor block.
9054       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9055         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
9056         InsertNewInstBefore(NC, *I);
9057       } else {
9058         // Otherwise, it's a call, just insert cast right after the call instr
9059         InsertNewInstBefore(NC, *Caller);
9060       }
9061       AddUsersToWorkList(*Caller);
9062     } else {
9063       NV = UndefValue::get(Caller->getType());
9064     }
9065   }
9066
9067   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9068     Caller->replaceAllUsesWith(NV);
9069   Caller->eraseFromParent();
9070   RemoveFromWorkList(Caller);
9071   return true;
9072 }
9073
9074 // transformCallThroughTrampoline - Turn a call to a function created by the
9075 // init_trampoline intrinsic into a direct call to the underlying function.
9076 //
9077 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9078   Value *Callee = CS.getCalledValue();
9079   const PointerType *PTy = cast<PointerType>(Callee->getType());
9080   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9081   const PAListPtr &Attrs = CS.getParamAttrs();
9082
9083   // If the call already has the 'nest' attribute somewhere then give up -
9084   // otherwise 'nest' would occur twice after splicing in the chain.
9085   if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
9086     return 0;
9087
9088   IntrinsicInst *Tramp =
9089     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9090
9091   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9092   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9093   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9094
9095   const PAListPtr &NestAttrs = NestF->getParamAttrs();
9096   if (!NestAttrs.isEmpty()) {
9097     unsigned NestIdx = 1;
9098     const Type *NestTy = 0;
9099     ParameterAttributes NestAttr = ParamAttr::None;
9100
9101     // Look for a parameter marked with the 'nest' attribute.
9102     for (FunctionType::param_iterator I = NestFTy->param_begin(),
9103          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9104       if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
9105         // Record the parameter type and any other attributes.
9106         NestTy = *I;
9107         NestAttr = NestAttrs.getParamAttrs(NestIdx);
9108         break;
9109       }
9110
9111     if (NestTy) {
9112       Instruction *Caller = CS.getInstruction();
9113       std::vector<Value*> NewArgs;
9114       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9115
9116       SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9117       NewAttrs.reserve(Attrs.getNumSlots() + 1);
9118
9119       // Insert the nest argument into the call argument list, which may
9120       // mean appending it.  Likewise for attributes.
9121
9122       // Add any function result attributes.
9123       if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9124         NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
9125
9126       {
9127         unsigned Idx = 1;
9128         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9129         do {
9130           if (Idx == NestIdx) {
9131             // Add the chain argument and attributes.
9132             Value *NestVal = Tramp->getOperand(3);
9133             if (NestVal->getType() != NestTy)
9134               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9135             NewArgs.push_back(NestVal);
9136             NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
9137           }
9138
9139           if (I == E)
9140             break;
9141
9142           // Add the original argument and attributes.
9143           NewArgs.push_back(*I);
9144           if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
9145             NewAttrs.push_back
9146               (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
9147
9148           ++Idx, ++I;
9149         } while (1);
9150       }
9151
9152       // The trampoline may have been bitcast to a bogus type (FTy).
9153       // Handle this by synthesizing a new function type, equal to FTy
9154       // with the chain parameter inserted.
9155
9156       std::vector<const Type*> NewTypes;
9157       NewTypes.reserve(FTy->getNumParams()+1);
9158
9159       // Insert the chain's type into the list of parameter types, which may
9160       // mean appending it.
9161       {
9162         unsigned Idx = 1;
9163         FunctionType::param_iterator I = FTy->param_begin(),
9164           E = FTy->param_end();
9165
9166         do {
9167           if (Idx == NestIdx)
9168             // Add the chain's type.
9169             NewTypes.push_back(NestTy);
9170
9171           if (I == E)
9172             break;
9173
9174           // Add the original type.
9175           NewTypes.push_back(*I);
9176
9177           ++Idx, ++I;
9178         } while (1);
9179       }
9180
9181       // Replace the trampoline call with a direct call.  Let the generic
9182       // code sort out any function type mismatches.
9183       FunctionType *NewFTy =
9184         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
9185       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9186         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
9187       const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
9188
9189       Instruction *NewCaller;
9190       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9191         NewCaller = InvokeInst::Create(NewCallee,
9192                                        II->getNormalDest(), II->getUnwindDest(),
9193                                        NewArgs.begin(), NewArgs.end(),
9194                                        Caller->getName(), Caller);
9195         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
9196         cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
9197       } else {
9198         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9199                                      Caller->getName(), Caller);
9200         if (cast<CallInst>(Caller)->isTailCall())
9201           cast<CallInst>(NewCaller)->setTailCall();
9202         cast<CallInst>(NewCaller)->
9203           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
9204         cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
9205       }
9206       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9207         Caller->replaceAllUsesWith(NewCaller);
9208       Caller->eraseFromParent();
9209       RemoveFromWorkList(Caller);
9210       return 0;
9211     }
9212   }
9213
9214   // Replace the trampoline call with a direct call.  Since there is no 'nest'
9215   // parameter, there is no need to adjust the argument list.  Let the generic
9216   // code sort out any function type mismatches.
9217   Constant *NewCallee =
9218     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9219   CS.setCalledFunction(NewCallee);
9220   return CS.getInstruction();
9221 }
9222
9223 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9224 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9225 /// and a single binop.
9226 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9227   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9228   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9229          isa<CmpInst>(FirstInst));
9230   unsigned Opc = FirstInst->getOpcode();
9231   Value *LHSVal = FirstInst->getOperand(0);
9232   Value *RHSVal = FirstInst->getOperand(1);
9233     
9234   const Type *LHSType = LHSVal->getType();
9235   const Type *RHSType = RHSVal->getType();
9236   
9237   // Scan to see if all operands are the same opcode, all have one use, and all
9238   // kill their operands (i.e. the operands have one use).
9239   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9240     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9241     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9242         // Verify type of the LHS matches so we don't fold cmp's of different
9243         // types or GEP's with different index types.
9244         I->getOperand(0)->getType() != LHSType ||
9245         I->getOperand(1)->getType() != RHSType)
9246       return 0;
9247
9248     // If they are CmpInst instructions, check their predicates
9249     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9250       if (cast<CmpInst>(I)->getPredicate() !=
9251           cast<CmpInst>(FirstInst)->getPredicate())
9252         return 0;
9253     
9254     // Keep track of which operand needs a phi node.
9255     if (I->getOperand(0) != LHSVal) LHSVal = 0;
9256     if (I->getOperand(1) != RHSVal) RHSVal = 0;
9257   }
9258   
9259   // Otherwise, this is safe to transform, determine if it is profitable.
9260
9261   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9262   // Indexes are often folded into load/store instructions, so we don't want to
9263   // hide them behind a phi.
9264   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9265     return 0;
9266   
9267   Value *InLHS = FirstInst->getOperand(0);
9268   Value *InRHS = FirstInst->getOperand(1);
9269   PHINode *NewLHS = 0, *NewRHS = 0;
9270   if (LHSVal == 0) {
9271     NewLHS = PHINode::Create(LHSType,
9272                              FirstInst->getOperand(0)->getName() + ".pn");
9273     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9274     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9275     InsertNewInstBefore(NewLHS, PN);
9276     LHSVal = NewLHS;
9277   }
9278   
9279   if (RHSVal == 0) {
9280     NewRHS = PHINode::Create(RHSType,
9281                              FirstInst->getOperand(1)->getName() + ".pn");
9282     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9283     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9284     InsertNewInstBefore(NewRHS, PN);
9285     RHSVal = NewRHS;
9286   }
9287   
9288   // Add all operands to the new PHIs.
9289   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9290     if (NewLHS) {
9291       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9292       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9293     }
9294     if (NewRHS) {
9295       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9296       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9297     }
9298   }
9299     
9300   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9301     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
9302   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9303     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
9304                            RHSVal);
9305   else {
9306     assert(isa<GetElementPtrInst>(FirstInst));
9307     return GetElementPtrInst::Create(LHSVal, RHSVal);
9308   }
9309 }
9310
9311 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9312 /// of the block that defines it.  This means that it must be obvious the value
9313 /// of the load is not changed from the point of the load to the end of the
9314 /// block it is in.
9315 ///
9316 /// Finally, it is safe, but not profitable, to sink a load targetting a
9317 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
9318 /// to a register.
9319 static bool isSafeToSinkLoad(LoadInst *L) {
9320   BasicBlock::iterator BBI = L, E = L->getParent()->end();
9321   
9322   for (++BBI; BBI != E; ++BBI)
9323     if (BBI->mayWriteToMemory())
9324       return false;
9325   
9326   // Check for non-address taken alloca.  If not address-taken already, it isn't
9327   // profitable to do this xform.
9328   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9329     bool isAddressTaken = false;
9330     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9331          UI != E; ++UI) {
9332       if (isa<LoadInst>(UI)) continue;
9333       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9334         // If storing TO the alloca, then the address isn't taken.
9335         if (SI->getOperand(1) == AI) continue;
9336       }
9337       isAddressTaken = true;
9338       break;
9339     }
9340     
9341     if (!isAddressTaken)
9342       return false;
9343   }
9344   
9345   return true;
9346 }
9347
9348
9349 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9350 // operator and they all are only used by the PHI, PHI together their
9351 // inputs, and do the operation once, to the result of the PHI.
9352 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9353   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9354
9355   // Scan the instruction, looking for input operations that can be folded away.
9356   // If all input operands to the phi are the same instruction (e.g. a cast from
9357   // the same type or "+42") we can pull the operation through the PHI, reducing
9358   // code size and simplifying code.
9359   Constant *ConstantOp = 0;
9360   const Type *CastSrcTy = 0;
9361   bool isVolatile = false;
9362   if (isa<CastInst>(FirstInst)) {
9363     CastSrcTy = FirstInst->getOperand(0)->getType();
9364   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9365     // Can fold binop, compare or shift here if the RHS is a constant, 
9366     // otherwise call FoldPHIArgBinOpIntoPHI.
9367     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9368     if (ConstantOp == 0)
9369       return FoldPHIArgBinOpIntoPHI(PN);
9370   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9371     isVolatile = LI->isVolatile();
9372     // We can't sink the load if the loaded value could be modified between the
9373     // load and the PHI.
9374     if (LI->getParent() != PN.getIncomingBlock(0) ||
9375         !isSafeToSinkLoad(LI))
9376       return 0;
9377     
9378     // If the PHI is of volatile loads and the load block has multiple
9379     // successors, sinking it would remove a load of the volatile value from
9380     // the path through the other successor.
9381     if (isVolatile &&
9382         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9383       return 0;
9384     
9385   } else if (isa<GetElementPtrInst>(FirstInst)) {
9386     if (FirstInst->getNumOperands() == 2)
9387       return FoldPHIArgBinOpIntoPHI(PN);
9388     // Can't handle general GEPs yet.
9389     return 0;
9390   } else {
9391     return 0;  // Cannot fold this operation.
9392   }
9393
9394   // Check to see if all arguments are the same operation.
9395   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9396     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9397     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9398     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9399       return 0;
9400     if (CastSrcTy) {
9401       if (I->getOperand(0)->getType() != CastSrcTy)
9402         return 0;  // Cast operation must match.
9403     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9404       // We can't sink the load if the loaded value could be modified between 
9405       // the load and the PHI.
9406       if (LI->isVolatile() != isVolatile ||
9407           LI->getParent() != PN.getIncomingBlock(i) ||
9408           !isSafeToSinkLoad(LI))
9409         return 0;
9410       
9411       // If the PHI is of volatile loads and the load block has multiple
9412       // successors, sinking it would remove a load of the volatile value from
9413       // the path through the other successor.
9414       if (isVolatile &&
9415           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9416         return 0;
9417
9418       
9419     } else if (I->getOperand(1) != ConstantOp) {
9420       return 0;
9421     }
9422   }
9423
9424   // Okay, they are all the same operation.  Create a new PHI node of the
9425   // correct type, and PHI together all of the LHS's of the instructions.
9426   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9427                                    PN.getName()+".in");
9428   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9429
9430   Value *InVal = FirstInst->getOperand(0);
9431   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9432
9433   // Add all operands to the new PHI.
9434   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9435     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9436     if (NewInVal != InVal)
9437       InVal = 0;
9438     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9439   }
9440
9441   Value *PhiVal;
9442   if (InVal) {
9443     // The new PHI unions all of the same values together.  This is really
9444     // common, so we handle it intelligently here for compile-time speed.
9445     PhiVal = InVal;
9446     delete NewPN;
9447   } else {
9448     InsertNewInstBefore(NewPN, PN);
9449     PhiVal = NewPN;
9450   }
9451
9452   // Insert and return the new operation.
9453   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
9454     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
9455   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9456     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
9457   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9458     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
9459                            PhiVal, ConstantOp);
9460   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9461   
9462   // If this was a volatile load that we are merging, make sure to loop through
9463   // and mark all the input loads as non-volatile.  If we don't do this, we will
9464   // insert a new volatile load and the old ones will not be deletable.
9465   if (isVolatile)
9466     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9467       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9468   
9469   return new LoadInst(PhiVal, "", isVolatile);
9470 }
9471
9472 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9473 /// that is dead.
9474 static bool DeadPHICycle(PHINode *PN,
9475                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
9476   if (PN->use_empty()) return true;
9477   if (!PN->hasOneUse()) return false;
9478
9479   // Remember this node, and if we find the cycle, return.
9480   if (!PotentiallyDeadPHIs.insert(PN))
9481     return true;
9482   
9483   // Don't scan crazily complex things.
9484   if (PotentiallyDeadPHIs.size() == 16)
9485     return false;
9486
9487   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9488     return DeadPHICycle(PU, PotentiallyDeadPHIs);
9489
9490   return false;
9491 }
9492
9493 /// PHIsEqualValue - Return true if this phi node is always equal to
9494 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
9495 ///   z = some value; x = phi (y, z); y = phi (x, z)
9496 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
9497                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9498   // See if we already saw this PHI node.
9499   if (!ValueEqualPHIs.insert(PN))
9500     return true;
9501   
9502   // Don't scan crazily complex things.
9503   if (ValueEqualPHIs.size() == 16)
9504     return false;
9505  
9506   // Scan the operands to see if they are either phi nodes or are equal to
9507   // the value.
9508   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9509     Value *Op = PN->getIncomingValue(i);
9510     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9511       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9512         return false;
9513     } else if (Op != NonPhiInVal)
9514       return false;
9515   }
9516   
9517   return true;
9518 }
9519
9520
9521 // PHINode simplification
9522 //
9523 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
9524   // If LCSSA is around, don't mess with Phi nodes
9525   if (MustPreserveLCSSA) return 0;
9526   
9527   if (Value *V = PN.hasConstantValue())
9528     return ReplaceInstUsesWith(PN, V);
9529
9530   // If all PHI operands are the same operation, pull them through the PHI,
9531   // reducing code size.
9532   if (isa<Instruction>(PN.getIncomingValue(0)) &&
9533       PN.getIncomingValue(0)->hasOneUse())
9534     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9535       return Result;
9536
9537   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
9538   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9539   // PHI)... break the cycle.
9540   if (PN.hasOneUse()) {
9541     Instruction *PHIUser = cast<Instruction>(PN.use_back());
9542     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
9543       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
9544       PotentiallyDeadPHIs.insert(&PN);
9545       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9546         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9547     }
9548    
9549     // If this phi has a single use, and if that use just computes a value for
9550     // the next iteration of a loop, delete the phi.  This occurs with unused
9551     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
9552     // common case here is good because the only other things that catch this
9553     // are induction variable analysis (sometimes) and ADCE, which is only run
9554     // late.
9555     if (PHIUser->hasOneUse() &&
9556         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9557         PHIUser->use_back() == &PN) {
9558       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9559     }
9560   }
9561
9562   // We sometimes end up with phi cycles that non-obviously end up being the
9563   // same value, for example:
9564   //   z = some value; x = phi (y, z); y = phi (x, z)
9565   // where the phi nodes don't necessarily need to be in the same block.  Do a
9566   // quick check to see if the PHI node only contains a single non-phi value, if
9567   // so, scan to see if the phi cycle is actually equal to that value.
9568   {
9569     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9570     // Scan for the first non-phi operand.
9571     while (InValNo != NumOperandVals && 
9572            isa<PHINode>(PN.getIncomingValue(InValNo)))
9573       ++InValNo;
9574
9575     if (InValNo != NumOperandVals) {
9576       Value *NonPhiInVal = PN.getOperand(InValNo);
9577       
9578       // Scan the rest of the operands to see if there are any conflicts, if so
9579       // there is no need to recursively scan other phis.
9580       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9581         Value *OpVal = PN.getIncomingValue(InValNo);
9582         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9583           break;
9584       }
9585       
9586       // If we scanned over all operands, then we have one unique value plus
9587       // phi values.  Scan PHI nodes to see if they all merge in each other or
9588       // the value.
9589       if (InValNo == NumOperandVals) {
9590         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9591         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9592           return ReplaceInstUsesWith(PN, NonPhiInVal);
9593       }
9594     }
9595   }
9596   return 0;
9597 }
9598
9599 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9600                                    Instruction *InsertPoint,
9601                                    InstCombiner *IC) {
9602   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9603   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9604   // We must cast correctly to the pointer type. Ensure that we
9605   // sign extend the integer value if it is smaller as this is
9606   // used for address computation.
9607   Instruction::CastOps opcode = 
9608      (VTySize < PtrSize ? Instruction::SExt :
9609       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9610   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9611 }
9612
9613
9614 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9615   Value *PtrOp = GEP.getOperand(0);
9616   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
9617   // If so, eliminate the noop.
9618   if (GEP.getNumOperands() == 1)
9619     return ReplaceInstUsesWith(GEP, PtrOp);
9620
9621   if (isa<UndefValue>(GEP.getOperand(0)))
9622     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9623
9624   bool HasZeroPointerIndex = false;
9625   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9626     HasZeroPointerIndex = C->isNullValue();
9627
9628   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9629     return ReplaceInstUsesWith(GEP, PtrOp);
9630
9631   // Eliminate unneeded casts for indices.
9632   bool MadeChange = false;
9633   
9634   gep_type_iterator GTI = gep_type_begin(GEP);
9635   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
9636        i != e; ++i, ++GTI) {
9637     if (isa<SequentialType>(*GTI)) {
9638       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
9639         if (CI->getOpcode() == Instruction::ZExt ||
9640             CI->getOpcode() == Instruction::SExt) {
9641           const Type *SrcTy = CI->getOperand(0)->getType();
9642           // We can eliminate a cast from i32 to i64 iff the target 
9643           // is a 32-bit pointer target.
9644           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9645             MadeChange = true;
9646             *i = CI->getOperand(0);
9647           }
9648         }
9649       }
9650       // If we are using a wider index than needed for this platform, shrink it
9651       // to what we need.  If the incoming value needs a cast instruction,
9652       // insert it.  This explicit cast can make subsequent optimizations more
9653       // obvious.
9654       Value *Op = *i;
9655       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
9656         if (Constant *C = dyn_cast<Constant>(Op)) {
9657           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
9658           MadeChange = true;
9659         } else {
9660           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9661                                 GEP);
9662           *i = Op;
9663           MadeChange = true;
9664         }
9665       }
9666     }
9667   }
9668   if (MadeChange) return &GEP;
9669
9670   // If this GEP instruction doesn't move the pointer, and if the input operand
9671   // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9672   // real input to the dest type.
9673   if (GEP.hasAllZeroIndices()) {
9674     if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9675       // If the bitcast is of an allocation, and the allocation will be
9676       // converted to match the type of the cast, don't touch this.
9677       if (isa<AllocationInst>(BCI->getOperand(0))) {
9678         // See if the bitcast simplifies, if so, don't nuke this GEP yet.
9679         if (Instruction *I = visitBitCast(*BCI)) {
9680           if (I != BCI) {
9681             I->takeName(BCI);
9682             BCI->getParent()->getInstList().insert(BCI, I);
9683             ReplaceInstUsesWith(*BCI, I);
9684           }
9685           return &GEP;
9686         }
9687       }
9688       return new BitCastInst(BCI->getOperand(0), GEP.getType());
9689     }
9690   }
9691   
9692   // Combine Indices - If the source pointer to this getelementptr instruction
9693   // is a getelementptr instruction, combine the indices of the two
9694   // getelementptr instructions into a single instruction.
9695   //
9696   SmallVector<Value*, 8> SrcGEPOperands;
9697   if (User *Src = dyn_castGetElementPtr(PtrOp))
9698     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9699
9700   if (!SrcGEPOperands.empty()) {
9701     // Note that if our source is a gep chain itself that we wait for that
9702     // chain to be resolved before we perform this transformation.  This
9703     // avoids us creating a TON of code in some cases.
9704     //
9705     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9706         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9707       return 0;   // Wait until our source is folded to completion.
9708
9709     SmallVector<Value*, 8> Indices;
9710
9711     // Find out whether the last index in the source GEP is a sequential idx.
9712     bool EndsWithSequential = false;
9713     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9714            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9715       EndsWithSequential = !isa<StructType>(*I);
9716
9717     // Can we combine the two pointer arithmetics offsets?
9718     if (EndsWithSequential) {
9719       // Replace: gep (gep %P, long B), long A, ...
9720       // With:    T = long A+B; gep %P, T, ...
9721       //
9722       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9723       if (SO1 == Constant::getNullValue(SO1->getType())) {
9724         Sum = GO1;
9725       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9726         Sum = SO1;
9727       } else {
9728         // If they aren't the same type, convert both to an integer of the
9729         // target's pointer size.
9730         if (SO1->getType() != GO1->getType()) {
9731           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9732             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9733           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9734             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9735           } else {
9736             unsigned PS = TD->getPointerSizeInBits();
9737             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
9738               // Convert GO1 to SO1's type.
9739               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9740
9741             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
9742               // Convert SO1 to GO1's type.
9743               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9744             } else {
9745               const Type *PT = TD->getIntPtrType();
9746               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9747               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9748             }
9749           }
9750         }
9751         if (isa<Constant>(SO1) && isa<Constant>(GO1))
9752           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9753         else {
9754           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
9755           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
9756         }
9757       }
9758
9759       // Recycle the GEP we already have if possible.
9760       if (SrcGEPOperands.size() == 2) {
9761         GEP.setOperand(0, SrcGEPOperands[0]);
9762         GEP.setOperand(1, Sum);
9763         return &GEP;
9764       } else {
9765         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9766                        SrcGEPOperands.end()-1);
9767         Indices.push_back(Sum);
9768         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9769       }
9770     } else if (isa<Constant>(*GEP.idx_begin()) &&
9771                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
9772                SrcGEPOperands.size() != 1) {
9773       // Otherwise we can do the fold if the first index of the GEP is a zero
9774       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9775                      SrcGEPOperands.end());
9776       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9777     }
9778
9779     if (!Indices.empty())
9780       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9781                                        Indices.end(), GEP.getName());
9782
9783   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
9784     // GEP of global variable.  If all of the indices for this GEP are
9785     // constants, we can promote this to a constexpr instead of an instruction.
9786
9787     // Scan for nonconstants...
9788     SmallVector<Constant*, 8> Indices;
9789     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9790     for (; I != E && isa<Constant>(*I); ++I)
9791       Indices.push_back(cast<Constant>(*I));
9792
9793     if (I == E) {  // If they are all constants...
9794       Constant *CE = ConstantExpr::getGetElementPtr(GV,
9795                                                     &Indices[0],Indices.size());
9796
9797       // Replace all uses of the GEP with the new constexpr...
9798       return ReplaceInstUsesWith(GEP, CE);
9799     }
9800   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
9801     if (!isa<PointerType>(X->getType())) {
9802       // Not interesting.  Source pointer must be a cast from pointer.
9803     } else if (HasZeroPointerIndex) {
9804       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9805       // into     : GEP [10 x i8]* X, i32 0, ...
9806       //
9807       // This occurs when the program declares an array extern like "int X[];"
9808       //
9809       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9810       const PointerType *XTy = cast<PointerType>(X->getType());
9811       if (const ArrayType *XATy =
9812           dyn_cast<ArrayType>(XTy->getElementType()))
9813         if (const ArrayType *CATy =
9814             dyn_cast<ArrayType>(CPTy->getElementType()))
9815           if (CATy->getElementType() == XATy->getElementType()) {
9816             // At this point, we know that the cast source type is a pointer
9817             // to an array of the same type as the destination pointer
9818             // array.  Because the array type is never stepped over (there
9819             // is a leading zero) we can fold the cast into this GEP.
9820             GEP.setOperand(0, X);
9821             return &GEP;
9822           }
9823     } else if (GEP.getNumOperands() == 2) {
9824       // Transform things like:
9825       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9826       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
9827       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9828       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9829       if (isa<ArrayType>(SrcElTy) &&
9830           TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9831           TD->getABITypeSize(ResElTy)) {
9832         Value *Idx[2];
9833         Idx[0] = Constant::getNullValue(Type::Int32Ty);
9834         Idx[1] = GEP.getOperand(1);
9835         Value *V = InsertNewInstBefore(
9836                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
9837         // V and GEP are both pointer types --> BitCast
9838         return new BitCastInst(V, GEP.getType());
9839       }
9840       
9841       // Transform things like:
9842       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
9843       //   (where tmp = 8*tmp2) into:
9844       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
9845       
9846       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
9847         uint64_t ArrayEltSize =
9848             TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
9849         
9850         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
9851         // allow either a mul, shift, or constant here.
9852         Value *NewIdx = 0;
9853         ConstantInt *Scale = 0;
9854         if (ArrayEltSize == 1) {
9855           NewIdx = GEP.getOperand(1);
9856           Scale = ConstantInt::get(NewIdx->getType(), 1);
9857         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
9858           NewIdx = ConstantInt::get(CI->getType(), 1);
9859           Scale = CI;
9860         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9861           if (Inst->getOpcode() == Instruction::Shl &&
9862               isa<ConstantInt>(Inst->getOperand(1))) {
9863             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9864             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9865             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
9866             NewIdx = Inst->getOperand(0);
9867           } else if (Inst->getOpcode() == Instruction::Mul &&
9868                      isa<ConstantInt>(Inst->getOperand(1))) {
9869             Scale = cast<ConstantInt>(Inst->getOperand(1));
9870             NewIdx = Inst->getOperand(0);
9871           }
9872         }
9873         
9874         // If the index will be to exactly the right offset with the scale taken
9875         // out, perform the transformation. Note, we don't know whether Scale is
9876         // signed or not. We'll use unsigned version of division/modulo
9877         // operation after making sure Scale doesn't have the sign bit set.
9878         if (Scale && Scale->getSExtValue() >= 0LL &&
9879             Scale->getZExtValue() % ArrayEltSize == 0) {
9880           Scale = ConstantInt::get(Scale->getType(),
9881                                    Scale->getZExtValue() / ArrayEltSize);
9882           if (Scale->getZExtValue() != 1) {
9883             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
9884                                                        false /*ZExt*/);
9885             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
9886             NewIdx = InsertNewInstBefore(Sc, GEP);
9887           }
9888
9889           // Insert the new GEP instruction.
9890           Value *Idx[2];
9891           Idx[0] = Constant::getNullValue(Type::Int32Ty);
9892           Idx[1] = NewIdx;
9893           Instruction *NewGEP =
9894             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
9895           NewGEP = InsertNewInstBefore(NewGEP, GEP);
9896           // The NewGEP must be pointer typed, so must the old one -> BitCast
9897           return new BitCastInst(NewGEP, GEP.getType());
9898         }
9899       }
9900     }
9901   }
9902
9903   return 0;
9904 }
9905
9906 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9907   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
9908   if (AI.isArrayAllocation()) {  // Check C != 1
9909     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9910       const Type *NewTy = 
9911         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
9912       AllocationInst *New = 0;
9913
9914       // Create and insert the replacement instruction...
9915       if (isa<MallocInst>(AI))
9916         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
9917       else {
9918         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
9919         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
9920       }
9921
9922       InsertNewInstBefore(New, AI);
9923
9924       // Scan to the end of the allocation instructions, to skip over a block of
9925       // allocas if possible...
9926       //
9927       BasicBlock::iterator It = New;
9928       while (isa<AllocationInst>(*It)) ++It;
9929
9930       // Now that I is pointing to the first non-allocation-inst in the block,
9931       // insert our getelementptr instruction...
9932       //
9933       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
9934       Value *Idx[2];
9935       Idx[0] = NullIdx;
9936       Idx[1] = NullIdx;
9937       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
9938                                            New->getName()+".sub", It);
9939
9940       // Now make everything use the getelementptr instead of the original
9941       // allocation.
9942       return ReplaceInstUsesWith(AI, V);
9943     } else if (isa<UndefValue>(AI.getArraySize())) {
9944       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9945     }
9946   }
9947
9948   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9949   // Note that we only do this for alloca's, because malloc should allocate and
9950   // return a unique pointer, even for a zero byte allocation.
9951   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
9952       TD->getABITypeSize(AI.getAllocatedType()) == 0)
9953     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9954
9955   return 0;
9956 }
9957
9958 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9959   Value *Op = FI.getOperand(0);
9960
9961   // free undef -> unreachable.
9962   if (isa<UndefValue>(Op)) {
9963     // Insert a new store to null because we cannot modify the CFG here.
9964     new StoreInst(ConstantInt::getTrue(),
9965                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
9966     return EraseInstFromFunction(FI);
9967   }
9968   
9969   // If we have 'free null' delete the instruction.  This can happen in stl code
9970   // when lots of inlining happens.
9971   if (isa<ConstantPointerNull>(Op))
9972     return EraseInstFromFunction(FI);
9973   
9974   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9975   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9976     FI.setOperand(0, CI->getOperand(0));
9977     return &FI;
9978   }
9979   
9980   // Change free (gep X, 0,0,0,0) into free(X)
9981   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9982     if (GEPI->hasAllZeroIndices()) {
9983       AddToWorkList(GEPI);
9984       FI.setOperand(0, GEPI->getOperand(0));
9985       return &FI;
9986     }
9987   }
9988   
9989   // Change free(malloc) into nothing, if the malloc has a single use.
9990   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9991     if (MI->hasOneUse()) {
9992       EraseInstFromFunction(FI);
9993       return EraseInstFromFunction(*MI);
9994     }
9995
9996   return 0;
9997 }
9998
9999
10000 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
10001 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
10002                                         const TargetData *TD) {
10003   User *CI = cast<User>(LI.getOperand(0));
10004   Value *CastOp = CI->getOperand(0);
10005
10006   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10007     // Instead of loading constant c string, use corresponding integer value
10008     // directly if string length is small enough.
10009     std::string Str;
10010     if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
10011       unsigned len = Str.length();
10012       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10013       unsigned numBits = Ty->getPrimitiveSizeInBits();
10014       // Replace LI with immediate integer store.
10015       if ((numBits >> 3) == len + 1) {
10016         APInt StrVal(numBits, 0);
10017         APInt SingleChar(numBits, 0);
10018         if (TD->isLittleEndian()) {
10019           for (signed i = len-1; i >= 0; i--) {
10020             SingleChar = (uint64_t) Str[i];
10021             StrVal = (StrVal << 8) | SingleChar;
10022           }
10023         } else {
10024           for (unsigned i = 0; i < len; i++) {
10025             SingleChar = (uint64_t) Str[i];
10026             StrVal = (StrVal << 8) | SingleChar;
10027           }
10028           // Append NULL at the end.
10029           SingleChar = 0;
10030           StrVal = (StrVal << 8) | SingleChar;
10031         }
10032         Value *NL = ConstantInt::get(StrVal);
10033         return IC.ReplaceInstUsesWith(LI, NL);
10034       }
10035     }
10036   }
10037
10038   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10039   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10040     const Type *SrcPTy = SrcTy->getElementType();
10041
10042     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
10043          isa<VectorType>(DestPTy)) {
10044       // If the source is an array, the code below will not succeed.  Check to
10045       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10046       // constants.
10047       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10048         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10049           if (ASrcTy->getNumElements() != 0) {
10050             Value *Idxs[2];
10051             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10052             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10053             SrcTy = cast<PointerType>(CastOp->getType());
10054             SrcPTy = SrcTy->getElementType();
10055           }
10056
10057       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
10058             isa<VectorType>(SrcPTy)) &&
10059           // Do not allow turning this into a load of an integer, which is then
10060           // casted to a pointer, this pessimizes pointer analysis a lot.
10061           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10062           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10063                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10064
10065         // Okay, we are casting from one integer or pointer type to another of
10066         // the same size.  Instead of casting the pointer before the load, cast
10067         // the result of the loaded value.
10068         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10069                                                              CI->getName(),
10070                                                          LI.isVolatile()),LI);
10071         // Now cast the result of the load.
10072         return new BitCastInst(NewLoad, LI.getType());
10073       }
10074     }
10075   }
10076   return 0;
10077 }
10078
10079 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
10080 /// from this value cannot trap.  If it is not obviously safe to load from the
10081 /// specified pointer, we do a quick local scan of the basic block containing
10082 /// ScanFrom, to determine if the address is already accessed.
10083 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
10084   // If it is an alloca it is always safe to load from.
10085   if (isa<AllocaInst>(V)) return true;
10086
10087   // If it is a global variable it is mostly safe to load from.
10088   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
10089     // Don't try to evaluate aliases.  External weak GV can be null.
10090     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
10091
10092   // Otherwise, be a little bit agressive by scanning the local block where we
10093   // want to check to see if the pointer is already being loaded or stored
10094   // from/to.  If so, the previous load or store would have already trapped,
10095   // so there is no harm doing an extra load (also, CSE will later eliminate
10096   // the load entirely).
10097   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10098
10099   while (BBI != E) {
10100     --BBI;
10101
10102     // If we see a free or a call (which might do a free) the pointer could be
10103     // marked invalid.
10104     if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
10105       return false;
10106     
10107     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10108       if (LI->getOperand(0) == V) return true;
10109     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
10110       if (SI->getOperand(1) == V) return true;
10111     }
10112
10113   }
10114   return false;
10115 }
10116
10117 /// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10118 /// until we find the underlying object a pointer is referring to or something
10119 /// we don't understand.  Note that the returned pointer may be offset from the
10120 /// input, because we ignore GEP indices.
10121 static Value *GetUnderlyingObject(Value *Ptr) {
10122   while (1) {
10123     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10124       if (CE->getOpcode() == Instruction::BitCast ||
10125           CE->getOpcode() == Instruction::GetElementPtr)
10126         Ptr = CE->getOperand(0);
10127       else
10128         return Ptr;
10129     } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10130       Ptr = BCI->getOperand(0);
10131     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10132       Ptr = GEP->getOperand(0);
10133     } else {
10134       return Ptr;
10135     }
10136   }
10137 }
10138
10139 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10140   Value *Op = LI.getOperand(0);
10141
10142   // Attempt to improve the alignment.
10143   unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10144   if (KnownAlign >
10145       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10146                                 LI.getAlignment()))
10147     LI.setAlignment(KnownAlign);
10148
10149   // load (cast X) --> cast (load X) iff safe
10150   if (isa<CastInst>(Op))
10151     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10152       return Res;
10153
10154   // None of the following transforms are legal for volatile loads.
10155   if (LI.isVolatile()) return 0;
10156   
10157   if (&LI.getParent()->front() != &LI) {
10158     BasicBlock::iterator BBI = &LI; --BBI;
10159     // If the instruction immediately before this is a store to the same
10160     // address, do a simple form of store->load forwarding.
10161     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10162       if (SI->getOperand(1) == LI.getOperand(0))
10163         return ReplaceInstUsesWith(LI, SI->getOperand(0));
10164     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10165       if (LIB->getOperand(0) == LI.getOperand(0))
10166         return ReplaceInstUsesWith(LI, LIB);
10167   }
10168
10169   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10170     const Value *GEPI0 = GEPI->getOperand(0);
10171     // TODO: Consider a target hook for valid address spaces for this xform.
10172     if (isa<ConstantPointerNull>(GEPI0) &&
10173         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
10174       // Insert a new store to null instruction before the load to indicate
10175       // that this code is not reachable.  We do this instead of inserting
10176       // an unreachable instruction directly because we cannot modify the
10177       // CFG.
10178       new StoreInst(UndefValue::get(LI.getType()),
10179                     Constant::getNullValue(Op->getType()), &LI);
10180       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10181     }
10182   } 
10183
10184   if (Constant *C = dyn_cast<Constant>(Op)) {
10185     // load null/undef -> undef
10186     // TODO: Consider a target hook for valid address spaces for this xform.
10187     if (isa<UndefValue>(C) || (C->isNullValue() && 
10188         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
10189       // Insert a new store to null instruction before the load to indicate that
10190       // this code is not reachable.  We do this instead of inserting an
10191       // unreachable instruction directly because we cannot modify the CFG.
10192       new StoreInst(UndefValue::get(LI.getType()),
10193                     Constant::getNullValue(Op->getType()), &LI);
10194       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10195     }
10196
10197     // Instcombine load (constant global) into the value loaded.
10198     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10199       if (GV->isConstant() && !GV->isDeclaration())
10200         return ReplaceInstUsesWith(LI, GV->getInitializer());
10201
10202     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
10203     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
10204       if (CE->getOpcode() == Instruction::GetElementPtr) {
10205         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10206           if (GV->isConstant() && !GV->isDeclaration())
10207             if (Constant *V = 
10208                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10209               return ReplaceInstUsesWith(LI, V);
10210         if (CE->getOperand(0)->isNullValue()) {
10211           // Insert a new store to null instruction before the load to indicate
10212           // that this code is not reachable.  We do this instead of inserting
10213           // an unreachable instruction directly because we cannot modify the
10214           // CFG.
10215           new StoreInst(UndefValue::get(LI.getType()),
10216                         Constant::getNullValue(Op->getType()), &LI);
10217           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10218         }
10219
10220       } else if (CE->isCast()) {
10221         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10222           return Res;
10223       }
10224     }
10225   }
10226     
10227   // If this load comes from anywhere in a constant global, and if the global
10228   // is all undef or zero, we know what it loads.
10229   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10230     if (GV->isConstant() && GV->hasInitializer()) {
10231       if (GV->getInitializer()->isNullValue())
10232         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10233       else if (isa<UndefValue>(GV->getInitializer()))
10234         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10235     }
10236   }
10237
10238   if (Op->hasOneUse()) {
10239     // Change select and PHI nodes to select values instead of addresses: this
10240     // helps alias analysis out a lot, allows many others simplifications, and
10241     // exposes redundancy in the code.
10242     //
10243     // Note that we cannot do the transformation unless we know that the
10244     // introduced loads cannot trap!  Something like this is valid as long as
10245     // the condition is always false: load (select bool %C, int* null, int* %G),
10246     // but it would not be valid if we transformed it to load from null
10247     // unconditionally.
10248     //
10249     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10250       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
10251       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10252           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10253         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10254                                      SI->getOperand(1)->getName()+".val"), LI);
10255         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10256                                      SI->getOperand(2)->getName()+".val"), LI);
10257         return SelectInst::Create(SI->getCondition(), V1, V2);
10258       }
10259
10260       // load (select (cond, null, P)) -> load P
10261       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10262         if (C->isNullValue()) {
10263           LI.setOperand(0, SI->getOperand(2));
10264           return &LI;
10265         }
10266
10267       // load (select (cond, P, null)) -> load P
10268       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10269         if (C->isNullValue()) {
10270           LI.setOperand(0, SI->getOperand(1));
10271           return &LI;
10272         }
10273     }
10274   }
10275   return 0;
10276 }
10277
10278 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10279 /// when possible.
10280 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10281   User *CI = cast<User>(SI.getOperand(1));
10282   Value *CastOp = CI->getOperand(0);
10283
10284   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10285   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10286     const Type *SrcPTy = SrcTy->getElementType();
10287
10288     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10289       // If the source is an array, the code below will not succeed.  Check to
10290       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10291       // constants.
10292       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10293         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10294           if (ASrcTy->getNumElements() != 0) {
10295             Value* Idxs[2];
10296             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10297             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10298             SrcTy = cast<PointerType>(CastOp->getType());
10299             SrcPTy = SrcTy->getElementType();
10300           }
10301
10302       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10303           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10304                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10305
10306         // Okay, we are casting from one integer or pointer type to another of
10307         // the same size.  Instead of casting the pointer before 
10308         // the store, cast the value to be stored.
10309         Value *NewCast;
10310         Value *SIOp0 = SI.getOperand(0);
10311         Instruction::CastOps opcode = Instruction::BitCast;
10312         const Type* CastSrcTy = SIOp0->getType();
10313         const Type* CastDstTy = SrcPTy;
10314         if (isa<PointerType>(CastDstTy)) {
10315           if (CastSrcTy->isInteger())
10316             opcode = Instruction::IntToPtr;
10317         } else if (isa<IntegerType>(CastDstTy)) {
10318           if (isa<PointerType>(SIOp0->getType()))
10319             opcode = Instruction::PtrToInt;
10320         }
10321         if (Constant *C = dyn_cast<Constant>(SIOp0))
10322           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10323         else
10324           NewCast = IC.InsertNewInstBefore(
10325             CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
10326             SI);
10327         return new StoreInst(NewCast, CastOp);
10328       }
10329     }
10330   }
10331   return 0;
10332 }
10333
10334 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10335   Value *Val = SI.getOperand(0);
10336   Value *Ptr = SI.getOperand(1);
10337
10338   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
10339     EraseInstFromFunction(SI);
10340     ++NumCombined;
10341     return 0;
10342   }
10343   
10344   // If the RHS is an alloca with a single use, zapify the store, making the
10345   // alloca dead.
10346   if (Ptr->hasOneUse() && !SI.isVolatile()) {
10347     if (isa<AllocaInst>(Ptr)) {
10348       EraseInstFromFunction(SI);
10349       ++NumCombined;
10350       return 0;
10351     }
10352     
10353     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10354       if (isa<AllocaInst>(GEP->getOperand(0)) &&
10355           GEP->getOperand(0)->hasOneUse()) {
10356         EraseInstFromFunction(SI);
10357         ++NumCombined;
10358         return 0;
10359       }
10360   }
10361
10362   // Attempt to improve the alignment.
10363   unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10364   if (KnownAlign >
10365       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10366                                 SI.getAlignment()))
10367     SI.setAlignment(KnownAlign);
10368
10369   // Do really simple DSE, to catch cases where there are several consequtive
10370   // stores to the same location, separated by a few arithmetic operations. This
10371   // situation often occurs with bitfield accesses.
10372   BasicBlock::iterator BBI = &SI;
10373   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10374        --ScanInsts) {
10375     --BBI;
10376     
10377     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10378       // Prev store isn't volatile, and stores to the same location?
10379       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10380         ++NumDeadStore;
10381         ++BBI;
10382         EraseInstFromFunction(*PrevSI);
10383         continue;
10384       }
10385       break;
10386     }
10387     
10388     // If this is a load, we have to stop.  However, if the loaded value is from
10389     // the pointer we're loading and is producing the pointer we're storing,
10390     // then *this* store is dead (X = load P; store X -> P).
10391     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10392       if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
10393         EraseInstFromFunction(SI);
10394         ++NumCombined;
10395         return 0;
10396       }
10397       // Otherwise, this is a load from some other location.  Stores before it
10398       // may not be dead.
10399       break;
10400     }
10401     
10402     // Don't skip over loads or things that can modify memory.
10403     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
10404       break;
10405   }
10406   
10407   
10408   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
10409
10410   // store X, null    -> turns into 'unreachable' in SimplifyCFG
10411   if (isa<ConstantPointerNull>(Ptr)) {
10412     if (!isa<UndefValue>(Val)) {
10413       SI.setOperand(0, UndefValue::get(Val->getType()));
10414       if (Instruction *U = dyn_cast<Instruction>(Val))
10415         AddToWorkList(U);  // Dropped a use.
10416       ++NumCombined;
10417     }
10418     return 0;  // Do not modify these!
10419   }
10420
10421   // store undef, Ptr -> noop
10422   if (isa<UndefValue>(Val)) {
10423     EraseInstFromFunction(SI);
10424     ++NumCombined;
10425     return 0;
10426   }
10427
10428   // If the pointer destination is a cast, see if we can fold the cast into the
10429   // source instead.
10430   if (isa<CastInst>(Ptr))
10431     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10432       return Res;
10433   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10434     if (CE->isCast())
10435       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10436         return Res;
10437
10438   
10439   // If this store is the last instruction in the basic block, and if the block
10440   // ends with an unconditional branch, try to move it to the successor block.
10441   BBI = &SI; ++BBI;
10442   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10443     if (BI->isUnconditional())
10444       if (SimplifyStoreAtEndOfBlock(SI))
10445         return 0;  // xform done!
10446   
10447   return 0;
10448 }
10449
10450 /// SimplifyStoreAtEndOfBlock - Turn things like:
10451 ///   if () { *P = v1; } else { *P = v2 }
10452 /// into a phi node with a store in the successor.
10453 ///
10454 /// Simplify things like:
10455 ///   *P = v1; if () { *P = v2; }
10456 /// into a phi node with a store in the successor.
10457 ///
10458 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10459   BasicBlock *StoreBB = SI.getParent();
10460   
10461   // Check to see if the successor block has exactly two incoming edges.  If
10462   // so, see if the other predecessor contains a store to the same location.
10463   // if so, insert a PHI node (if needed) and move the stores down.
10464   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
10465   
10466   // Determine whether Dest has exactly two predecessors and, if so, compute
10467   // the other predecessor.
10468   pred_iterator PI = pred_begin(DestBB);
10469   BasicBlock *OtherBB = 0;
10470   if (*PI != StoreBB)
10471     OtherBB = *PI;
10472   ++PI;
10473   if (PI == pred_end(DestBB))
10474     return false;
10475   
10476   if (*PI != StoreBB) {
10477     if (OtherBB)
10478       return false;
10479     OtherBB = *PI;
10480   }
10481   if (++PI != pred_end(DestBB))
10482     return false;
10483
10484   // Bail out if all the relevant blocks aren't distinct (this can happen,
10485   // for example, if SI is in an infinite loop)
10486   if (StoreBB == DestBB || OtherBB == DestBB)
10487     return false;
10488
10489   // Verify that the other block ends in a branch and is not otherwise empty.
10490   BasicBlock::iterator BBI = OtherBB->getTerminator();
10491   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
10492   if (!OtherBr || BBI == OtherBB->begin())
10493     return false;
10494   
10495   // If the other block ends in an unconditional branch, check for the 'if then
10496   // else' case.  there is an instruction before the branch.
10497   StoreInst *OtherStore = 0;
10498   if (OtherBr->isUnconditional()) {
10499     // If this isn't a store, or isn't a store to the same location, bail out.
10500     --BBI;
10501     OtherStore = dyn_cast<StoreInst>(BBI);
10502     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10503       return false;
10504   } else {
10505     // Otherwise, the other block ended with a conditional branch. If one of the
10506     // destinations is StoreBB, then we have the if/then case.
10507     if (OtherBr->getSuccessor(0) != StoreBB && 
10508         OtherBr->getSuccessor(1) != StoreBB)
10509       return false;
10510     
10511     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
10512     // if/then triangle.  See if there is a store to the same ptr as SI that
10513     // lives in OtherBB.
10514     for (;; --BBI) {
10515       // Check to see if we find the matching store.
10516       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10517         if (OtherStore->getOperand(1) != SI.getOperand(1))
10518           return false;
10519         break;
10520       }
10521       // If we find something that may be using or overwriting the stored
10522       // value, or if we run out of instructions, we can't do the xform.
10523       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
10524           BBI == OtherBB->begin())
10525         return false;
10526     }
10527     
10528     // In order to eliminate the store in OtherBr, we have to
10529     // make sure nothing reads or overwrites the stored value in
10530     // StoreBB.
10531     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10532       // FIXME: This should really be AA driven.
10533       if (I->mayReadFromMemory() || I->mayWriteToMemory())
10534         return false;
10535     }
10536   }
10537   
10538   // Insert a PHI node now if we need it.
10539   Value *MergedVal = OtherStore->getOperand(0);
10540   if (MergedVal != SI.getOperand(0)) {
10541     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
10542     PN->reserveOperandSpace(2);
10543     PN->addIncoming(SI.getOperand(0), SI.getParent());
10544     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10545     MergedVal = InsertNewInstBefore(PN, DestBB->front());
10546   }
10547   
10548   // Advance to a place where it is safe to insert the new store and
10549   // insert it.
10550   BBI = DestBB->getFirstNonPHI();
10551   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10552                                     OtherStore->isVolatile()), *BBI);
10553   
10554   // Nuke the old stores.
10555   EraseInstFromFunction(SI);
10556   EraseInstFromFunction(*OtherStore);
10557   ++NumCombined;
10558   return true;
10559 }
10560
10561
10562 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10563   // Change br (not X), label True, label False to: br X, label False, True
10564   Value *X = 0;
10565   BasicBlock *TrueDest;
10566   BasicBlock *FalseDest;
10567   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10568       !isa<Constant>(X)) {
10569     // Swap Destinations and condition...
10570     BI.setCondition(X);
10571     BI.setSuccessor(0, FalseDest);
10572     BI.setSuccessor(1, TrueDest);
10573     return &BI;
10574   }
10575
10576   // Cannonicalize fcmp_one -> fcmp_oeq
10577   FCmpInst::Predicate FPred; Value *Y;
10578   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
10579                              TrueDest, FalseDest)))
10580     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10581          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10582       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
10583       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
10584       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10585       NewSCC->takeName(I);
10586       // Swap Destinations and condition...
10587       BI.setCondition(NewSCC);
10588       BI.setSuccessor(0, FalseDest);
10589       BI.setSuccessor(1, TrueDest);
10590       RemoveFromWorkList(I);
10591       I->eraseFromParent();
10592       AddToWorkList(NewSCC);
10593       return &BI;
10594     }
10595
10596   // Cannonicalize icmp_ne -> icmp_eq
10597   ICmpInst::Predicate IPred;
10598   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10599                       TrueDest, FalseDest)))
10600     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
10601          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10602          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10603       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10604       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10605       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10606       NewSCC->takeName(I);
10607       // Swap Destinations and condition...
10608       BI.setCondition(NewSCC);
10609       BI.setSuccessor(0, FalseDest);
10610       BI.setSuccessor(1, TrueDest);
10611       RemoveFromWorkList(I);
10612       I->eraseFromParent();;
10613       AddToWorkList(NewSCC);
10614       return &BI;
10615     }
10616
10617   return 0;
10618 }
10619
10620 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10621   Value *Cond = SI.getCondition();
10622   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10623     if (I->getOpcode() == Instruction::Add)
10624       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10625         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10626         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10627           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10628                                                 AddRHS));
10629         SI.setOperand(0, I->getOperand(0));
10630         AddToWorkList(I);
10631         return &SI;
10632       }
10633   }
10634   return 0;
10635 }
10636
10637 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
10638   Value *Agg = EV.getAggregateOperand();
10639
10640   if (!EV.hasIndices())
10641     return ReplaceInstUsesWith(EV, Agg);
10642
10643   if (Constant *C = dyn_cast<Constant>(Agg)) {
10644     if (isa<UndefValue>(C))
10645       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
10646       
10647     if (isa<ConstantAggregateZero>(C))
10648       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
10649
10650     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
10651       // Extract the element indexed by the first index out of the constant
10652       Value *V = C->getOperand(*EV.idx_begin());
10653       if (EV.getNumIndices() > 1)
10654         // Extract the remaining indices out of the constant indexed by the
10655         // first index
10656         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
10657       else
10658         return ReplaceInstUsesWith(EV, V);
10659     }
10660     return 0; // Can't handle other constants
10661   } 
10662   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
10663     // We're extracting from an insertvalue instruction, compare the indices
10664     const unsigned *exti, *exte, *insi, *inse;
10665     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
10666          exte = EV.idx_end(), inse = IV->idx_end();
10667          exti != exte && insi != inse;
10668          ++exti, ++insi) {
10669       if (*insi != *exti)
10670         // The insert and extract both reference distinctly different elements.
10671         // This means the extract is not influenced by the insert, and we can
10672         // replace the aggregate operand of the extract with the aggregate
10673         // operand of the insert. i.e., replace
10674         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
10675         // %E = extractvalue { i32, { i32 } } %I, 0
10676         // with
10677         // %E = extractvalue { i32, { i32 } } %A, 0
10678         return ExtractValueInst::Create(IV->getAggregateOperand(),
10679                                         EV.idx_begin(), EV.idx_end());
10680     }
10681     if (exti == exte && insi == inse)
10682       // Both iterators are at the end: Index lists are identical. Replace
10683       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
10684       // %C = extractvalue { i32, { i32 } } %B, 1, 0
10685       // with "i32 42"
10686       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
10687     if (exti == exte) {
10688       // The extract list is a prefix of the insert list. i.e. replace
10689       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
10690       // %E = extractvalue { i32, { i32 } } %I, 1
10691       // with
10692       // %X = extractvalue { i32, { i32 } } %A, 1
10693       // %E = insertvalue { i32 } %X, i32 42, 0
10694       // by switching the order of the insert and extract (though the
10695       // insertvalue should be left in, since it may have other uses).
10696       Value *NewEV = InsertNewInstBefore(
10697         ExtractValueInst::Create(IV->getAggregateOperand(),
10698                                  EV.idx_begin(), EV.idx_end()),
10699         EV);
10700       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
10701                                      insi, inse);
10702     }
10703     if (insi == inse)
10704       // The insert list is a prefix of the extract list
10705       // We can simply remove the common indices from the extract and make it
10706       // operate on the inserted value instead of the insertvalue result.
10707       // i.e., replace
10708       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
10709       // %E = extractvalue { i32, { i32 } } %I, 1, 0
10710       // with
10711       // %E extractvalue { i32 } { i32 42 }, 0
10712       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
10713                                       exti, exte);
10714   }
10715   // Can't simplify extracts from other values. Note that nested extracts are
10716   // already simplified implicitely by the above (extract ( extract (insert) )
10717   // will be translated into extract ( insert ( extract ) ) first and then just
10718   // the value inserted, if appropriate).
10719   return 0;
10720 }
10721
10722 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10723 /// is to leave as a vector operation.
10724 static bool CheapToScalarize(Value *V, bool isConstant) {
10725   if (isa<ConstantAggregateZero>(V)) 
10726     return true;
10727   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10728     if (isConstant) return true;
10729     // If all elts are the same, we can extract.
10730     Constant *Op0 = C->getOperand(0);
10731     for (unsigned i = 1; i < C->getNumOperands(); ++i)
10732       if (C->getOperand(i) != Op0)
10733         return false;
10734     return true;
10735   }
10736   Instruction *I = dyn_cast<Instruction>(V);
10737   if (!I) return false;
10738   
10739   // Insert element gets simplified to the inserted element or is deleted if
10740   // this is constant idx extract element and its a constant idx insertelt.
10741   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10742       isa<ConstantInt>(I->getOperand(2)))
10743     return true;
10744   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10745     return true;
10746   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10747     if (BO->hasOneUse() &&
10748         (CheapToScalarize(BO->getOperand(0), isConstant) ||
10749          CheapToScalarize(BO->getOperand(1), isConstant)))
10750       return true;
10751   if (CmpInst *CI = dyn_cast<CmpInst>(I))
10752     if (CI->hasOneUse() &&
10753         (CheapToScalarize(CI->getOperand(0), isConstant) ||
10754          CheapToScalarize(CI->getOperand(1), isConstant)))
10755       return true;
10756   
10757   return false;
10758 }
10759
10760 /// Read and decode a shufflevector mask.
10761 ///
10762 /// It turns undef elements into values that are larger than the number of
10763 /// elements in the input.
10764 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10765   unsigned NElts = SVI->getType()->getNumElements();
10766   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10767     return std::vector<unsigned>(NElts, 0);
10768   if (isa<UndefValue>(SVI->getOperand(2)))
10769     return std::vector<unsigned>(NElts, 2*NElts);
10770
10771   std::vector<unsigned> Result;
10772   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
10773   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
10774     if (isa<UndefValue>(*i))
10775       Result.push_back(NElts*2);  // undef -> 8
10776     else
10777       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
10778   return Result;
10779 }
10780
10781 /// FindScalarElement - Given a vector and an element number, see if the scalar
10782 /// value is already around as a register, for example if it were inserted then
10783 /// extracted from the vector.
10784 static Value *FindScalarElement(Value *V, unsigned EltNo) {
10785   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10786   const VectorType *PTy = cast<VectorType>(V->getType());
10787   unsigned Width = PTy->getNumElements();
10788   if (EltNo >= Width)  // Out of range access.
10789     return UndefValue::get(PTy->getElementType());
10790   
10791   if (isa<UndefValue>(V))
10792     return UndefValue::get(PTy->getElementType());
10793   else if (isa<ConstantAggregateZero>(V))
10794     return Constant::getNullValue(PTy->getElementType());
10795   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
10796     return CP->getOperand(EltNo);
10797   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10798     // If this is an insert to a variable element, we don't know what it is.
10799     if (!isa<ConstantInt>(III->getOperand(2))) 
10800       return 0;
10801     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
10802     
10803     // If this is an insert to the element we are looking for, return the
10804     // inserted value.
10805     if (EltNo == IIElt) 
10806       return III->getOperand(1);
10807     
10808     // Otherwise, the insertelement doesn't modify the value, recurse on its
10809     // vector input.
10810     return FindScalarElement(III->getOperand(0), EltNo);
10811   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10812     unsigned InEl = getShuffleMask(SVI)[EltNo];
10813     if (InEl < Width)
10814       return FindScalarElement(SVI->getOperand(0), InEl);
10815     else if (InEl < Width*2)
10816       return FindScalarElement(SVI->getOperand(1), InEl - Width);
10817     else
10818       return UndefValue::get(PTy->getElementType());
10819   }
10820   
10821   // Otherwise, we don't know.
10822   return 0;
10823 }
10824
10825 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
10826   // If vector val is undef, replace extract with scalar undef.
10827   if (isa<UndefValue>(EI.getOperand(0)))
10828     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10829
10830   // If vector val is constant 0, replace extract with scalar 0.
10831   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10832     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10833   
10834   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
10835     // If vector val is constant with all elements the same, replace EI with
10836     // that element. When the elements are not identical, we cannot replace yet
10837     // (we do that below, but only when the index is constant).
10838     Constant *op0 = C->getOperand(0);
10839     for (unsigned i = 1; i < C->getNumOperands(); ++i)
10840       if (C->getOperand(i) != op0) {
10841         op0 = 0; 
10842         break;
10843       }
10844     if (op0)
10845       return ReplaceInstUsesWith(EI, op0);
10846   }
10847   
10848   // If extracting a specified index from the vector, see if we can recursively
10849   // find a previously computed scalar that was inserted into the vector.
10850   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10851     unsigned IndexVal = IdxC->getZExtValue();
10852     unsigned VectorWidth = 
10853       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10854       
10855     // If this is extracting an invalid index, turn this into undef, to avoid
10856     // crashing the code below.
10857     if (IndexVal >= VectorWidth)
10858       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10859     
10860     // This instruction only demands the single element from the input vector.
10861     // If the input vector has a single use, simplify it based on this use
10862     // property.
10863     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
10864       uint64_t UndefElts;
10865       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
10866                                                 1 << IndexVal,
10867                                                 UndefElts)) {
10868         EI.setOperand(0, V);
10869         return &EI;
10870       }
10871     }
10872     
10873     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
10874       return ReplaceInstUsesWith(EI, Elt);
10875     
10876     // If the this extractelement is directly using a bitcast from a vector of
10877     // the same number of elements, see if we can find the source element from
10878     // it.  In this case, we will end up needing to bitcast the scalars.
10879     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10880       if (const VectorType *VT = 
10881               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10882         if (VT->getNumElements() == VectorWidth)
10883           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10884             return new BitCastInst(Elt, EI.getType());
10885     }
10886   }
10887   
10888   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
10889     if (I->hasOneUse()) {
10890       // Push extractelement into predecessor operation if legal and
10891       // profitable to do so
10892       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
10893         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10894         if (CheapToScalarize(BO, isConstantElt)) {
10895           ExtractElementInst *newEI0 = 
10896             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10897                                    EI.getName()+".lhs");
10898           ExtractElementInst *newEI1 =
10899             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10900                                    EI.getName()+".rhs");
10901           InsertNewInstBefore(newEI0, EI);
10902           InsertNewInstBefore(newEI1, EI);
10903           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
10904         }
10905       } else if (isa<LoadInst>(I)) {
10906         unsigned AS = 
10907           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
10908         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10909                                          PointerType::get(EI.getType(), AS),EI);
10910         GetElementPtrInst *GEP =
10911           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
10912         InsertNewInstBefore(GEP, EI);
10913         return new LoadInst(GEP);
10914       }
10915     }
10916     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10917       // Extracting the inserted element?
10918       if (IE->getOperand(2) == EI.getOperand(1))
10919         return ReplaceInstUsesWith(EI, IE->getOperand(1));
10920       // If the inserted and extracted elements are constants, they must not
10921       // be the same value, extract from the pre-inserted value instead.
10922       if (isa<Constant>(IE->getOperand(2)) &&
10923           isa<Constant>(EI.getOperand(1))) {
10924         AddUsesToWorkList(EI);
10925         EI.setOperand(0, IE->getOperand(0));
10926         return &EI;
10927       }
10928     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10929       // If this is extracting an element from a shufflevector, figure out where
10930       // it came from and extract from the appropriate input element instead.
10931       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10932         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
10933         Value *Src;
10934         if (SrcIdx < SVI->getType()->getNumElements())
10935           Src = SVI->getOperand(0);
10936         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10937           SrcIdx -= SVI->getType()->getNumElements();
10938           Src = SVI->getOperand(1);
10939         } else {
10940           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10941         }
10942         return new ExtractElementInst(Src, SrcIdx);
10943       }
10944     }
10945   }
10946   return 0;
10947 }
10948
10949 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10950 /// elements from either LHS or RHS, return the shuffle mask and true. 
10951 /// Otherwise, return false.
10952 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10953                                          std::vector<Constant*> &Mask) {
10954   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10955          "Invalid CollectSingleShuffleElements");
10956   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10957
10958   if (isa<UndefValue>(V)) {
10959     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10960     return true;
10961   } else if (V == LHS) {
10962     for (unsigned i = 0; i != NumElts; ++i)
10963       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10964     return true;
10965   } else if (V == RHS) {
10966     for (unsigned i = 0; i != NumElts; ++i)
10967       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
10968     return true;
10969   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10970     // If this is an insert of an extract from some other vector, include it.
10971     Value *VecOp    = IEI->getOperand(0);
10972     Value *ScalarOp = IEI->getOperand(1);
10973     Value *IdxOp    = IEI->getOperand(2);
10974     
10975     if (!isa<ConstantInt>(IdxOp))
10976       return false;
10977     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10978     
10979     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
10980       // Okay, we can handle this if the vector we are insertinting into is
10981       // transitively ok.
10982       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10983         // If so, update the mask to reflect the inserted undef.
10984         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
10985         return true;
10986       }      
10987     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10988       if (isa<ConstantInt>(EI->getOperand(1)) &&
10989           EI->getOperand(0)->getType() == V->getType()) {
10990         unsigned ExtractedIdx =
10991           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10992         
10993         // This must be extracting from either LHS or RHS.
10994         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10995           // Okay, we can handle this if the vector we are insertinting into is
10996           // transitively ok.
10997           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10998             // If so, update the mask to reflect the inserted value.
10999             if (EI->getOperand(0) == LHS) {
11000               Mask[InsertedIdx & (NumElts-1)] = 
11001                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11002             } else {
11003               assert(EI->getOperand(0) == RHS);
11004               Mask[InsertedIdx & (NumElts-1)] = 
11005                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
11006               
11007             }
11008             return true;
11009           }
11010         }
11011       }
11012     }
11013   }
11014   // TODO: Handle shufflevector here!
11015   
11016   return false;
11017 }
11018
11019 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11020 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
11021 /// that computes V and the LHS value of the shuffle.
11022 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
11023                                      Value *&RHS) {
11024   assert(isa<VectorType>(V->getType()) && 
11025          (RHS == 0 || V->getType() == RHS->getType()) &&
11026          "Invalid shuffle!");
11027   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11028
11029   if (isa<UndefValue>(V)) {
11030     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11031     return V;
11032   } else if (isa<ConstantAggregateZero>(V)) {
11033     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
11034     return V;
11035   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11036     // If this is an insert of an extract from some other vector, include it.
11037     Value *VecOp    = IEI->getOperand(0);
11038     Value *ScalarOp = IEI->getOperand(1);
11039     Value *IdxOp    = IEI->getOperand(2);
11040     
11041     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11042       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11043           EI->getOperand(0)->getType() == V->getType()) {
11044         unsigned ExtractedIdx =
11045           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11046         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11047         
11048         // Either the extracted from or inserted into vector must be RHSVec,
11049         // otherwise we'd end up with a shuffle of three inputs.
11050         if (EI->getOperand(0) == RHS || RHS == 0) {
11051           RHS = EI->getOperand(0);
11052           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
11053           Mask[InsertedIdx & (NumElts-1)] = 
11054             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
11055           return V;
11056         }
11057         
11058         if (VecOp == RHS) {
11059           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
11060           // Everything but the extracted element is replaced with the RHS.
11061           for (unsigned i = 0; i != NumElts; ++i) {
11062             if (i != InsertedIdx)
11063               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
11064           }
11065           return V;
11066         }
11067         
11068         // If this insertelement is a chain that comes from exactly these two
11069         // vectors, return the vector and the effective shuffle.
11070         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11071           return EI->getOperand(0);
11072         
11073       }
11074     }
11075   }
11076   // TODO: Handle shufflevector here!
11077   
11078   // Otherwise, can't do anything fancy.  Return an identity vector.
11079   for (unsigned i = 0; i != NumElts; ++i)
11080     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11081   return V;
11082 }
11083
11084 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11085   Value *VecOp    = IE.getOperand(0);
11086   Value *ScalarOp = IE.getOperand(1);
11087   Value *IdxOp    = IE.getOperand(2);
11088   
11089   // Inserting an undef or into an undefined place, remove this.
11090   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11091     ReplaceInstUsesWith(IE, VecOp);
11092   
11093   // If the inserted element was extracted from some other vector, and if the 
11094   // indexes are constant, try to turn this into a shufflevector operation.
11095   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11096     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11097         EI->getOperand(0)->getType() == IE.getType()) {
11098       unsigned NumVectorElts = IE.getType()->getNumElements();
11099       unsigned ExtractedIdx =
11100         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11101       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11102       
11103       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11104         return ReplaceInstUsesWith(IE, VecOp);
11105       
11106       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
11107         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11108       
11109       // If we are extracting a value from a vector, then inserting it right
11110       // back into the same place, just use the input vector.
11111       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11112         return ReplaceInstUsesWith(IE, VecOp);      
11113       
11114       // We could theoretically do this for ANY input.  However, doing so could
11115       // turn chains of insertelement instructions into a chain of shufflevector
11116       // instructions, and right now we do not merge shufflevectors.  As such,
11117       // only do this in a situation where it is clear that there is benefit.
11118       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11119         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
11120         // the values of VecOp, except then one read from EIOp0.
11121         // Build a new shuffle mask.
11122         std::vector<Constant*> Mask;
11123         if (isa<UndefValue>(VecOp))
11124           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11125         else {
11126           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11127           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11128                                                        NumVectorElts));
11129         } 
11130         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11131         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11132                                      ConstantVector::get(Mask));
11133       }
11134       
11135       // If this insertelement isn't used by some other insertelement, turn it
11136       // (and any insertelements it points to), into one big shuffle.
11137       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11138         std::vector<Constant*> Mask;
11139         Value *RHS = 0;
11140         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11141         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11142         // We now have a shuffle of LHS, RHS, Mask.
11143         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11144       }
11145     }
11146   }
11147
11148   return 0;
11149 }
11150
11151
11152 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11153   Value *LHS = SVI.getOperand(0);
11154   Value *RHS = SVI.getOperand(1);
11155   std::vector<unsigned> Mask = getShuffleMask(&SVI);
11156
11157   bool MadeChange = false;
11158   
11159   // Undefined shuffle mask -> undefined value.
11160   if (isa<UndefValue>(SVI.getOperand(2)))
11161     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11162   
11163   // If we have shuffle(x, undef, mask) and any elements of mask refer to
11164   // the undef, change them to undefs.
11165   if (isa<UndefValue>(SVI.getOperand(1))) {
11166     // Scan to see if there are any references to the RHS.  If so, replace them
11167     // with undef element refs and set MadeChange to true.
11168     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11169       if (Mask[i] >= e && Mask[i] != 2*e) {
11170         Mask[i] = 2*e;
11171         MadeChange = true;
11172       }
11173     }
11174     
11175     if (MadeChange) {
11176       // Remap any references to RHS to use LHS.
11177       std::vector<Constant*> Elts;
11178       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11179         if (Mask[i] == 2*e)
11180           Elts.push_back(UndefValue::get(Type::Int32Ty));
11181         else
11182           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11183       }
11184       SVI.setOperand(2, ConstantVector::get(Elts));
11185     }
11186   }
11187   
11188   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
11189   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11190   if (LHS == RHS || isa<UndefValue>(LHS)) {
11191     if (isa<UndefValue>(LHS) && LHS == RHS) {
11192       // shuffle(undef,undef,mask) -> undef.
11193       return ReplaceInstUsesWith(SVI, LHS);
11194     }
11195     
11196     // Remap any references to RHS to use LHS.
11197     std::vector<Constant*> Elts;
11198     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11199       if (Mask[i] >= 2*e)
11200         Elts.push_back(UndefValue::get(Type::Int32Ty));
11201       else {
11202         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11203             (Mask[i] <  e && isa<UndefValue>(LHS)))
11204           Mask[i] = 2*e;     // Turn into undef.
11205         else
11206           Mask[i] &= (e-1);  // Force to LHS.
11207         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11208       }
11209     }
11210     SVI.setOperand(0, SVI.getOperand(1));
11211     SVI.setOperand(1, UndefValue::get(RHS->getType()));
11212     SVI.setOperand(2, ConstantVector::get(Elts));
11213     LHS = SVI.getOperand(0);
11214     RHS = SVI.getOperand(1);
11215     MadeChange = true;
11216   }
11217   
11218   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11219   bool isLHSID = true, isRHSID = true;
11220     
11221   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11222     if (Mask[i] >= e*2) continue;  // Ignore undef values.
11223     // Is this an identity shuffle of the LHS value?
11224     isLHSID &= (Mask[i] == i);
11225       
11226     // Is this an identity shuffle of the RHS value?
11227     isRHSID &= (Mask[i]-e == i);
11228   }
11229
11230   // Eliminate identity shuffles.
11231   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11232   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11233   
11234   // If the LHS is a shufflevector itself, see if we can combine it with this
11235   // one without producing an unusual shuffle.  Here we are really conservative:
11236   // we are absolutely afraid of producing a shuffle mask not in the input
11237   // program, because the code gen may not be smart enough to turn a merged
11238   // shuffle into two specific shuffles: it may produce worse code.  As such,
11239   // we only merge two shuffles if the result is one of the two input shuffle
11240   // masks.  In this case, merging the shuffles just removes one instruction,
11241   // which we know is safe.  This is good for things like turning:
11242   // (splat(splat)) -> splat.
11243   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11244     if (isa<UndefValue>(RHS)) {
11245       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11246
11247       std::vector<unsigned> NewMask;
11248       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11249         if (Mask[i] >= 2*e)
11250           NewMask.push_back(2*e);
11251         else
11252           NewMask.push_back(LHSMask[Mask[i]]);
11253       
11254       // If the result mask is equal to the src shuffle or this shuffle mask, do
11255       // the replacement.
11256       if (NewMask == LHSMask || NewMask == Mask) {
11257         std::vector<Constant*> Elts;
11258         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11259           if (NewMask[i] >= e*2) {
11260             Elts.push_back(UndefValue::get(Type::Int32Ty));
11261           } else {
11262             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11263           }
11264         }
11265         return new ShuffleVectorInst(LHSSVI->getOperand(0),
11266                                      LHSSVI->getOperand(1),
11267                                      ConstantVector::get(Elts));
11268       }
11269     }
11270   }
11271
11272   return MadeChange ? &SVI : 0;
11273 }
11274
11275
11276
11277
11278 /// TryToSinkInstruction - Try to move the specified instruction from its
11279 /// current block into the beginning of DestBlock, which can only happen if it's
11280 /// safe to move the instruction past all of the instructions between it and the
11281 /// end of its block.
11282 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11283   assert(I->hasOneUse() && "Invariants didn't hold!");
11284
11285   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
11286   if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11287     return false;
11288
11289   // Do not sink alloca instructions out of the entry block.
11290   if (isa<AllocaInst>(I) && I->getParent() ==
11291         &DestBlock->getParent()->getEntryBlock())
11292     return false;
11293
11294   // We can only sink load instructions if there is nothing between the load and
11295   // the end of block that could change the value.
11296   if (I->mayReadFromMemory()) {
11297     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
11298          Scan != E; ++Scan)
11299       if (Scan->mayWriteToMemory())
11300         return false;
11301   }
11302
11303   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
11304
11305   I->moveBefore(InsertPos);
11306   ++NumSunkInst;
11307   return true;
11308 }
11309
11310
11311 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11312 /// all reachable code to the worklist.
11313 ///
11314 /// This has a couple of tricks to make the code faster and more powerful.  In
11315 /// particular, we constant fold and DCE instructions as we go, to avoid adding
11316 /// them to the worklist (this significantly speeds up instcombine on code where
11317 /// many instructions are dead or constant).  Additionally, if we find a branch
11318 /// whose condition is a known constant, we only visit the reachable successors.
11319 ///
11320 static void AddReachableCodeToWorklist(BasicBlock *BB, 
11321                                        SmallPtrSet<BasicBlock*, 64> &Visited,
11322                                        InstCombiner &IC,
11323                                        const TargetData *TD) {
11324   std::vector<BasicBlock*> Worklist;
11325   Worklist.push_back(BB);
11326
11327   while (!Worklist.empty()) {
11328     BB = Worklist.back();
11329     Worklist.pop_back();
11330     
11331     // We have now visited this block!  If we've already been here, ignore it.
11332     if (!Visited.insert(BB)) continue;
11333     
11334     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11335       Instruction *Inst = BBI++;
11336       
11337       // DCE instruction if trivially dead.
11338       if (isInstructionTriviallyDead(Inst)) {
11339         ++NumDeadInst;
11340         DOUT << "IC: DCE: " << *Inst;
11341         Inst->eraseFromParent();
11342         continue;
11343       }
11344       
11345       // ConstantProp instruction if trivially constant.
11346       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11347         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11348         Inst->replaceAllUsesWith(C);
11349         ++NumConstProp;
11350         Inst->eraseFromParent();
11351         continue;
11352       }
11353      
11354       IC.AddToWorkList(Inst);
11355     }
11356
11357     // Recursively visit successors.  If this is a branch or switch on a
11358     // constant, only visit the reachable successor.
11359     TerminatorInst *TI = BB->getTerminator();
11360     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11361       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11362         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
11363         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
11364         Worklist.push_back(ReachableBB);
11365         continue;
11366       }
11367     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11368       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11369         // See if this is an explicit destination.
11370         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11371           if (SI->getCaseValue(i) == Cond) {
11372             BasicBlock *ReachableBB = SI->getSuccessor(i);
11373             Worklist.push_back(ReachableBB);
11374             continue;
11375           }
11376         
11377         // Otherwise it is the default destination.
11378         Worklist.push_back(SI->getSuccessor(0));
11379         continue;
11380       }
11381     }
11382     
11383     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11384       Worklist.push_back(TI->getSuccessor(i));
11385   }
11386 }
11387
11388 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
11389   bool Changed = false;
11390   TD = &getAnalysis<TargetData>();
11391   
11392   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11393              << F.getNameStr() << "\n");
11394
11395   {
11396     // Do a depth-first traversal of the function, populate the worklist with
11397     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
11398     // track of which blocks we visit.
11399     SmallPtrSet<BasicBlock*, 64> Visited;
11400     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
11401
11402     // Do a quick scan over the function.  If we find any blocks that are
11403     // unreachable, remove any instructions inside of them.  This prevents
11404     // the instcombine code from having to deal with some bad special cases.
11405     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11406       if (!Visited.count(BB)) {
11407         Instruction *Term = BB->getTerminator();
11408         while (Term != BB->begin()) {   // Remove instrs bottom-up
11409           BasicBlock::iterator I = Term; --I;
11410
11411           DOUT << "IC: DCE: " << *I;
11412           ++NumDeadInst;
11413
11414           if (!I->use_empty())
11415             I->replaceAllUsesWith(UndefValue::get(I->getType()));
11416           I->eraseFromParent();
11417         }
11418       }
11419   }
11420
11421   while (!Worklist.empty()) {
11422     Instruction *I = RemoveOneFromWorkList();
11423     if (I == 0) continue;  // skip null values.
11424
11425     // Check to see if we can DCE the instruction.
11426     if (isInstructionTriviallyDead(I)) {
11427       // Add operands to the worklist.
11428       if (I->getNumOperands() < 4)
11429         AddUsesToWorkList(*I);
11430       ++NumDeadInst;
11431
11432       DOUT << "IC: DCE: " << *I;
11433
11434       I->eraseFromParent();
11435       RemoveFromWorkList(I);
11436       continue;
11437     }
11438
11439     // Instruction isn't dead, see if we can constant propagate it.
11440     if (Constant *C = ConstantFoldInstruction(I, TD)) {
11441       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
11442
11443       // Add operands to the worklist.
11444       AddUsesToWorkList(*I);
11445       ReplaceInstUsesWith(*I, C);
11446
11447       ++NumConstProp;
11448       I->eraseFromParent();
11449       RemoveFromWorkList(I);
11450       continue;
11451     }
11452
11453     if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11454       // See if we can constant fold its operands.
11455       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11456         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11457           if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11458             i->set(NewC);
11459         }
11460       }
11461     }
11462
11463     // See if we can trivially sink this instruction to a successor basic block.
11464     if (I->hasOneUse()) {
11465       BasicBlock *BB = I->getParent();
11466       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11467       if (UserParent != BB) {
11468         bool UserIsSuccessor = false;
11469         // See if the user is one of our successors.
11470         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11471           if (*SI == UserParent) {
11472             UserIsSuccessor = true;
11473             break;
11474           }
11475
11476         // If the user is one of our immediate successors, and if that successor
11477         // only has us as a predecessors (we'd have to split the critical edge
11478         // otherwise), we can keep going.
11479         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11480             next(pred_begin(UserParent)) == pred_end(UserParent))
11481           // Okay, the CFG is simple enough, try to sink this instruction.
11482           Changed |= TryToSinkInstruction(I, UserParent);
11483       }
11484     }
11485
11486     // Now that we have an instruction, try combining it to simplify it...
11487 #ifndef NDEBUG
11488     std::string OrigI;
11489 #endif
11490     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11491     if (Instruction *Result = visit(*I)) {
11492       ++NumCombined;
11493       // Should we replace the old instruction with a new one?
11494       if (Result != I) {
11495         DOUT << "IC: Old = " << *I
11496              << "    New = " << *Result;
11497
11498         // Everything uses the new instruction now.
11499         I->replaceAllUsesWith(Result);
11500
11501         // Push the new instruction and any users onto the worklist.
11502         AddToWorkList(Result);
11503         AddUsersToWorkList(*Result);
11504
11505         // Move the name to the new instruction first.
11506         Result->takeName(I);
11507
11508         // Insert the new instruction into the basic block...
11509         BasicBlock *InstParent = I->getParent();
11510         BasicBlock::iterator InsertPos = I;
11511
11512         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
11513           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11514             ++InsertPos;
11515
11516         InstParent->getInstList().insert(InsertPos, Result);
11517
11518         // Make sure that we reprocess all operands now that we reduced their
11519         // use counts.
11520         AddUsesToWorkList(*I);
11521
11522         // Instructions can end up on the worklist more than once.  Make sure
11523         // we do not process an instruction that has been deleted.
11524         RemoveFromWorkList(I);
11525
11526         // Erase the old instruction.
11527         InstParent->getInstList().erase(I);
11528       } else {
11529 #ifndef NDEBUG
11530         DOUT << "IC: Mod = " << OrigI
11531              << "    New = " << *I;
11532 #endif
11533
11534         // If the instruction was modified, it's possible that it is now dead.
11535         // if so, remove it.
11536         if (isInstructionTriviallyDead(I)) {
11537           // Make sure we process all operands now that we are reducing their
11538           // use counts.
11539           AddUsesToWorkList(*I);
11540
11541           // Instructions may end up in the worklist more than once.  Erase all
11542           // occurrences of this instruction.
11543           RemoveFromWorkList(I);
11544           I->eraseFromParent();
11545         } else {
11546           AddToWorkList(I);
11547           AddUsersToWorkList(*I);
11548         }
11549       }
11550       Changed = true;
11551     }
11552   }
11553
11554   assert(WorklistMap.empty() && "Worklist empty, but map not?");
11555     
11556   // Do an explicit clear, this shrinks the map if needed.
11557   WorklistMap.clear();
11558   return Changed;
11559 }
11560
11561
11562 bool InstCombiner::runOnFunction(Function &F) {
11563   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11564   
11565   bool EverMadeChange = false;
11566
11567   // Iterate while there is work to do.
11568   unsigned Iteration = 0;
11569   while (DoOneIteration(F, Iteration++))
11570     EverMadeChange = true;
11571   return EverMadeChange;
11572 }
11573
11574 FunctionPass *llvm::createInstructionCombiningPass() {
11575   return new InstCombiner();
11576 }
11577