Don't count DebugInfo instructions in another limit
[oota-llvm.git] / lib / Transforms / Scalar / InstructionCombining.cpp
1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions.  This pass does not modify the CFG.  This pass is where
12 // algebraic simplification happens.
13 //
14 // This pass combines things like:
15 //    %Y = add i32 %X, 1
16 //    %Z = add i32 %Y, 1
17 // into:
18 //    %Z = add i32 %X, 2
19 //
20 // This is a simple worklist driven algorithm.
21 //
22 // This pass guarantees that the following canonicalizations are performed on
23 // the program:
24 //    1. If a binary operator has a constant operand, it is moved to the RHS
25 //    2. Bitwise operators with constant operands are always grouped so that
26 //       shifts are performed first, then or's, then and's, then xor's.
27 //    3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All cmp instructions on boolean values are replaced with logical ops
29 //    5. add X, X is represented as (X*2) => (X << 1)
30 //    6. Multiplies with a power-of-two constant argument are transformed into
31 //       shifts.
32 //   ... etc.
33 //
34 //===----------------------------------------------------------------------===//
35
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/Analysis/ConstantFolding.h"
43 #include "llvm/Analysis/ValueTracking.h"
44 #include "llvm/Target/TargetData.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Support/CallSite.h"
48 #include "llvm/Support/ConstantRange.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/GetElementPtrTypeIterator.h"
51 #include "llvm/Support/InstVisitor.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/PatternMatch.h"
54 #include "llvm/Support/Compiler.h"
55 #include "llvm/ADT/DenseMap.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/SmallPtrSet.h"
58 #include "llvm/ADT/Statistic.h"
59 #include "llvm/ADT/STLExtras.h"
60 #include <algorithm>
61 #include <climits>
62 #include <sstream>
63 using namespace llvm;
64 using namespace llvm::PatternMatch;
65
66 STATISTIC(NumCombined , "Number of insts combined");
67 STATISTIC(NumConstProp, "Number of constant folds");
68 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70 STATISTIC(NumSunkInst , "Number of instructions sunk");
71
72 namespace {
73   class VISIBILITY_HIDDEN InstCombiner
74     : public FunctionPass,
75       public InstVisitor<InstCombiner, Instruction*> {
76     // Worklist of all of the instructions that need to be simplified.
77     SmallVector<Instruction*, 256> Worklist;
78     DenseMap<Instruction*, unsigned> WorklistMap;
79     TargetData *TD;
80     bool MustPreserveLCSSA;
81   public:
82     static char ID; // Pass identification, replacement for typeid
83     InstCombiner() : FunctionPass(&ID) {}
84
85     /// AddToWorkList - Add the specified instruction to the worklist if it
86     /// isn't already in it.
87     void AddToWorkList(Instruction *I) {
88       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
89         Worklist.push_back(I);
90     }
91     
92     // RemoveFromWorkList - remove I from the worklist if it exists.
93     void RemoveFromWorkList(Instruction *I) {
94       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95       if (It == WorklistMap.end()) return; // Not in worklist.
96       
97       // Don't bother moving everything down, just null out the slot.
98       Worklist[It->second] = 0;
99       
100       WorklistMap.erase(It);
101     }
102     
103     Instruction *RemoveOneFromWorkList() {
104       Instruction *I = Worklist.back();
105       Worklist.pop_back();
106       WorklistMap.erase(I);
107       return I;
108     }
109
110     
111     /// AddUsersToWorkList - When an instruction is simplified, add all users of
112     /// the instruction to the work lists because they might get more simplified
113     /// now.
114     ///
115     void AddUsersToWorkList(Value &I) {
116       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
117            UI != UE; ++UI)
118         AddToWorkList(cast<Instruction>(*UI));
119     }
120
121     /// AddUsesToWorkList - When an instruction is simplified, add operands to
122     /// the work lists because they might get more simplified now.
123     ///
124     void AddUsesToWorkList(Instruction &I) {
125       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
126         if (Instruction *Op = dyn_cast<Instruction>(*i))
127           AddToWorkList(Op);
128     }
129     
130     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131     /// dead.  Add all of its operands to the worklist, turning them into
132     /// undef's to reduce the number of uses of those instructions.
133     ///
134     /// Return the specified operand before it is turned into an undef.
135     ///
136     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137       Value *R = I.getOperand(op);
138       
139       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
140         if (Instruction *Op = dyn_cast<Instruction>(*i)) {
141           AddToWorkList(Op);
142           // Set the operand to undef to drop the use.
143           *i = UndefValue::get(Op->getType());
144         }
145       
146       return R;
147     }
148
149   public:
150     virtual bool runOnFunction(Function &F);
151     
152     bool DoOneIteration(Function &F, unsigned ItNum);
153
154     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
155       AU.addRequired<TargetData>();
156       AU.addPreservedID(LCSSAID);
157       AU.setPreservesCFG();
158     }
159
160     TargetData &getTargetData() const { return *TD; }
161
162     // Visitation implementation - Implement instruction combining for different
163     // instruction types.  The semantics are as follows:
164     // Return Value:
165     //    null        - No change was made
166     //     I          - Change was made, I is still valid, I may be dead though
167     //   otherwise    - Change was made, replace I with returned instruction
168     //
169     Instruction *visitAdd(BinaryOperator &I);
170     Instruction *visitSub(BinaryOperator &I);
171     Instruction *visitMul(BinaryOperator &I);
172     Instruction *visitURem(BinaryOperator &I);
173     Instruction *visitSRem(BinaryOperator &I);
174     Instruction *visitFRem(BinaryOperator &I);
175     bool SimplifyDivRemOfSelect(BinaryOperator &I);
176     Instruction *commonRemTransforms(BinaryOperator &I);
177     Instruction *commonIRemTransforms(BinaryOperator &I);
178     Instruction *commonDivTransforms(BinaryOperator &I);
179     Instruction *commonIDivTransforms(BinaryOperator &I);
180     Instruction *visitUDiv(BinaryOperator &I);
181     Instruction *visitSDiv(BinaryOperator &I);
182     Instruction *visitFDiv(BinaryOperator &I);
183     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
184     Instruction *visitAnd(BinaryOperator &I);
185     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
186     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
187                                      Value *A, Value *B, Value *C);
188     Instruction *visitOr (BinaryOperator &I);
189     Instruction *visitXor(BinaryOperator &I);
190     Instruction *visitShl(BinaryOperator &I);
191     Instruction *visitAShr(BinaryOperator &I);
192     Instruction *visitLShr(BinaryOperator &I);
193     Instruction *commonShiftTransforms(BinaryOperator &I);
194     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
195                                       Constant *RHSC);
196     Instruction *visitFCmpInst(FCmpInst &I);
197     Instruction *visitICmpInst(ICmpInst &I);
198     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
199     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
200                                                 Instruction *LHS,
201                                                 ConstantInt *RHS);
202     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
203                                 ConstantInt *DivRHS);
204
205     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
206                              ICmpInst::Predicate Cond, Instruction &I);
207     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
208                                      BinaryOperator &I);
209     Instruction *commonCastTransforms(CastInst &CI);
210     Instruction *commonIntCastTransforms(CastInst &CI);
211     Instruction *commonPointerCastTransforms(CastInst &CI);
212     Instruction *visitTrunc(TruncInst &CI);
213     Instruction *visitZExt(ZExtInst &CI);
214     Instruction *visitSExt(SExtInst &CI);
215     Instruction *visitFPTrunc(FPTruncInst &CI);
216     Instruction *visitFPExt(CastInst &CI);
217     Instruction *visitFPToUI(FPToUIInst &FI);
218     Instruction *visitFPToSI(FPToSIInst &FI);
219     Instruction *visitUIToFP(CastInst &CI);
220     Instruction *visitSIToFP(CastInst &CI);
221     Instruction *visitPtrToInt(CastInst &CI);
222     Instruction *visitIntToPtr(IntToPtrInst &CI);
223     Instruction *visitBitCast(BitCastInst &CI);
224     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
225                                 Instruction *FI);
226     Instruction *visitSelectInst(SelectInst &SI);
227     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
228     Instruction *visitCallInst(CallInst &CI);
229     Instruction *visitInvokeInst(InvokeInst &II);
230     Instruction *visitPHINode(PHINode &PN);
231     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
232     Instruction *visitAllocationInst(AllocationInst &AI);
233     Instruction *visitFreeInst(FreeInst &FI);
234     Instruction *visitLoadInst(LoadInst &LI);
235     Instruction *visitStoreInst(StoreInst &SI);
236     Instruction *visitBranchInst(BranchInst &BI);
237     Instruction *visitSwitchInst(SwitchInst &SI);
238     Instruction *visitInsertElementInst(InsertElementInst &IE);
239     Instruction *visitExtractElementInst(ExtractElementInst &EI);
240     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
241     Instruction *visitExtractValueInst(ExtractValueInst &EV);
242
243     // visitInstruction - Specify what to return for unhandled instructions...
244     Instruction *visitInstruction(Instruction &I) { return 0; }
245
246   private:
247     Instruction *visitCallSite(CallSite CS);
248     bool transformConstExprCastCall(CallSite CS);
249     Instruction *transformCallThroughTrampoline(CallSite CS);
250     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
251                                    bool DoXform = true);
252     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
253
254   public:
255     // InsertNewInstBefore - insert an instruction New before instruction Old
256     // in the program.  Add the new instruction to the worklist.
257     //
258     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
259       assert(New && New->getParent() == 0 &&
260              "New instruction already inserted into a basic block!");
261       BasicBlock *BB = Old.getParent();
262       BB->getInstList().insert(&Old, New);  // Insert inst
263       AddToWorkList(New);
264       return New;
265     }
266
267     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
268     /// This also adds the cast to the worklist.  Finally, this returns the
269     /// cast.
270     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
271                             Instruction &Pos) {
272       if (V->getType() == Ty) return V;
273
274       if (Constant *CV = dyn_cast<Constant>(V))
275         return ConstantExpr::getCast(opc, CV, Ty);
276       
277       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
278       AddToWorkList(C);
279       return C;
280     }
281         
282     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
283       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
284     }
285
286
287     // ReplaceInstUsesWith - This method is to be used when an instruction is
288     // found to be dead, replacable with another preexisting expression.  Here
289     // we add all uses of I to the worklist, replace all uses of I with the new
290     // value, then return I, so that the inst combiner will know that I was
291     // modified.
292     //
293     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
294       AddUsersToWorkList(I);         // Add all modified instrs to worklist
295       if (&I != V) {
296         I.replaceAllUsesWith(V);
297         return &I;
298       } else {
299         // If we are replacing the instruction with itself, this must be in a
300         // segment of unreachable code, so just clobber the instruction.
301         I.replaceAllUsesWith(UndefValue::get(I.getType()));
302         return &I;
303       }
304     }
305
306     // EraseInstFromFunction - When dealing with an instruction that has side
307     // effects or produces a void value, we can't rely on DCE to delete the
308     // instruction.  Instead, visit methods should return the value returned by
309     // this function.
310     Instruction *EraseInstFromFunction(Instruction &I) {
311       assert(I.use_empty() && "Cannot erase instruction that is used!");
312       AddUsesToWorkList(I);
313       RemoveFromWorkList(&I);
314       I.eraseFromParent();
315       return 0;  // Don't do anything with FI
316     }
317         
318     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
319                            APInt &KnownOne, unsigned Depth = 0) const {
320       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
321     }
322     
323     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
324                            unsigned Depth = 0) const {
325       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
326     }
327     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
328       return llvm::ComputeNumSignBits(Op, TD, Depth);
329     }
330
331   private:
332
333     /// SimplifyCommutative - This performs a few simplifications for 
334     /// commutative operators.
335     bool SimplifyCommutative(BinaryOperator &I);
336
337     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
338     /// most-complex to least-complex order.
339     bool SimplifyCompare(CmpInst &I);
340
341     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
342     /// based on the demanded bits.
343     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
344                                    APInt& KnownZero, APInt& KnownOne,
345                                    unsigned Depth);
346     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
347                               APInt& KnownZero, APInt& KnownOne,
348                               unsigned Depth=0);
349         
350     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
351     /// SimplifyDemandedBits knows about.  See if the instruction has any
352     /// properties that allow us to simplify its operands.
353     bool SimplifyDemandedInstructionBits(Instruction &Inst);
354         
355     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
356                                       APInt& UndefElts, unsigned Depth = 0);
357       
358     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
359     // PHI node as operand #0, see if we can fold the instruction into the PHI
360     // (which is only possible if all operands to the PHI are constants).
361     Instruction *FoldOpIntoPhi(Instruction &I);
362
363     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
364     // operator and they all are only used by the PHI, PHI together their
365     // inputs, and do the operation once, to the result of the PHI.
366     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
367     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
368     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
369
370     
371     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
372                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
373     
374     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
375                               bool isSub, Instruction &I);
376     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
377                                  bool isSigned, bool Inside, Instruction &IB);
378     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
379     Instruction *MatchBSwap(BinaryOperator &I);
380     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
381     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
382     Instruction *SimplifyMemSet(MemSetInst *MI);
383
384
385     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
386
387     bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
388                                     unsigned CastOpc, int &NumCastsRemoved);
389     unsigned GetOrEnforceKnownAlignment(Value *V,
390                                         unsigned PrefAlign = 0);
391
392   };
393 }
394
395 char InstCombiner::ID = 0;
396 static RegisterPass<InstCombiner>
397 X("instcombine", "Combine redundant instructions");
398
399 // getComplexity:  Assign a complexity or rank value to LLVM Values...
400 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
401 static unsigned getComplexity(Value *V) {
402   if (isa<Instruction>(V)) {
403     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
404       return 3;
405     return 4;
406   }
407   if (isa<Argument>(V)) return 3;
408   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
409 }
410
411 // isOnlyUse - Return true if this instruction will be deleted if we stop using
412 // it.
413 static bool isOnlyUse(Value *V) {
414   return V->hasOneUse() || isa<Constant>(V);
415 }
416
417 // getPromotedType - Return the specified type promoted as it would be to pass
418 // though a va_arg area...
419 static const Type *getPromotedType(const Type *Ty) {
420   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
421     if (ITy->getBitWidth() < 32)
422       return Type::Int32Ty;
423   }
424   return Ty;
425 }
426
427 /// getBitCastOperand - If the specified operand is a CastInst, a constant
428 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
429 /// operand value, otherwise return null.
430 static Value *getBitCastOperand(Value *V) {
431   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
432     // BitCastInst?
433     return I->getOperand(0);
434   else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
435     // GetElementPtrInst?
436     if (GEP->hasAllZeroIndices())
437       return GEP->getOperand(0);
438   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
439     if (CE->getOpcode() == Instruction::BitCast)
440       // BitCast ConstantExp?
441       return CE->getOperand(0);
442     else if (CE->getOpcode() == Instruction::GetElementPtr) {
443       // GetElementPtr ConstantExp?
444       for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
445            I != E; ++I) {
446         ConstantInt *CI = dyn_cast<ConstantInt>(I);
447         if (!CI || !CI->isZero())
448           // Any non-zero indices? Not cast-like.
449           return 0;
450       }
451       // All-zero indices? This is just like casting.
452       return CE->getOperand(0);
453     }
454   }
455   return 0;
456 }
457
458 /// This function is a wrapper around CastInst::isEliminableCastPair. It
459 /// simply extracts arguments and returns what that function returns.
460 static Instruction::CastOps 
461 isEliminableCastPair(
462   const CastInst *CI, ///< The first cast instruction
463   unsigned opcode,       ///< The opcode of the second cast instruction
464   const Type *DstTy,     ///< The target type for the second cast instruction
465   TargetData *TD         ///< The target data for pointer size
466 ) {
467   
468   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
469   const Type *MidTy = CI->getType();                  // B from above
470
471   // Get the opcodes of the two Cast instructions
472   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
473   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
474
475   return Instruction::CastOps(
476       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
477                                      DstTy, TD->getIntPtrType()));
478 }
479
480 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
481 /// in any code being generated.  It does not require codegen if V is simple
482 /// enough or if the cast can be folded into other casts.
483 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
484                               const Type *Ty, TargetData *TD) {
485   if (V->getType() == Ty || isa<Constant>(V)) return false;
486   
487   // If this is another cast that can be eliminated, it isn't codegen either.
488   if (const CastInst *CI = dyn_cast<CastInst>(V))
489     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
490       return false;
491   return true;
492 }
493
494 // SimplifyCommutative - This performs a few simplifications for commutative
495 // operators:
496 //
497 //  1. Order operands such that they are listed from right (least complex) to
498 //     left (most complex).  This puts constants before unary operators before
499 //     binary operators.
500 //
501 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
502 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
503 //
504 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
505   bool Changed = false;
506   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
507     Changed = !I.swapOperands();
508
509   if (!I.isAssociative()) return Changed;
510   Instruction::BinaryOps Opcode = I.getOpcode();
511   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
512     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
513       if (isa<Constant>(I.getOperand(1))) {
514         Constant *Folded = ConstantExpr::get(I.getOpcode(),
515                                              cast<Constant>(I.getOperand(1)),
516                                              cast<Constant>(Op->getOperand(1)));
517         I.setOperand(0, Op->getOperand(0));
518         I.setOperand(1, Folded);
519         return true;
520       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
521         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
522             isOnlyUse(Op) && isOnlyUse(Op1)) {
523           Constant *C1 = cast<Constant>(Op->getOperand(1));
524           Constant *C2 = cast<Constant>(Op1->getOperand(1));
525
526           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
527           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
528           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
529                                                     Op1->getOperand(0),
530                                                     Op1->getName(), &I);
531           AddToWorkList(New);
532           I.setOperand(0, New);
533           I.setOperand(1, Folded);
534           return true;
535         }
536     }
537   return Changed;
538 }
539
540 /// SimplifyCompare - For a CmpInst this function just orders the operands
541 /// so that theyare listed from right (least complex) to left (most complex).
542 /// This puts constants before unary operators before binary operators.
543 bool InstCombiner::SimplifyCompare(CmpInst &I) {
544   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
545     return false;
546   I.swapOperands();
547   // Compare instructions are not associative so there's nothing else we can do.
548   return true;
549 }
550
551 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
552 // if the LHS is a constant zero (which is the 'negate' form).
553 //
554 static inline Value *dyn_castNegVal(Value *V) {
555   if (BinaryOperator::isNeg(V))
556     return BinaryOperator::getNegArgument(V);
557
558   // Constants can be considered to be negated values if they can be folded.
559   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
560     return ConstantExpr::getNeg(C);
561
562   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
563     if (C->getType()->getElementType()->isInteger())
564       return ConstantExpr::getNeg(C);
565
566   return 0;
567 }
568
569 static inline Value *dyn_castNotVal(Value *V) {
570   if (BinaryOperator::isNot(V))
571     return BinaryOperator::getNotArgument(V);
572
573   // Constants can be considered to be not'ed values...
574   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
575     return ConstantInt::get(~C->getValue());
576   return 0;
577 }
578
579 // dyn_castFoldableMul - If this value is a multiply that can be folded into
580 // other computations (because it has a constant operand), return the
581 // non-constant operand of the multiply, and set CST to point to the multiplier.
582 // Otherwise, return null.
583 //
584 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
585   if (V->hasOneUse() && V->getType()->isInteger())
586     if (Instruction *I = dyn_cast<Instruction>(V)) {
587       if (I->getOpcode() == Instruction::Mul)
588         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
589           return I->getOperand(0);
590       if (I->getOpcode() == Instruction::Shl)
591         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
592           // The multiplier is really 1 << CST.
593           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
594           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
595           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
596           return I->getOperand(0);
597         }
598     }
599   return 0;
600 }
601
602 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
603 /// expression, return it.
604 static User *dyn_castGetElementPtr(Value *V) {
605   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
606   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
607     if (CE->getOpcode() == Instruction::GetElementPtr)
608       return cast<User>(V);
609   return false;
610 }
611
612 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
613 /// opcode value. Otherwise return UserOp1.
614 static unsigned getOpcode(const Value *V) {
615   if (const Instruction *I = dyn_cast<Instruction>(V))
616     return I->getOpcode();
617   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
618     return CE->getOpcode();
619   // Use UserOp1 to mean there's no opcode.
620   return Instruction::UserOp1;
621 }
622
623 /// AddOne - Add one to a ConstantInt
624 static ConstantInt *AddOne(ConstantInt *C) {
625   APInt Val(C->getValue());
626   return ConstantInt::get(++Val);
627 }
628 /// SubOne - Subtract one from a ConstantInt
629 static ConstantInt *SubOne(ConstantInt *C) {
630   APInt Val(C->getValue());
631   return ConstantInt::get(--Val);
632 }
633 /// Add - Add two ConstantInts together
634 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
635   return ConstantInt::get(C1->getValue() + C2->getValue());
636 }
637 /// And - Bitwise AND two ConstantInts together
638 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
639   return ConstantInt::get(C1->getValue() & C2->getValue());
640 }
641 /// Subtract - Subtract one ConstantInt from another
642 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
643   return ConstantInt::get(C1->getValue() - C2->getValue());
644 }
645 /// Multiply - Multiply two ConstantInts together
646 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
647   return ConstantInt::get(C1->getValue() * C2->getValue());
648 }
649 /// MultiplyOverflows - True if the multiply can not be expressed in an int
650 /// this size.
651 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
652   uint32_t W = C1->getBitWidth();
653   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
654   if (sign) {
655     LHSExt.sext(W * 2);
656     RHSExt.sext(W * 2);
657   } else {
658     LHSExt.zext(W * 2);
659     RHSExt.zext(W * 2);
660   }
661
662   APInt MulExt = LHSExt * RHSExt;
663
664   if (sign) {
665     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
666     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
667     return MulExt.slt(Min) || MulExt.sgt(Max);
668   } else 
669     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
670 }
671
672
673 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
674 /// specified instruction is a constant integer.  If so, check to see if there
675 /// are any bits set in the constant that are not demanded.  If so, shrink the
676 /// constant and return true.
677 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
678                                    APInt Demanded) {
679   assert(I && "No instruction?");
680   assert(OpNo < I->getNumOperands() && "Operand index too large");
681
682   // If the operand is not a constant integer, nothing to do.
683   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
684   if (!OpC) return false;
685
686   // If there are no bits set that aren't demanded, nothing to do.
687   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
688   if ((~Demanded & OpC->getValue()) == 0)
689     return false;
690
691   // This instruction is producing bits that are not demanded. Shrink the RHS.
692   Demanded &= OpC->getValue();
693   I->setOperand(OpNo, ConstantInt::get(Demanded));
694   return true;
695 }
696
697 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
698 // set of known zero and one bits, compute the maximum and minimum values that
699 // could have the specified known zero and known one bits, returning them in
700 // min/max.
701 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
702                                                    const APInt& KnownZero,
703                                                    const APInt& KnownOne,
704                                                    APInt& Min, APInt& Max) {
705   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
706   assert(KnownZero.getBitWidth() == BitWidth && 
707          KnownOne.getBitWidth() == BitWidth &&
708          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
709          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
710   APInt UnknownBits = ~(KnownZero|KnownOne);
711
712   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
713   // bit if it is unknown.
714   Min = KnownOne;
715   Max = KnownOne|UnknownBits;
716   
717   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
718     Min.set(BitWidth-1);
719     Max.clear(BitWidth-1);
720   }
721 }
722
723 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
724 // a set of known zero and one bits, compute the maximum and minimum values that
725 // could have the specified known zero and known one bits, returning them in
726 // min/max.
727 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
728                                                      const APInt &KnownZero,
729                                                      const APInt &KnownOne,
730                                                      APInt &Min, APInt &Max) {
731   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
732   assert(KnownZero.getBitWidth() == BitWidth && 
733          KnownOne.getBitWidth() == BitWidth &&
734          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
735          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
736   APInt UnknownBits = ~(KnownZero|KnownOne);
737   
738   // The minimum value is when the unknown bits are all zeros.
739   Min = KnownOne;
740   // The maximum value is when the unknown bits are all ones.
741   Max = KnownOne|UnknownBits;
742 }
743
744 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
745 /// SimplifyDemandedBits knows about.  See if the instruction has any
746 /// properties that allow us to simplify its operands.
747 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
748   unsigned BitWidth = cast<IntegerType>(Inst.getType())->getBitWidth();
749   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
750   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
751   
752   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
753                                      KnownZero, KnownOne, 0);
754   if (V == 0) return false;
755   if (V == &Inst) return true;
756   ReplaceInstUsesWith(Inst, V);
757   return true;
758 }
759
760 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
761 /// specified instruction operand if possible, updating it in place.  It returns
762 /// true if it made any change and false otherwise.
763 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
764                                         APInt &KnownZero, APInt &KnownOne,
765                                         unsigned Depth) {
766   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
767                                           KnownZero, KnownOne, Depth);
768   if (NewVal == 0) return false;
769   U.set(NewVal);
770   return true;
771 }
772
773
774 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
775 /// value based on the demanded bits.  When this function is called, it is known
776 /// that only the bits set in DemandedMask of the result of V are ever used
777 /// downstream. Consequently, depending on the mask and V, it may be possible
778 /// to replace V with a constant or one of its operands. In such cases, this
779 /// function does the replacement and returns true. In all other cases, it
780 /// returns false after analyzing the expression and setting KnownOne and known
781 /// to be one in the expression.  KnownZero contains all the bits that are known
782 /// to be zero in the expression. These are provided to potentially allow the
783 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
784 /// the expression. KnownOne and KnownZero always follow the invariant that 
785 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
786 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
787 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
788 /// and KnownOne must all be the same.
789 ///
790 /// This returns null if it did not change anything and it permits no
791 /// simplification.  This returns V itself if it did some simplification of V's
792 /// operands based on the information about what bits are demanded. This returns
793 /// some other non-null value if it found out that V is equal to another value
794 /// in the context where the specified bits are demanded, but not for all users.
795 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
796                                              APInt &KnownZero, APInt &KnownOne,
797                                              unsigned Depth) {
798   assert(V != 0 && "Null pointer of Value???");
799   assert(Depth <= 6 && "Limit Search Depth");
800   uint32_t BitWidth = DemandedMask.getBitWidth();
801   const IntegerType *VTy = cast<IntegerType>(V->getType());
802   assert(VTy->getBitWidth() == BitWidth && 
803          KnownZero.getBitWidth() == BitWidth && 
804          KnownOne.getBitWidth() == BitWidth &&
805          "Value *V, DemandedMask, KnownZero and KnownOne \
806           must have same BitWidth");
807   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
808     // We know all of the bits for a constant!
809     KnownOne = CI->getValue() & DemandedMask;
810     KnownZero = ~KnownOne & DemandedMask;
811     return 0;
812   }
813   
814   KnownZero.clear();
815   KnownOne.clear();
816   if (DemandedMask == 0) {   // Not demanding any bits from V.
817     if (isa<UndefValue>(V))
818       return 0;
819     return UndefValue::get(VTy);
820   }
821   
822   if (Depth == 6)        // Limit search depth.
823     return 0;
824   
825   Instruction *I = dyn_cast<Instruction>(V);
826   if (!I) return 0;        // Only analyze instructions.
827   
828   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
829   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
830
831   // If there are multiple uses of this value and we aren't at the root, then
832   // we can't do any simplifications of the operands, because DemandedMask
833   // only reflects the bits demanded by *one* of the users.
834   if (Depth != 0 && !I->hasOneUse()) {
835     // Despite the fact that we can't simplify this instruction in all User's
836     // context, we can at least compute the knownzero/knownone bits, and we can
837     // do simplifications that apply to *just* the one user if we know that
838     // this instruction has a simpler value in that context.
839     if (I->getOpcode() == Instruction::And) {
840       // If either the LHS or the RHS are Zero, the result is zero.
841       ComputeMaskedBits(I->getOperand(1), DemandedMask,
842                         RHSKnownZero, RHSKnownOne, Depth+1);
843       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
844                         LHSKnownZero, LHSKnownOne, Depth+1);
845       
846       // If all of the demanded bits are known 1 on one side, return the other.
847       // These bits cannot contribute to the result of the 'and' in this
848       // context.
849       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
850           (DemandedMask & ~LHSKnownZero))
851         return I->getOperand(0);
852       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
853           (DemandedMask & ~RHSKnownZero))
854         return I->getOperand(1);
855       
856       // If all of the demanded bits in the inputs are known zeros, return zero.
857       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
858         return Constant::getNullValue(VTy);
859       
860     } else if (I->getOpcode() == Instruction::Or) {
861       // We can simplify (X|Y) -> X or Y in the user's context if we know that
862       // only bits from X or Y are demanded.
863       
864       // If either the LHS or the RHS are One, the result is One.
865       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
866                         RHSKnownZero, RHSKnownOne, Depth+1);
867       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
868                         LHSKnownZero, LHSKnownOne, Depth+1);
869       
870       // If all of the demanded bits are known zero on one side, return the
871       // other.  These bits cannot contribute to the result of the 'or' in this
872       // context.
873       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
874           (DemandedMask & ~LHSKnownOne))
875         return I->getOperand(0);
876       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
877           (DemandedMask & ~RHSKnownOne))
878         return I->getOperand(1);
879       
880       // If all of the potentially set bits on one side are known to be set on
881       // the other side, just use the 'other' side.
882       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
883           (DemandedMask & (~RHSKnownZero)))
884         return I->getOperand(0);
885       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
886           (DemandedMask & (~LHSKnownZero)))
887         return I->getOperand(1);
888     }
889     
890     // Compute the KnownZero/KnownOne bits to simplify things downstream.
891     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
892     return 0;
893   }
894   
895   // If this is the root being simplified, allow it to have multiple uses,
896   // just set the DemandedMask to all bits so that we can try to simplify the
897   // operands.  This allows visitTruncInst (for example) to simplify the
898   // operand of a trunc without duplicating all the logic below.
899   if (Depth == 0 && !V->hasOneUse())
900     DemandedMask = APInt::getAllOnesValue(BitWidth);
901   
902   switch (I->getOpcode()) {
903   default:
904     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
905     break;
906   case Instruction::And:
907     // If either the LHS or the RHS are Zero, the result is zero.
908     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
909                              RHSKnownZero, RHSKnownOne, Depth+1) ||
910         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
911                              LHSKnownZero, LHSKnownOne, Depth+1))
912       return I;
913     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
914     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
915
916     // If all of the demanded bits are known 1 on one side, return the other.
917     // These bits cannot contribute to the result of the 'and'.
918     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
919         (DemandedMask & ~LHSKnownZero))
920       return I->getOperand(0);
921     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
922         (DemandedMask & ~RHSKnownZero))
923       return I->getOperand(1);
924     
925     // If all of the demanded bits in the inputs are known zeros, return zero.
926     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
927       return Constant::getNullValue(VTy);
928       
929     // If the RHS is a constant, see if we can simplify it.
930     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
931       return I;
932       
933     // Output known-1 bits are only known if set in both the LHS & RHS.
934     RHSKnownOne &= LHSKnownOne;
935     // Output known-0 are known to be clear if zero in either the LHS | RHS.
936     RHSKnownZero |= LHSKnownZero;
937     break;
938   case Instruction::Or:
939     // If either the LHS or the RHS are One, the result is One.
940     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
941                              RHSKnownZero, RHSKnownOne, Depth+1) ||
942         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
943                              LHSKnownZero, LHSKnownOne, Depth+1))
944       return I;
945     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
946     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
947     
948     // If all of the demanded bits are known zero on one side, return the other.
949     // These bits cannot contribute to the result of the 'or'.
950     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
951         (DemandedMask & ~LHSKnownOne))
952       return I->getOperand(0);
953     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
954         (DemandedMask & ~RHSKnownOne))
955       return I->getOperand(1);
956
957     // If all of the potentially set bits on one side are known to be set on
958     // the other side, just use the 'other' side.
959     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
960         (DemandedMask & (~RHSKnownZero)))
961       return I->getOperand(0);
962     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
963         (DemandedMask & (~LHSKnownZero)))
964       return I->getOperand(1);
965         
966     // If the RHS is a constant, see if we can simplify it.
967     if (ShrinkDemandedConstant(I, 1, DemandedMask))
968       return I;
969           
970     // Output known-0 bits are only known if clear in both the LHS & RHS.
971     RHSKnownZero &= LHSKnownZero;
972     // Output known-1 are known to be set if set in either the LHS | RHS.
973     RHSKnownOne |= LHSKnownOne;
974     break;
975   case Instruction::Xor: {
976     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
977                              RHSKnownZero, RHSKnownOne, Depth+1) ||
978         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
979                              LHSKnownZero, LHSKnownOne, Depth+1))
980       return I;
981     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
982     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
983     
984     // If all of the demanded bits are known zero on one side, return the other.
985     // These bits cannot contribute to the result of the 'xor'.
986     if ((DemandedMask & RHSKnownZero) == DemandedMask)
987       return I->getOperand(0);
988     if ((DemandedMask & LHSKnownZero) == DemandedMask)
989       return I->getOperand(1);
990     
991     // Output known-0 bits are known if clear or set in both the LHS & RHS.
992     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
993                          (RHSKnownOne & LHSKnownOne);
994     // Output known-1 are known to be set if set in only one of the LHS, RHS.
995     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
996                         (RHSKnownOne & LHSKnownZero);
997     
998     // If all of the demanded bits are known to be zero on one side or the
999     // other, turn this into an *inclusive* or.
1000     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1001     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1002       Instruction *Or =
1003         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1004                                  I->getName());
1005       return InsertNewInstBefore(Or, *I);
1006     }
1007     
1008     // If all of the demanded bits on one side are known, and all of the set
1009     // bits on that side are also known to be set on the other side, turn this
1010     // into an AND, as we know the bits will be cleared.
1011     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1012     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1013       // all known
1014       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1015         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1016         Instruction *And = 
1017           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1018         return InsertNewInstBefore(And, *I);
1019       }
1020     }
1021     
1022     // If the RHS is a constant, see if we can simplify it.
1023     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1024     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1025       return I;
1026     
1027     RHSKnownZero = KnownZeroOut;
1028     RHSKnownOne  = KnownOneOut;
1029     break;
1030   }
1031   case Instruction::Select:
1032     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1033                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1034         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1035                              LHSKnownZero, LHSKnownOne, Depth+1))
1036       return I;
1037     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1038     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1039     
1040     // If the operands are constants, see if we can simplify them.
1041     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1042         ShrinkDemandedConstant(I, 2, DemandedMask))
1043       return I;
1044     
1045     // Only known if known in both the LHS and RHS.
1046     RHSKnownOne &= LHSKnownOne;
1047     RHSKnownZero &= LHSKnownZero;
1048     break;
1049   case Instruction::Trunc: {
1050     unsigned truncBf = I->getOperand(0)->getType()->getPrimitiveSizeInBits();
1051     DemandedMask.zext(truncBf);
1052     RHSKnownZero.zext(truncBf);
1053     RHSKnownOne.zext(truncBf);
1054     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1055                              RHSKnownZero, RHSKnownOne, Depth+1))
1056       return I;
1057     DemandedMask.trunc(BitWidth);
1058     RHSKnownZero.trunc(BitWidth);
1059     RHSKnownOne.trunc(BitWidth);
1060     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1061     break;
1062   }
1063   case Instruction::BitCast:
1064     if (!I->getOperand(0)->getType()->isInteger())
1065       return false;  // vector->int or fp->int?
1066     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1067                              RHSKnownZero, RHSKnownOne, Depth+1))
1068       return I;
1069     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1070     break;
1071   case Instruction::ZExt: {
1072     // Compute the bits in the result that are not present in the input.
1073     unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
1074     
1075     DemandedMask.trunc(SrcBitWidth);
1076     RHSKnownZero.trunc(SrcBitWidth);
1077     RHSKnownOne.trunc(SrcBitWidth);
1078     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1079                              RHSKnownZero, RHSKnownOne, Depth+1))
1080       return I;
1081     DemandedMask.zext(BitWidth);
1082     RHSKnownZero.zext(BitWidth);
1083     RHSKnownOne.zext(BitWidth);
1084     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1085     // The top bits are known to be zero.
1086     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1087     break;
1088   }
1089   case Instruction::SExt: {
1090     // Compute the bits in the result that are not present in the input.
1091     unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
1092     
1093     APInt InputDemandedBits = DemandedMask & 
1094                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1095
1096     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1097     // If any of the sign extended bits are demanded, we know that the sign
1098     // bit is demanded.
1099     if ((NewBits & DemandedMask) != 0)
1100       InputDemandedBits.set(SrcBitWidth-1);
1101       
1102     InputDemandedBits.trunc(SrcBitWidth);
1103     RHSKnownZero.trunc(SrcBitWidth);
1104     RHSKnownOne.trunc(SrcBitWidth);
1105     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1106                              RHSKnownZero, RHSKnownOne, Depth+1))
1107       return I;
1108     InputDemandedBits.zext(BitWidth);
1109     RHSKnownZero.zext(BitWidth);
1110     RHSKnownOne.zext(BitWidth);
1111     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1112       
1113     // If the sign bit of the input is known set or clear, then we know the
1114     // top bits of the result.
1115
1116     // If the input sign bit is known zero, or if the NewBits are not demanded
1117     // convert this into a zero extension.
1118     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1119       // Convert to ZExt cast
1120       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1121       return InsertNewInstBefore(NewCast, *I);
1122     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1123       RHSKnownOne |= NewBits;
1124     }
1125     break;
1126   }
1127   case Instruction::Add: {
1128     // Figure out what the input bits are.  If the top bits of the and result
1129     // are not demanded, then the add doesn't demand them from its input
1130     // either.
1131     unsigned NLZ = DemandedMask.countLeadingZeros();
1132       
1133     // If there is a constant on the RHS, there are a variety of xformations
1134     // we can do.
1135     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1136       // If null, this should be simplified elsewhere.  Some of the xforms here
1137       // won't work if the RHS is zero.
1138       if (RHS->isZero())
1139         break;
1140       
1141       // If the top bit of the output is demanded, demand everything from the
1142       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1143       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1144
1145       // Find information about known zero/one bits in the input.
1146       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1147                                LHSKnownZero, LHSKnownOne, Depth+1))
1148         return I;
1149
1150       // If the RHS of the add has bits set that can't affect the input, reduce
1151       // the constant.
1152       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1153         return I;
1154       
1155       // Avoid excess work.
1156       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1157         break;
1158       
1159       // Turn it into OR if input bits are zero.
1160       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1161         Instruction *Or =
1162           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1163                                    I->getName());
1164         return InsertNewInstBefore(Or, *I);
1165       }
1166       
1167       // We can say something about the output known-zero and known-one bits,
1168       // depending on potential carries from the input constant and the
1169       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1170       // bits set and the RHS constant is 0x01001, then we know we have a known
1171       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1172       
1173       // To compute this, we first compute the potential carry bits.  These are
1174       // the bits which may be modified.  I'm not aware of a better way to do
1175       // this scan.
1176       const APInt &RHSVal = RHS->getValue();
1177       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1178       
1179       // Now that we know which bits have carries, compute the known-1/0 sets.
1180       
1181       // Bits are known one if they are known zero in one operand and one in the
1182       // other, and there is no input carry.
1183       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1184                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1185       
1186       // Bits are known zero if they are known zero in both operands and there
1187       // is no input carry.
1188       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1189     } else {
1190       // If the high-bits of this ADD are not demanded, then it does not demand
1191       // the high bits of its LHS or RHS.
1192       if (DemandedMask[BitWidth-1] == 0) {
1193         // Right fill the mask of bits for this ADD to demand the most
1194         // significant bit and all those below it.
1195         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1196         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1197                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1198             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1199                                  LHSKnownZero, LHSKnownOne, Depth+1))
1200           return I;
1201       }
1202     }
1203     break;
1204   }
1205   case Instruction::Sub:
1206     // If the high-bits of this SUB are not demanded, then it does not demand
1207     // the high bits of its LHS or RHS.
1208     if (DemandedMask[BitWidth-1] == 0) {
1209       // Right fill the mask of bits for this SUB to demand the most
1210       // significant bit and all those below it.
1211       uint32_t NLZ = DemandedMask.countLeadingZeros();
1212       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1213       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1214                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1215           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1216                                LHSKnownZero, LHSKnownOne, Depth+1))
1217         return I;
1218     }
1219     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1220     // the known zeros and ones.
1221     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1222     break;
1223   case Instruction::Shl:
1224     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1225       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1226       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1227       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1228                                RHSKnownZero, RHSKnownOne, Depth+1))
1229         return I;
1230       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1231       RHSKnownZero <<= ShiftAmt;
1232       RHSKnownOne  <<= ShiftAmt;
1233       // low bits known zero.
1234       if (ShiftAmt)
1235         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1236     }
1237     break;
1238   case Instruction::LShr:
1239     // For a logical shift right
1240     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1241       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1242       
1243       // Unsigned shift right.
1244       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1245       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1246                                RHSKnownZero, RHSKnownOne, Depth+1))
1247         return I;
1248       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1249       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1250       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1251       if (ShiftAmt) {
1252         // Compute the new bits that are at the top now.
1253         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1254         RHSKnownZero |= HighBits;  // high bits known zero.
1255       }
1256     }
1257     break;
1258   case Instruction::AShr:
1259     // If this is an arithmetic shift right and only the low-bit is set, we can
1260     // always convert this into a logical shr, even if the shift amount is
1261     // variable.  The low bit of the shift cannot be an input sign bit unless
1262     // the shift amount is >= the size of the datatype, which is undefined.
1263     if (DemandedMask == 1) {
1264       // Perform the logical shift right.
1265       Instruction *NewVal = BinaryOperator::CreateLShr(
1266                         I->getOperand(0), I->getOperand(1), I->getName());
1267       return InsertNewInstBefore(NewVal, *I);
1268     }    
1269
1270     // If the sign bit is the only bit demanded by this ashr, then there is no
1271     // need to do it, the shift doesn't change the high bit.
1272     if (DemandedMask.isSignBit())
1273       return I->getOperand(0);
1274     
1275     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1276       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1277       
1278       // Signed shift right.
1279       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1280       // If any of the "high bits" are demanded, we should set the sign bit as
1281       // demanded.
1282       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1283         DemandedMaskIn.set(BitWidth-1);
1284       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1285                                RHSKnownZero, RHSKnownOne, Depth+1))
1286         return I;
1287       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1288       // Compute the new bits that are at the top now.
1289       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1290       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1291       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1292         
1293       // Handle the sign bits.
1294       APInt SignBit(APInt::getSignBit(BitWidth));
1295       // Adjust to where it is now in the mask.
1296       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1297         
1298       // If the input sign bit is known to be zero, or if none of the top bits
1299       // are demanded, turn this into an unsigned shift right.
1300       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1301           (HighBits & ~DemandedMask) == HighBits) {
1302         // Perform the logical shift right.
1303         Instruction *NewVal = BinaryOperator::CreateLShr(
1304                           I->getOperand(0), SA, I->getName());
1305         return InsertNewInstBefore(NewVal, *I);
1306       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1307         RHSKnownOne |= HighBits;
1308       }
1309     }
1310     break;
1311   case Instruction::SRem:
1312     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1313       APInt RA = Rem->getValue().abs();
1314       if (RA.isPowerOf2()) {
1315         if (DemandedMask.ule(RA))    // srem won't affect demanded bits
1316           return I->getOperand(0);
1317
1318         APInt LowBits = RA - 1;
1319         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1320         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1321                                  LHSKnownZero, LHSKnownOne, Depth+1))
1322           return I;
1323
1324         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1325           LHSKnownZero |= ~LowBits;
1326
1327         KnownZero |= LHSKnownZero & DemandedMask;
1328
1329         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1330       }
1331     }
1332     break;
1333   case Instruction::URem: {
1334     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1335     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1336     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1337                              KnownZero2, KnownOne2, Depth+1) ||
1338         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1339                              KnownZero2, KnownOne2, Depth+1))
1340       return I;
1341
1342     unsigned Leaders = KnownZero2.countLeadingOnes();
1343     Leaders = std::max(Leaders,
1344                        KnownZero2.countLeadingOnes());
1345     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1346     break;
1347   }
1348   case Instruction::Call:
1349     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1350       switch (II->getIntrinsicID()) {
1351       default: break;
1352       case Intrinsic::bswap: {
1353         // If the only bits demanded come from one byte of the bswap result,
1354         // just shift the input byte into position to eliminate the bswap.
1355         unsigned NLZ = DemandedMask.countLeadingZeros();
1356         unsigned NTZ = DemandedMask.countTrailingZeros();
1357           
1358         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1359         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1360         // have 14 leading zeros, round to 8.
1361         NLZ &= ~7;
1362         NTZ &= ~7;
1363         // If we need exactly one byte, we can do this transformation.
1364         if (BitWidth-NLZ-NTZ == 8) {
1365           unsigned ResultBit = NTZ;
1366           unsigned InputBit = BitWidth-NTZ-8;
1367           
1368           // Replace this with either a left or right shift to get the byte into
1369           // the right place.
1370           Instruction *NewVal;
1371           if (InputBit > ResultBit)
1372             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1373                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1374           else
1375             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1376                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1377           NewVal->takeName(I);
1378           return InsertNewInstBefore(NewVal, *I);
1379         }
1380           
1381         // TODO: Could compute known zero/one bits based on the input.
1382         break;
1383       }
1384       }
1385     }
1386     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1387     break;
1388   }
1389   
1390   // If the client is only demanding bits that we know, return the known
1391   // constant.
1392   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1393     return ConstantInt::get(RHSKnownOne);
1394   return false;
1395 }
1396
1397
1398 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1399 /// any number of elements. DemandedElts contains the set of elements that are
1400 /// actually used by the caller.  This method analyzes which elements of the
1401 /// operand are undef and returns that information in UndefElts.
1402 ///
1403 /// If the information about demanded elements can be used to simplify the
1404 /// operation, the operation is simplified, then the resultant value is
1405 /// returned.  This returns null if no change was made.
1406 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1407                                                 APInt& UndefElts,
1408                                                 unsigned Depth) {
1409   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1410   APInt EltMask(APInt::getAllOnesValue(VWidth));
1411   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1412
1413   if (isa<UndefValue>(V)) {
1414     // If the entire vector is undefined, just return this info.
1415     UndefElts = EltMask;
1416     return 0;
1417   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1418     UndefElts = EltMask;
1419     return UndefValue::get(V->getType());
1420   }
1421
1422   UndefElts = 0;
1423   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1424     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1425     Constant *Undef = UndefValue::get(EltTy);
1426
1427     std::vector<Constant*> Elts;
1428     for (unsigned i = 0; i != VWidth; ++i)
1429       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1430         Elts.push_back(Undef);
1431         UndefElts.set(i);
1432       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1433         Elts.push_back(Undef);
1434         UndefElts.set(i);
1435       } else {                               // Otherwise, defined.
1436         Elts.push_back(CP->getOperand(i));
1437       }
1438
1439     // If we changed the constant, return it.
1440     Constant *NewCP = ConstantVector::get(Elts);
1441     return NewCP != CP ? NewCP : 0;
1442   } else if (isa<ConstantAggregateZero>(V)) {
1443     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1444     // set to undef.
1445     
1446     // Check if this is identity. If so, return 0 since we are not simplifying
1447     // anything.
1448     if (DemandedElts == ((1ULL << VWidth) -1))
1449       return 0;
1450     
1451     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1452     Constant *Zero = Constant::getNullValue(EltTy);
1453     Constant *Undef = UndefValue::get(EltTy);
1454     std::vector<Constant*> Elts;
1455     for (unsigned i = 0; i != VWidth; ++i) {
1456       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1457       Elts.push_back(Elt);
1458     }
1459     UndefElts = DemandedElts ^ EltMask;
1460     return ConstantVector::get(Elts);
1461   }
1462   
1463   // Limit search depth.
1464   if (Depth == 10)
1465     return false;
1466
1467   // If multiple users are using the root value, procede with
1468   // simplification conservatively assuming that all elements
1469   // are needed.
1470   if (!V->hasOneUse()) {
1471     // Quit if we find multiple users of a non-root value though.
1472     // They'll be handled when it's their turn to be visited by
1473     // the main instcombine process.
1474     if (Depth != 0)
1475       // TODO: Just compute the UndefElts information recursively.
1476       return false;
1477
1478     // Conservatively assume that all elements are needed.
1479     DemandedElts = EltMask;
1480   }
1481   
1482   Instruction *I = dyn_cast<Instruction>(V);
1483   if (!I) return false;        // Only analyze instructions.
1484   
1485   bool MadeChange = false;
1486   APInt UndefElts2(VWidth, 0);
1487   Value *TmpV;
1488   switch (I->getOpcode()) {
1489   default: break;
1490     
1491   case Instruction::InsertElement: {
1492     // If this is a variable index, we don't know which element it overwrites.
1493     // demand exactly the same input as we produce.
1494     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1495     if (Idx == 0) {
1496       // Note that we can't propagate undef elt info, because we don't know
1497       // which elt is getting updated.
1498       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1499                                         UndefElts2, Depth+1);
1500       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1501       break;
1502     }
1503     
1504     // If this is inserting an element that isn't demanded, remove this
1505     // insertelement.
1506     unsigned IdxNo = Idx->getZExtValue();
1507     if (IdxNo >= VWidth || !DemandedElts[IdxNo])
1508       return AddSoonDeadInstToWorklist(*I, 0);
1509     
1510     // Otherwise, the element inserted overwrites whatever was there, so the
1511     // input demanded set is simpler than the output set.
1512     APInt DemandedElts2 = DemandedElts;
1513     DemandedElts2.clear(IdxNo);
1514     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1515                                       UndefElts, Depth+1);
1516     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1517
1518     // The inserted element is defined.
1519     UndefElts.clear(IdxNo);
1520     break;
1521   }
1522   case Instruction::ShuffleVector: {
1523     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1524     uint64_t LHSVWidth =
1525       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1526     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1527     for (unsigned i = 0; i < VWidth; i++) {
1528       if (DemandedElts[i]) {
1529         unsigned MaskVal = Shuffle->getMaskValue(i);
1530         if (MaskVal != -1u) {
1531           assert(MaskVal < LHSVWidth * 2 &&
1532                  "shufflevector mask index out of range!");
1533           if (MaskVal < LHSVWidth)
1534             LeftDemanded.set(MaskVal);
1535           else
1536             RightDemanded.set(MaskVal - LHSVWidth);
1537         }
1538       }
1539     }
1540
1541     APInt UndefElts4(LHSVWidth, 0);
1542     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1543                                       UndefElts4, Depth+1);
1544     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1545
1546     APInt UndefElts3(LHSVWidth, 0);
1547     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1548                                       UndefElts3, Depth+1);
1549     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1550
1551     bool NewUndefElts = false;
1552     for (unsigned i = 0; i < VWidth; i++) {
1553       unsigned MaskVal = Shuffle->getMaskValue(i);
1554       if (MaskVal == -1u) {
1555         UndefElts.set(i);
1556       } else if (MaskVal < LHSVWidth) {
1557         if (UndefElts4[MaskVal]) {
1558           NewUndefElts = true;
1559           UndefElts.set(i);
1560         }
1561       } else {
1562         if (UndefElts3[MaskVal - LHSVWidth]) {
1563           NewUndefElts = true;
1564           UndefElts.set(i);
1565         }
1566       }
1567     }
1568
1569     if (NewUndefElts) {
1570       // Add additional discovered undefs.
1571       std::vector<Constant*> Elts;
1572       for (unsigned i = 0; i < VWidth; ++i) {
1573         if (UndefElts[i])
1574           Elts.push_back(UndefValue::get(Type::Int32Ty));
1575         else
1576           Elts.push_back(ConstantInt::get(Type::Int32Ty,
1577                                           Shuffle->getMaskValue(i)));
1578       }
1579       I->setOperand(2, ConstantVector::get(Elts));
1580       MadeChange = true;
1581     }
1582     break;
1583   }
1584   case Instruction::BitCast: {
1585     // Vector->vector casts only.
1586     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1587     if (!VTy) break;
1588     unsigned InVWidth = VTy->getNumElements();
1589     APInt InputDemandedElts(InVWidth, 0);
1590     unsigned Ratio;
1591
1592     if (VWidth == InVWidth) {
1593       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1594       // elements as are demanded of us.
1595       Ratio = 1;
1596       InputDemandedElts = DemandedElts;
1597     } else if (VWidth > InVWidth) {
1598       // Untested so far.
1599       break;
1600       
1601       // If there are more elements in the result than there are in the source,
1602       // then an input element is live if any of the corresponding output
1603       // elements are live.
1604       Ratio = VWidth/InVWidth;
1605       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1606         if (DemandedElts[OutIdx])
1607           InputDemandedElts.set(OutIdx/Ratio);
1608       }
1609     } else {
1610       // Untested so far.
1611       break;
1612       
1613       // If there are more elements in the source than there are in the result,
1614       // then an input element is live if the corresponding output element is
1615       // live.
1616       Ratio = InVWidth/VWidth;
1617       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1618         if (DemandedElts[InIdx/Ratio])
1619           InputDemandedElts.set(InIdx);
1620     }
1621     
1622     // div/rem demand all inputs, because they don't want divide by zero.
1623     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1624                                       UndefElts2, Depth+1);
1625     if (TmpV) {
1626       I->setOperand(0, TmpV);
1627       MadeChange = true;
1628     }
1629     
1630     UndefElts = UndefElts2;
1631     if (VWidth > InVWidth) {
1632       assert(0 && "Unimp");
1633       // If there are more elements in the result than there are in the source,
1634       // then an output element is undef if the corresponding input element is
1635       // undef.
1636       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1637         if (UndefElts2[OutIdx/Ratio])
1638           UndefElts.set(OutIdx);
1639     } else if (VWidth < InVWidth) {
1640       assert(0 && "Unimp");
1641       // If there are more elements in the source than there are in the result,
1642       // then a result element is undef if all of the corresponding input
1643       // elements are undef.
1644       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1645       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1646         if (!UndefElts2[InIdx])            // Not undef?
1647           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1648     }
1649     break;
1650   }
1651   case Instruction::And:
1652   case Instruction::Or:
1653   case Instruction::Xor:
1654   case Instruction::Add:
1655   case Instruction::Sub:
1656   case Instruction::Mul:
1657     // div/rem demand all inputs, because they don't want divide by zero.
1658     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1659                                       UndefElts, Depth+1);
1660     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1661     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1662                                       UndefElts2, Depth+1);
1663     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1664       
1665     // Output elements are undefined if both are undefined.  Consider things
1666     // like undef&0.  The result is known zero, not undef.
1667     UndefElts &= UndefElts2;
1668     break;
1669     
1670   case Instruction::Call: {
1671     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1672     if (!II) break;
1673     switch (II->getIntrinsicID()) {
1674     default: break;
1675       
1676     // Binary vector operations that work column-wise.  A dest element is a
1677     // function of the corresponding input elements from the two inputs.
1678     case Intrinsic::x86_sse_sub_ss:
1679     case Intrinsic::x86_sse_mul_ss:
1680     case Intrinsic::x86_sse_min_ss:
1681     case Intrinsic::x86_sse_max_ss:
1682     case Intrinsic::x86_sse2_sub_sd:
1683     case Intrinsic::x86_sse2_mul_sd:
1684     case Intrinsic::x86_sse2_min_sd:
1685     case Intrinsic::x86_sse2_max_sd:
1686       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1687                                         UndefElts, Depth+1);
1688       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1689       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1690                                         UndefElts2, Depth+1);
1691       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1692
1693       // If only the low elt is demanded and this is a scalarizable intrinsic,
1694       // scalarize it now.
1695       if (DemandedElts == 1) {
1696         switch (II->getIntrinsicID()) {
1697         default: break;
1698         case Intrinsic::x86_sse_sub_ss:
1699         case Intrinsic::x86_sse_mul_ss:
1700         case Intrinsic::x86_sse2_sub_sd:
1701         case Intrinsic::x86_sse2_mul_sd:
1702           // TODO: Lower MIN/MAX/ABS/etc
1703           Value *LHS = II->getOperand(1);
1704           Value *RHS = II->getOperand(2);
1705           // Extract the element as scalars.
1706           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1707           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1708           
1709           switch (II->getIntrinsicID()) {
1710           default: assert(0 && "Case stmts out of sync!");
1711           case Intrinsic::x86_sse_sub_ss:
1712           case Intrinsic::x86_sse2_sub_sd:
1713             TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
1714                                                         II->getName()), *II);
1715             break;
1716           case Intrinsic::x86_sse_mul_ss:
1717           case Intrinsic::x86_sse2_mul_sd:
1718             TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
1719                                                          II->getName()), *II);
1720             break;
1721           }
1722           
1723           Instruction *New =
1724             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1725                                       II->getName());
1726           InsertNewInstBefore(New, *II);
1727           AddSoonDeadInstToWorklist(*II, 0);
1728           return New;
1729         }            
1730       }
1731         
1732       // Output elements are undefined if both are undefined.  Consider things
1733       // like undef&0.  The result is known zero, not undef.
1734       UndefElts &= UndefElts2;
1735       break;
1736     }
1737     break;
1738   }
1739   }
1740   return MadeChange ? I : 0;
1741 }
1742
1743
1744 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1745 /// function is designed to check a chain of associative operators for a
1746 /// potential to apply a certain optimization.  Since the optimization may be
1747 /// applicable if the expression was reassociated, this checks the chain, then
1748 /// reassociates the expression as necessary to expose the optimization
1749 /// opportunity.  This makes use of a special Functor, which must define
1750 /// 'shouldApply' and 'apply' methods.
1751 ///
1752 template<typename Functor>
1753 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1754   unsigned Opcode = Root.getOpcode();
1755   Value *LHS = Root.getOperand(0);
1756
1757   // Quick check, see if the immediate LHS matches...
1758   if (F.shouldApply(LHS))
1759     return F.apply(Root);
1760
1761   // Otherwise, if the LHS is not of the same opcode as the root, return.
1762   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1763   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1764     // Should we apply this transform to the RHS?
1765     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1766
1767     // If not to the RHS, check to see if we should apply to the LHS...
1768     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1769       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1770       ShouldApply = true;
1771     }
1772
1773     // If the functor wants to apply the optimization to the RHS of LHSI,
1774     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1775     if (ShouldApply) {
1776       // Now all of the instructions are in the current basic block, go ahead
1777       // and perform the reassociation.
1778       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1779
1780       // First move the selected RHS to the LHS of the root...
1781       Root.setOperand(0, LHSI->getOperand(1));
1782
1783       // Make what used to be the LHS of the root be the user of the root...
1784       Value *ExtraOperand = TmpLHSI->getOperand(1);
1785       if (&Root == TmpLHSI) {
1786         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1787         return 0;
1788       }
1789       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1790       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1791       BasicBlock::iterator ARI = &Root; ++ARI;
1792       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1793       ARI = Root;
1794
1795       // Now propagate the ExtraOperand down the chain of instructions until we
1796       // get to LHSI.
1797       while (TmpLHSI != LHSI) {
1798         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1799         // Move the instruction to immediately before the chain we are
1800         // constructing to avoid breaking dominance properties.
1801         NextLHSI->moveBefore(ARI);
1802         ARI = NextLHSI;
1803
1804         Value *NextOp = NextLHSI->getOperand(1);
1805         NextLHSI->setOperand(1, ExtraOperand);
1806         TmpLHSI = NextLHSI;
1807         ExtraOperand = NextOp;
1808       }
1809
1810       // Now that the instructions are reassociated, have the functor perform
1811       // the transformation...
1812       return F.apply(Root);
1813     }
1814
1815     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1816   }
1817   return 0;
1818 }
1819
1820 namespace {
1821
1822 // AddRHS - Implements: X + X --> X << 1
1823 struct AddRHS {
1824   Value *RHS;
1825   AddRHS(Value *rhs) : RHS(rhs) {}
1826   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1827   Instruction *apply(BinaryOperator &Add) const {
1828     return BinaryOperator::CreateShl(Add.getOperand(0),
1829                                      ConstantInt::get(Add.getType(), 1));
1830   }
1831 };
1832
1833 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1834 //                 iff C1&C2 == 0
1835 struct AddMaskingAnd {
1836   Constant *C2;
1837   AddMaskingAnd(Constant *c) : C2(c) {}
1838   bool shouldApply(Value *LHS) const {
1839     ConstantInt *C1;
1840     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1841            ConstantExpr::getAnd(C1, C2)->isNullValue();
1842   }
1843   Instruction *apply(BinaryOperator &Add) const {
1844     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1845   }
1846 };
1847
1848 }
1849
1850 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1851                                              InstCombiner *IC) {
1852   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1853     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1854   }
1855
1856   // Figure out if the constant is the left or the right argument.
1857   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1858   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1859
1860   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1861     if (ConstIsRHS)
1862       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1863     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1864   }
1865
1866   Value *Op0 = SO, *Op1 = ConstOperand;
1867   if (!ConstIsRHS)
1868     std::swap(Op0, Op1);
1869   Instruction *New;
1870   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1871     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1872   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1873     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1874                           SO->getName()+".cmp");
1875   else {
1876     assert(0 && "Unknown binary instruction type!");
1877     abort();
1878   }
1879   return IC->InsertNewInstBefore(New, I);
1880 }
1881
1882 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1883 // constant as the other operand, try to fold the binary operator into the
1884 // select arguments.  This also works for Cast instructions, which obviously do
1885 // not have a second operand.
1886 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1887                                      InstCombiner *IC) {
1888   // Don't modify shared select instructions
1889   if (!SI->hasOneUse()) return 0;
1890   Value *TV = SI->getOperand(1);
1891   Value *FV = SI->getOperand(2);
1892
1893   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1894     // Bool selects with constant operands can be folded to logical ops.
1895     if (SI->getType() == Type::Int1Ty) return 0;
1896
1897     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1898     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1899
1900     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1901                               SelectFalseVal);
1902   }
1903   return 0;
1904 }
1905
1906
1907 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1908 /// node as operand #0, see if we can fold the instruction into the PHI (which
1909 /// is only possible if all operands to the PHI are constants).
1910 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1911   PHINode *PN = cast<PHINode>(I.getOperand(0));
1912   unsigned NumPHIValues = PN->getNumIncomingValues();
1913   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1914
1915   // Check to see if all of the operands of the PHI are constants.  If there is
1916   // one non-constant value, remember the BB it is.  If there is more than one
1917   // or if *it* is a PHI, bail out.
1918   BasicBlock *NonConstBB = 0;
1919   for (unsigned i = 0; i != NumPHIValues; ++i)
1920     if (!isa<Constant>(PN->getIncomingValue(i))) {
1921       if (NonConstBB) return 0;  // More than one non-const value.
1922       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1923       NonConstBB = PN->getIncomingBlock(i);
1924       
1925       // If the incoming non-constant value is in I's block, we have an infinite
1926       // loop.
1927       if (NonConstBB == I.getParent())
1928         return 0;
1929     }
1930   
1931   // If there is exactly one non-constant value, we can insert a copy of the
1932   // operation in that block.  However, if this is a critical edge, we would be
1933   // inserting the computation one some other paths (e.g. inside a loop).  Only
1934   // do this if the pred block is unconditionally branching into the phi block.
1935   if (NonConstBB) {
1936     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1937     if (!BI || !BI->isUnconditional()) return 0;
1938   }
1939
1940   // Okay, we can do the transformation: create the new PHI node.
1941   PHINode *NewPN = PHINode::Create(I.getType(), "");
1942   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1943   InsertNewInstBefore(NewPN, *PN);
1944   NewPN->takeName(PN);
1945
1946   // Next, add all of the operands to the PHI.
1947   if (I.getNumOperands() == 2) {
1948     Constant *C = cast<Constant>(I.getOperand(1));
1949     for (unsigned i = 0; i != NumPHIValues; ++i) {
1950       Value *InV = 0;
1951       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1952         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1953           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1954         else
1955           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1956       } else {
1957         assert(PN->getIncomingBlock(i) == NonConstBB);
1958         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1959           InV = BinaryOperator::Create(BO->getOpcode(),
1960                                        PN->getIncomingValue(i), C, "phitmp",
1961                                        NonConstBB->getTerminator());
1962         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1963           InV = CmpInst::Create(CI->getOpcode(), 
1964                                 CI->getPredicate(),
1965                                 PN->getIncomingValue(i), C, "phitmp",
1966                                 NonConstBB->getTerminator());
1967         else
1968           assert(0 && "Unknown binop!");
1969         
1970         AddToWorkList(cast<Instruction>(InV));
1971       }
1972       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1973     }
1974   } else { 
1975     CastInst *CI = cast<CastInst>(&I);
1976     const Type *RetTy = CI->getType();
1977     for (unsigned i = 0; i != NumPHIValues; ++i) {
1978       Value *InV;
1979       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1980         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1981       } else {
1982         assert(PN->getIncomingBlock(i) == NonConstBB);
1983         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
1984                                I.getType(), "phitmp", 
1985                                NonConstBB->getTerminator());
1986         AddToWorkList(cast<Instruction>(InV));
1987       }
1988       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1989     }
1990   }
1991   return ReplaceInstUsesWith(I, NewPN);
1992 }
1993
1994
1995 /// WillNotOverflowSignedAdd - Return true if we can prove that:
1996 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
1997 /// This basically requires proving that the add in the original type would not
1998 /// overflow to change the sign bit or have a carry out.
1999 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2000   // There are different heuristics we can use for this.  Here are some simple
2001   // ones.
2002   
2003   // Add has the property that adding any two 2's complement numbers can only 
2004   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2005   // have at least two sign bits, we know that the addition of the two values will
2006   // sign extend fine.
2007   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2008     return true;
2009   
2010   
2011   // If one of the operands only has one non-zero bit, and if the other operand
2012   // has a known-zero bit in a more significant place than it (not including the
2013   // sign bit) the ripple may go up to and fill the zero, but won't change the
2014   // sign.  For example, (X & ~4) + 1.
2015   
2016   // TODO: Implement.
2017   
2018   return false;
2019 }
2020
2021
2022 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2023   bool Changed = SimplifyCommutative(I);
2024   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2025
2026   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2027     // X + undef -> undef
2028     if (isa<UndefValue>(RHS))
2029       return ReplaceInstUsesWith(I, RHS);
2030
2031     // X + 0 --> X
2032     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2033       if (RHSC->isNullValue())
2034         return ReplaceInstUsesWith(I, LHS);
2035     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2036       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2037                               (I.getType())->getValueAPF()))
2038         return ReplaceInstUsesWith(I, LHS);
2039     }
2040
2041     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2042       // X + (signbit) --> X ^ signbit
2043       const APInt& Val = CI->getValue();
2044       uint32_t BitWidth = Val.getBitWidth();
2045       if (Val == APInt::getSignBit(BitWidth))
2046         return BinaryOperator::CreateXor(LHS, RHS);
2047       
2048       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2049       // (X & 254)+1 -> (X&254)|1
2050       if (!isa<VectorType>(I.getType()) && SimplifyDemandedInstructionBits(I))
2051         return &I;
2052
2053       // zext(i1) - 1  ->  select i1, 0, -1
2054       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2055         if (CI->isAllOnesValue() &&
2056             ZI->getOperand(0)->getType() == Type::Int1Ty)
2057           return SelectInst::Create(ZI->getOperand(0),
2058                                     Constant::getNullValue(I.getType()),
2059                                     ConstantInt::getAllOnesValue(I.getType()));
2060     }
2061
2062     if (isa<PHINode>(LHS))
2063       if (Instruction *NV = FoldOpIntoPhi(I))
2064         return NV;
2065     
2066     ConstantInt *XorRHS = 0;
2067     Value *XorLHS = 0;
2068     if (isa<ConstantInt>(RHSC) &&
2069         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2070       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2071       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2072       
2073       uint32_t Size = TySizeBits / 2;
2074       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2075       APInt CFF80Val(-C0080Val);
2076       do {
2077         if (TySizeBits > Size) {
2078           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2079           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2080           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2081               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2082             // This is a sign extend if the top bits are known zero.
2083             if (!MaskedValueIsZero(XorLHS, 
2084                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2085               Size = 0;  // Not a sign ext, but can't be any others either.
2086             break;
2087           }
2088         }
2089         Size >>= 1;
2090         C0080Val = APIntOps::lshr(C0080Val, Size);
2091         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2092       } while (Size >= 1);
2093       
2094       // FIXME: This shouldn't be necessary. When the backends can handle types
2095       // with funny bit widths then this switch statement should be removed. It
2096       // is just here to get the size of the "middle" type back up to something
2097       // that the back ends can handle.
2098       const Type *MiddleType = 0;
2099       switch (Size) {
2100         default: break;
2101         case 32: MiddleType = Type::Int32Ty; break;
2102         case 16: MiddleType = Type::Int16Ty; break;
2103         case  8: MiddleType = Type::Int8Ty; break;
2104       }
2105       if (MiddleType) {
2106         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2107         InsertNewInstBefore(NewTrunc, I);
2108         return new SExtInst(NewTrunc, I.getType(), I.getName());
2109       }
2110     }
2111   }
2112
2113   if (I.getType() == Type::Int1Ty)
2114     return BinaryOperator::CreateXor(LHS, RHS);
2115
2116   // X + X --> X << 1
2117   if (I.getType()->isInteger()) {
2118     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2119
2120     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2121       if (RHSI->getOpcode() == Instruction::Sub)
2122         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2123           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2124     }
2125     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2126       if (LHSI->getOpcode() == Instruction::Sub)
2127         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2128           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2129     }
2130   }
2131
2132   // -A + B  -->  B - A
2133   // -A + -B  -->  -(A + B)
2134   if (Value *LHSV = dyn_castNegVal(LHS)) {
2135     if (LHS->getType()->isIntOrIntVector()) {
2136       if (Value *RHSV = dyn_castNegVal(RHS)) {
2137         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2138         InsertNewInstBefore(NewAdd, I);
2139         return BinaryOperator::CreateNeg(NewAdd);
2140       }
2141     }
2142     
2143     return BinaryOperator::CreateSub(RHS, LHSV);
2144   }
2145
2146   // A + -B  -->  A - B
2147   if (!isa<Constant>(RHS))
2148     if (Value *V = dyn_castNegVal(RHS))
2149       return BinaryOperator::CreateSub(LHS, V);
2150
2151
2152   ConstantInt *C2;
2153   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2154     if (X == RHS)   // X*C + X --> X * (C+1)
2155       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2156
2157     // X*C1 + X*C2 --> X * (C1+C2)
2158     ConstantInt *C1;
2159     if (X == dyn_castFoldableMul(RHS, C1))
2160       return BinaryOperator::CreateMul(X, Add(C1, C2));
2161   }
2162
2163   // X + X*C --> X * (C+1)
2164   if (dyn_castFoldableMul(RHS, C2) == LHS)
2165     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2166
2167   // X + ~X --> -1   since   ~X = -X-1
2168   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2169     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2170   
2171
2172   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2173   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2174     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2175       return R;
2176   
2177   // A+B --> A|B iff A and B have no bits set in common.
2178   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2179     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2180     APInt LHSKnownOne(IT->getBitWidth(), 0);
2181     APInt LHSKnownZero(IT->getBitWidth(), 0);
2182     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2183     if (LHSKnownZero != 0) {
2184       APInt RHSKnownOne(IT->getBitWidth(), 0);
2185       APInt RHSKnownZero(IT->getBitWidth(), 0);
2186       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2187       
2188       // No bits in common -> bitwise or.
2189       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2190         return BinaryOperator::CreateOr(LHS, RHS);
2191     }
2192   }
2193
2194   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2195   if (I.getType()->isIntOrIntVector()) {
2196     Value *W, *X, *Y, *Z;
2197     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2198         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2199       if (W != Y) {
2200         if (W == Z) {
2201           std::swap(Y, Z);
2202         } else if (Y == X) {
2203           std::swap(W, X);
2204         } else if (X == Z) {
2205           std::swap(Y, Z);
2206           std::swap(W, X);
2207         }
2208       }
2209
2210       if (W == Y) {
2211         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2212                                                             LHS->getName()), I);
2213         return BinaryOperator::CreateMul(W, NewAdd);
2214       }
2215     }
2216   }
2217
2218   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2219     Value *X = 0;
2220     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2221       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2222
2223     // (X & FF00) + xx00  -> (X+xx00) & FF00
2224     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2225       Constant *Anded = And(CRHS, C2);
2226       if (Anded == CRHS) {
2227         // See if all bits from the first bit set in the Add RHS up are included
2228         // in the mask.  First, get the rightmost bit.
2229         const APInt& AddRHSV = CRHS->getValue();
2230
2231         // Form a mask of all bits from the lowest bit added through the top.
2232         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2233
2234         // See if the and mask includes all of these bits.
2235         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2236
2237         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2238           // Okay, the xform is safe.  Insert the new add pronto.
2239           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2240                                                             LHS->getName()), I);
2241           return BinaryOperator::CreateAnd(NewAdd, C2);
2242         }
2243       }
2244     }
2245
2246     // Try to fold constant add into select arguments.
2247     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2248       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2249         return R;
2250   }
2251
2252   // add (cast *A to intptrtype) B -> 
2253   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2254   {
2255     CastInst *CI = dyn_cast<CastInst>(LHS);
2256     Value *Other = RHS;
2257     if (!CI) {
2258       CI = dyn_cast<CastInst>(RHS);
2259       Other = LHS;
2260     }
2261     if (CI && CI->getType()->isSized() && 
2262         (CI->getType()->getPrimitiveSizeInBits() == 
2263          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2264         && isa<PointerType>(CI->getOperand(0)->getType())) {
2265       unsigned AS =
2266         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2267       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2268                                       PointerType::get(Type::Int8Ty, AS), I);
2269       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2270       return new PtrToIntInst(I2, CI->getType());
2271     }
2272   }
2273   
2274   // add (select X 0 (sub n A)) A  -->  select X A n
2275   {
2276     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2277     Value *A = RHS;
2278     if (!SI) {
2279       SI = dyn_cast<SelectInst>(RHS);
2280       A = LHS;
2281     }
2282     if (SI && SI->hasOneUse()) {
2283       Value *TV = SI->getTrueValue();
2284       Value *FV = SI->getFalseValue();
2285       Value *N;
2286
2287       // Can we fold the add into the argument of the select?
2288       // We check both true and false select arguments for a matching subtract.
2289       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2290         // Fold the add into the true select value.
2291         return SelectInst::Create(SI->getCondition(), N, A);
2292       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2293         // Fold the add into the false select value.
2294         return SelectInst::Create(SI->getCondition(), A, N);
2295     }
2296   }
2297   
2298   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2299   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2300     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2301       return ReplaceInstUsesWith(I, LHS);
2302
2303   // Check for (add (sext x), y), see if we can merge this into an
2304   // integer add followed by a sext.
2305   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2306     // (add (sext x), cst) --> (sext (add x, cst'))
2307     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2308       Constant *CI = 
2309         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2310       if (LHSConv->hasOneUse() &&
2311           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2312           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2313         // Insert the new, smaller add.
2314         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2315                                                         CI, "addconv");
2316         InsertNewInstBefore(NewAdd, I);
2317         return new SExtInst(NewAdd, I.getType());
2318       }
2319     }
2320     
2321     // (add (sext x), (sext y)) --> (sext (add int x, y))
2322     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2323       // Only do this if x/y have the same type, if at last one of them has a
2324       // single use (so we don't increase the number of sexts), and if the
2325       // integer add will not overflow.
2326       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2327           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2328           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2329                                    RHSConv->getOperand(0))) {
2330         // Insert the new integer add.
2331         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2332                                                         RHSConv->getOperand(0),
2333                                                         "addconv");
2334         InsertNewInstBefore(NewAdd, I);
2335         return new SExtInst(NewAdd, I.getType());
2336       }
2337     }
2338   }
2339   
2340   // Check for (add double (sitofp x), y), see if we can merge this into an
2341   // integer add followed by a promotion.
2342   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2343     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2344     // ... if the constant fits in the integer value.  This is useful for things
2345     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2346     // requires a constant pool load, and generally allows the add to be better
2347     // instcombined.
2348     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2349       Constant *CI = 
2350       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2351       if (LHSConv->hasOneUse() &&
2352           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2353           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2354         // Insert the new integer add.
2355         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2356                                                         CI, "addconv");
2357         InsertNewInstBefore(NewAdd, I);
2358         return new SIToFPInst(NewAdd, I.getType());
2359       }
2360     }
2361     
2362     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2363     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2364       // Only do this if x/y have the same type, if at last one of them has a
2365       // single use (so we don't increase the number of int->fp conversions),
2366       // and if the integer add will not overflow.
2367       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2368           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2369           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2370                                    RHSConv->getOperand(0))) {
2371         // Insert the new integer add.
2372         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2373                                                         RHSConv->getOperand(0),
2374                                                         "addconv");
2375         InsertNewInstBefore(NewAdd, I);
2376         return new SIToFPInst(NewAdd, I.getType());
2377       }
2378     }
2379   }
2380   
2381   return Changed ? &I : 0;
2382 }
2383
2384 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2385   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2386
2387   if (Op0 == Op1 &&                        // sub X, X  -> 0
2388       !I.getType()->isFPOrFPVector())
2389     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2390
2391   // If this is a 'B = x-(-A)', change to B = x+A...
2392   if (Value *V = dyn_castNegVal(Op1))
2393     return BinaryOperator::CreateAdd(Op0, V);
2394
2395   if (isa<UndefValue>(Op0))
2396     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2397   if (isa<UndefValue>(Op1))
2398     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2399
2400   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2401     // Replace (-1 - A) with (~A)...
2402     if (C->isAllOnesValue())
2403       return BinaryOperator::CreateNot(Op1);
2404
2405     // C - ~X == X + (1+C)
2406     Value *X = 0;
2407     if (match(Op1, m_Not(m_Value(X))))
2408       return BinaryOperator::CreateAdd(X, AddOne(C));
2409
2410     // -(X >>u 31) -> (X >>s 31)
2411     // -(X >>s 31) -> (X >>u 31)
2412     if (C->isZero()) {
2413       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2414         if (SI->getOpcode() == Instruction::LShr) {
2415           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2416             // Check to see if we are shifting out everything but the sign bit.
2417             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2418                 SI->getType()->getPrimitiveSizeInBits()-1) {
2419               // Ok, the transformation is safe.  Insert AShr.
2420               return BinaryOperator::Create(Instruction::AShr, 
2421                                           SI->getOperand(0), CU, SI->getName());
2422             }
2423           }
2424         }
2425         else if (SI->getOpcode() == Instruction::AShr) {
2426           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2427             // Check to see if we are shifting out everything but the sign bit.
2428             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2429                 SI->getType()->getPrimitiveSizeInBits()-1) {
2430               // Ok, the transformation is safe.  Insert LShr. 
2431               return BinaryOperator::CreateLShr(
2432                                           SI->getOperand(0), CU, SI->getName());
2433             }
2434           }
2435         }
2436       }
2437     }
2438
2439     // Try to fold constant sub into select arguments.
2440     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2441       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2442         return R;
2443   }
2444
2445   if (I.getType() == Type::Int1Ty)
2446     return BinaryOperator::CreateXor(Op0, Op1);
2447
2448   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2449     if (Op1I->getOpcode() == Instruction::Add &&
2450         !Op0->getType()->isFPOrFPVector()) {
2451       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2452         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2453       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2454         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2455       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2456         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2457           // C1-(X+C2) --> (C1-C2)-X
2458           return BinaryOperator::CreateSub(Subtract(CI1, CI2), 
2459                                            Op1I->getOperand(0));
2460       }
2461     }
2462
2463     if (Op1I->hasOneUse()) {
2464       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2465       // is not used by anyone else...
2466       //
2467       if (Op1I->getOpcode() == Instruction::Sub &&
2468           !Op1I->getType()->isFPOrFPVector()) {
2469         // Swap the two operands of the subexpr...
2470         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2471         Op1I->setOperand(0, IIOp1);
2472         Op1I->setOperand(1, IIOp0);
2473
2474         // Create the new top level add instruction...
2475         return BinaryOperator::CreateAdd(Op0, Op1);
2476       }
2477
2478       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2479       //
2480       if (Op1I->getOpcode() == Instruction::And &&
2481           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2482         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2483
2484         Value *NewNot =
2485           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2486         return BinaryOperator::CreateAnd(Op0, NewNot);
2487       }
2488
2489       // 0 - (X sdiv C)  -> (X sdiv -C)
2490       if (Op1I->getOpcode() == Instruction::SDiv)
2491         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2492           if (CSI->isZero())
2493             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2494               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2495                                                ConstantExpr::getNeg(DivRHS));
2496
2497       // X - X*C --> X * (1-C)
2498       ConstantInt *C2 = 0;
2499       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2500         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2501         return BinaryOperator::CreateMul(Op0, CP1);
2502       }
2503     }
2504   }
2505
2506   if (!Op0->getType()->isFPOrFPVector())
2507     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2508       if (Op0I->getOpcode() == Instruction::Add) {
2509         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2510           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2511         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2512           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2513       } else if (Op0I->getOpcode() == Instruction::Sub) {
2514         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2515           return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2516       }
2517     }
2518
2519   ConstantInt *C1;
2520   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2521     if (X == Op1)  // X*C - X --> X * (C-1)
2522       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2523
2524     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2525     if (X == dyn_castFoldableMul(Op1, C2))
2526       return BinaryOperator::CreateMul(X, Subtract(C1, C2));
2527   }
2528   return 0;
2529 }
2530
2531 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2532 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2533 /// TrueIfSigned if the result of the comparison is true when the input value is
2534 /// signed.
2535 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2536                            bool &TrueIfSigned) {
2537   switch (pred) {
2538   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2539     TrueIfSigned = true;
2540     return RHS->isZero();
2541   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2542     TrueIfSigned = true;
2543     return RHS->isAllOnesValue();
2544   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2545     TrueIfSigned = false;
2546     return RHS->isAllOnesValue();
2547   case ICmpInst::ICMP_UGT:
2548     // True if LHS u> RHS and RHS == high-bit-mask - 1
2549     TrueIfSigned = true;
2550     return RHS->getValue() ==
2551       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2552   case ICmpInst::ICMP_UGE: 
2553     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2554     TrueIfSigned = true;
2555     return RHS->getValue().isSignBit();
2556   default:
2557     return false;
2558   }
2559 }
2560
2561 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2562   bool Changed = SimplifyCommutative(I);
2563   Value *Op0 = I.getOperand(0);
2564
2565   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2566     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2567
2568   // Simplify mul instructions with a constant RHS...
2569   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2570     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2571
2572       // ((X << C1)*C2) == (X * (C2 << C1))
2573       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2574         if (SI->getOpcode() == Instruction::Shl)
2575           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2576             return BinaryOperator::CreateMul(SI->getOperand(0),
2577                                              ConstantExpr::getShl(CI, ShOp));
2578
2579       if (CI->isZero())
2580         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2581       if (CI->equalsInt(1))                  // X * 1  == X
2582         return ReplaceInstUsesWith(I, Op0);
2583       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2584         return BinaryOperator::CreateNeg(Op0, I.getName());
2585
2586       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2587       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2588         return BinaryOperator::CreateShl(Op0,
2589                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2590       }
2591     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2592       if (Op1F->isNullValue())
2593         return ReplaceInstUsesWith(I, Op1);
2594
2595       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2596       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2597       if (Op1F->isExactlyValue(1.0))
2598         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2599     } else if (isa<VectorType>(Op1->getType())) {
2600       if (isa<ConstantAggregateZero>(Op1))
2601         return ReplaceInstUsesWith(I, Op1);
2602
2603       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2604         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2605           return BinaryOperator::CreateNeg(Op0, I.getName());
2606
2607         // As above, vector X*splat(1.0) -> X in all defined cases.
2608         if (Constant *Splat = Op1V->getSplatValue()) {
2609           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2610             if (F->isExactlyValue(1.0))
2611               return ReplaceInstUsesWith(I, Op0);
2612           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2613             if (CI->equalsInt(1))
2614               return ReplaceInstUsesWith(I, Op0);
2615         }
2616       }
2617     }
2618     
2619     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2620       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2621           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2622         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2623         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2624                                                      Op1, "tmp");
2625         InsertNewInstBefore(Add, I);
2626         Value *C1C2 = ConstantExpr::getMul(Op1, 
2627                                            cast<Constant>(Op0I->getOperand(1)));
2628         return BinaryOperator::CreateAdd(Add, C1C2);
2629         
2630       }
2631
2632     // Try to fold constant mul into select arguments.
2633     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2634       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2635         return R;
2636
2637     if (isa<PHINode>(Op0))
2638       if (Instruction *NV = FoldOpIntoPhi(I))
2639         return NV;
2640   }
2641
2642   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2643     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2644       return BinaryOperator::CreateMul(Op0v, Op1v);
2645
2646   // (X / Y) *  Y = X - (X % Y)
2647   // (X / Y) * -Y = (X % Y) - X
2648   {
2649     Value *Op1 = I.getOperand(1);
2650     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2651     if (!BO ||
2652         (BO->getOpcode() != Instruction::UDiv && 
2653          BO->getOpcode() != Instruction::SDiv)) {
2654       Op1 = Op0;
2655       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2656     }
2657     Value *Neg = dyn_castNegVal(Op1);
2658     if (BO && BO->hasOneUse() &&
2659         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2660         (BO->getOpcode() == Instruction::UDiv ||
2661          BO->getOpcode() == Instruction::SDiv)) {
2662       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2663
2664       Instruction *Rem;
2665       if (BO->getOpcode() == Instruction::UDiv)
2666         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2667       else
2668         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2669
2670       InsertNewInstBefore(Rem, I);
2671       Rem->takeName(BO);
2672
2673       if (Op1BO == Op1)
2674         return BinaryOperator::CreateSub(Op0BO, Rem);
2675       else
2676         return BinaryOperator::CreateSub(Rem, Op0BO);
2677     }
2678   }
2679
2680   if (I.getType() == Type::Int1Ty)
2681     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2682
2683   // If one of the operands of the multiply is a cast from a boolean value, then
2684   // we know the bool is either zero or one, so this is a 'masking' multiply.
2685   // See if we can simplify things based on how the boolean was originally
2686   // formed.
2687   CastInst *BoolCast = 0;
2688   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2689     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2690       BoolCast = CI;
2691   if (!BoolCast)
2692     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2693       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2694         BoolCast = CI;
2695   if (BoolCast) {
2696     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2697       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2698       const Type *SCOpTy = SCIOp0->getType();
2699       bool TIS = false;
2700       
2701       // If the icmp is true iff the sign bit of X is set, then convert this
2702       // multiply into a shift/and combination.
2703       if (isa<ConstantInt>(SCIOp1) &&
2704           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2705           TIS) {
2706         // Shift the X value right to turn it into "all signbits".
2707         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2708                                           SCOpTy->getPrimitiveSizeInBits()-1);
2709         Value *V =
2710           InsertNewInstBefore(
2711             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2712                                             BoolCast->getOperand(0)->getName()+
2713                                             ".mask"), I);
2714
2715         // If the multiply type is not the same as the source type, sign extend
2716         // or truncate to the multiply type.
2717         if (I.getType() != V->getType()) {
2718           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2719           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2720           Instruction::CastOps opcode = 
2721             (SrcBits == DstBits ? Instruction::BitCast : 
2722              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2723           V = InsertCastBefore(opcode, V, I.getType(), I);
2724         }
2725
2726         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2727         return BinaryOperator::CreateAnd(V, OtherOp);
2728       }
2729     }
2730   }
2731
2732   return Changed ? &I : 0;
2733 }
2734
2735 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2736 /// instruction.
2737 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2738   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2739   
2740   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2741   int NonNullOperand = -1;
2742   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2743     if (ST->isNullValue())
2744       NonNullOperand = 2;
2745   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2746   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2747     if (ST->isNullValue())
2748       NonNullOperand = 1;
2749   
2750   if (NonNullOperand == -1)
2751     return false;
2752   
2753   Value *SelectCond = SI->getOperand(0);
2754   
2755   // Change the div/rem to use 'Y' instead of the select.
2756   I.setOperand(1, SI->getOperand(NonNullOperand));
2757   
2758   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2759   // problem.  However, the select, or the condition of the select may have
2760   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2761   // propagate the known value for the select into other uses of it, and
2762   // propagate a known value of the condition into its other users.
2763   
2764   // If the select and condition only have a single use, don't bother with this,
2765   // early exit.
2766   if (SI->use_empty() && SelectCond->hasOneUse())
2767     return true;
2768   
2769   // Scan the current block backward, looking for other uses of SI.
2770   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2771   
2772   while (BBI != BBFront) {
2773     --BBI;
2774     // If we found a call to a function, we can't assume it will return, so
2775     // information from below it cannot be propagated above it.
2776     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2777       break;
2778     
2779     // Replace uses of the select or its condition with the known values.
2780     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2781          I != E; ++I) {
2782       if (*I == SI) {
2783         *I = SI->getOperand(NonNullOperand);
2784         AddToWorkList(BBI);
2785       } else if (*I == SelectCond) {
2786         *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2787                                    ConstantInt::getFalse();
2788         AddToWorkList(BBI);
2789       }
2790     }
2791     
2792     // If we past the instruction, quit looking for it.
2793     if (&*BBI == SI)
2794       SI = 0;
2795     if (&*BBI == SelectCond)
2796       SelectCond = 0;
2797     
2798     // If we ran out of things to eliminate, break out of the loop.
2799     if (SelectCond == 0 && SI == 0)
2800       break;
2801     
2802   }
2803   return true;
2804 }
2805
2806
2807 /// This function implements the transforms on div instructions that work
2808 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2809 /// used by the visitors to those instructions.
2810 /// @brief Transforms common to all three div instructions
2811 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2812   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2813
2814   // undef / X -> 0        for integer.
2815   // undef / X -> undef    for FP (the undef could be a snan).
2816   if (isa<UndefValue>(Op0)) {
2817     if (Op0->getType()->isFPOrFPVector())
2818       return ReplaceInstUsesWith(I, Op0);
2819     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2820   }
2821
2822   // X / undef -> undef
2823   if (isa<UndefValue>(Op1))
2824     return ReplaceInstUsesWith(I, Op1);
2825
2826   return 0;
2827 }
2828
2829 /// This function implements the transforms common to both integer division
2830 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2831 /// division instructions.
2832 /// @brief Common integer divide transforms
2833 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2834   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2835
2836   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2837   if (Op0 == Op1) {
2838     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2839       ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2840       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2841       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2842     }
2843
2844     ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2845     return ReplaceInstUsesWith(I, CI);
2846   }
2847   
2848   if (Instruction *Common = commonDivTransforms(I))
2849     return Common;
2850   
2851   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2852   // This does not apply for fdiv.
2853   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2854     return &I;
2855
2856   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2857     // div X, 1 == X
2858     if (RHS->equalsInt(1))
2859       return ReplaceInstUsesWith(I, Op0);
2860
2861     // (X / C1) / C2  -> X / (C1*C2)
2862     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2863       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2864         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2865           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2866             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2867           else 
2868             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2869                                           Multiply(RHS, LHSRHS));
2870         }
2871
2872     if (!RHS->isZero()) { // avoid X udiv 0
2873       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2874         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2875           return R;
2876       if (isa<PHINode>(Op0))
2877         if (Instruction *NV = FoldOpIntoPhi(I))
2878           return NV;
2879     }
2880   }
2881
2882   // 0 / X == 0, we don't need to preserve faults!
2883   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2884     if (LHS->equalsInt(0))
2885       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2886
2887   // It can't be division by zero, hence it must be division by one.
2888   if (I.getType() == Type::Int1Ty)
2889     return ReplaceInstUsesWith(I, Op0);
2890
2891   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2892     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2893       // div X, 1 == X
2894       if (X->isOne())
2895         return ReplaceInstUsesWith(I, Op0);
2896   }
2897
2898   return 0;
2899 }
2900
2901 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2902   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2903
2904   // Handle the integer div common cases
2905   if (Instruction *Common = commonIDivTransforms(I))
2906     return Common;
2907
2908   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2909     // X udiv C^2 -> X >> C
2910     // Check to see if this is an unsigned division with an exact power of 2,
2911     // if so, convert to a right shift.
2912     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2913       return BinaryOperator::CreateLShr(Op0, 
2914                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2915
2916     // X udiv C, where C >= signbit
2917     if (C->getValue().isNegative()) {
2918       Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
2919                                       I);
2920       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
2921                                 ConstantInt::get(I.getType(), 1));
2922     }
2923   }
2924
2925   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2926   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2927     if (RHSI->getOpcode() == Instruction::Shl &&
2928         isa<ConstantInt>(RHSI->getOperand(0))) {
2929       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2930       if (C1.isPowerOf2()) {
2931         Value *N = RHSI->getOperand(1);
2932         const Type *NTy = N->getType();
2933         if (uint32_t C2 = C1.logBase2()) {
2934           Constant *C2V = ConstantInt::get(NTy, C2);
2935           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
2936         }
2937         return BinaryOperator::CreateLShr(Op0, N);
2938       }
2939     }
2940   }
2941   
2942   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2943   // where C1&C2 are powers of two.
2944   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2945     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2946       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2947         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2948         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2949           // Compute the shift amounts
2950           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2951           // Construct the "on true" case of the select
2952           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2953           Instruction *TSI = BinaryOperator::CreateLShr(
2954                                                  Op0, TC, SI->getName()+".t");
2955           TSI = InsertNewInstBefore(TSI, I);
2956   
2957           // Construct the "on false" case of the select
2958           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2959           Instruction *FSI = BinaryOperator::CreateLShr(
2960                                                  Op0, FC, SI->getName()+".f");
2961           FSI = InsertNewInstBefore(FSI, I);
2962
2963           // construct the select instruction and return it.
2964           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
2965         }
2966       }
2967   return 0;
2968 }
2969
2970 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2971   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2972
2973   // Handle the integer div common cases
2974   if (Instruction *Common = commonIDivTransforms(I))
2975     return Common;
2976
2977   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2978     // sdiv X, -1 == -X
2979     if (RHS->isAllOnesValue())
2980       return BinaryOperator::CreateNeg(Op0);
2981   }
2982
2983   // If the sign bits of both operands are zero (i.e. we can prove they are
2984   // unsigned inputs), turn this into a udiv.
2985   if (I.getType()->isInteger()) {
2986     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2987     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2988       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2989       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2990     }
2991   }      
2992   
2993   return 0;
2994 }
2995
2996 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2997   return commonDivTransforms(I);
2998 }
2999
3000 /// This function implements the transforms on rem instructions that work
3001 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3002 /// is used by the visitors to those instructions.
3003 /// @brief Transforms common to all three rem instructions
3004 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3005   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3006
3007   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3008     if (I.getType()->isFPOrFPVector())
3009       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3010     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3011   }
3012   if (isa<UndefValue>(Op1))
3013     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3014
3015   // Handle cases involving: rem X, (select Cond, Y, Z)
3016   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3017     return &I;
3018
3019   return 0;
3020 }
3021
3022 /// This function implements the transforms common to both integer remainder
3023 /// instructions (urem and srem). It is called by the visitors to those integer
3024 /// remainder instructions.
3025 /// @brief Common integer remainder transforms
3026 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3027   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3028
3029   if (Instruction *common = commonRemTransforms(I))
3030     return common;
3031
3032   // 0 % X == 0 for integer, we don't need to preserve faults!
3033   if (Constant *LHS = dyn_cast<Constant>(Op0))
3034     if (LHS->isNullValue())
3035       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3036
3037   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3038     // X % 0 == undef, we don't need to preserve faults!
3039     if (RHS->equalsInt(0))
3040       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3041     
3042     if (RHS->equalsInt(1))  // X % 1 == 0
3043       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3044
3045     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3046       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3047         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3048           return R;
3049       } else if (isa<PHINode>(Op0I)) {
3050         if (Instruction *NV = FoldOpIntoPhi(I))
3051           return NV;
3052       }
3053
3054       // See if we can fold away this rem instruction.
3055       if (SimplifyDemandedInstructionBits(I))
3056         return &I;
3057     }
3058   }
3059
3060   return 0;
3061 }
3062
3063 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3064   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3065
3066   if (Instruction *common = commonIRemTransforms(I))
3067     return common;
3068   
3069   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3070     // X urem C^2 -> X and C
3071     // Check to see if this is an unsigned remainder with an exact power of 2,
3072     // if so, convert to a bitwise and.
3073     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3074       if (C->getValue().isPowerOf2())
3075         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3076   }
3077
3078   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3079     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3080     if (RHSI->getOpcode() == Instruction::Shl &&
3081         isa<ConstantInt>(RHSI->getOperand(0))) {
3082       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3083         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3084         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3085                                                                    "tmp"), I);
3086         return BinaryOperator::CreateAnd(Op0, Add);
3087       }
3088     }
3089   }
3090
3091   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3092   // where C1&C2 are powers of two.
3093   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3094     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3095       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3096         // STO == 0 and SFO == 0 handled above.
3097         if ((STO->getValue().isPowerOf2()) && 
3098             (SFO->getValue().isPowerOf2())) {
3099           Value *TrueAnd = InsertNewInstBefore(
3100             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3101           Value *FalseAnd = InsertNewInstBefore(
3102             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3103           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3104         }
3105       }
3106   }
3107   
3108   return 0;
3109 }
3110
3111 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3112   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3113
3114   // Handle the integer rem common cases
3115   if (Instruction *common = commonIRemTransforms(I))
3116     return common;
3117   
3118   if (Value *RHSNeg = dyn_castNegVal(Op1))
3119     if (!isa<Constant>(RHSNeg) ||
3120         (isa<ConstantInt>(RHSNeg) &&
3121          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3122       // X % -Y -> X % Y
3123       AddUsesToWorkList(I);
3124       I.setOperand(1, RHSNeg);
3125       return &I;
3126     }
3127
3128   // If the sign bits of both operands are zero (i.e. we can prove they are
3129   // unsigned inputs), turn this into a urem.
3130   if (I.getType()->isInteger()) {
3131     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3132     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3133       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3134       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3135     }
3136   }
3137
3138   // If it's a constant vector, flip any negative values positive.
3139   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3140     unsigned VWidth = RHSV->getNumOperands();
3141
3142     bool hasNegative = false;
3143     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3144       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3145         if (RHS->getValue().isNegative())
3146           hasNegative = true;
3147
3148     if (hasNegative) {
3149       std::vector<Constant *> Elts(VWidth);
3150       for (unsigned i = 0; i != VWidth; ++i) {
3151         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3152           if (RHS->getValue().isNegative())
3153             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3154           else
3155             Elts[i] = RHS;
3156         }
3157       }
3158
3159       Constant *NewRHSV = ConstantVector::get(Elts);
3160       if (NewRHSV != RHSV) {
3161         AddUsesToWorkList(I);
3162         I.setOperand(1, NewRHSV);
3163         return &I;
3164       }
3165     }
3166   }
3167
3168   return 0;
3169 }
3170
3171 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3172   return commonRemTransforms(I);
3173 }
3174
3175 // isOneBitSet - Return true if there is exactly one bit set in the specified
3176 // constant.
3177 static bool isOneBitSet(const ConstantInt *CI) {
3178   return CI->getValue().isPowerOf2();
3179 }
3180
3181 // isHighOnes - Return true if the constant is of the form 1+0+.
3182 // This is the same as lowones(~X).
3183 static bool isHighOnes(const ConstantInt *CI) {
3184   return (~CI->getValue() + 1).isPowerOf2();
3185 }
3186
3187 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3188 /// are carefully arranged to allow folding of expressions such as:
3189 ///
3190 ///      (A < B) | (A > B) --> (A != B)
3191 ///
3192 /// Note that this is only valid if the first and second predicates have the
3193 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3194 ///
3195 /// Three bits are used to represent the condition, as follows:
3196 ///   0  A > B
3197 ///   1  A == B
3198 ///   2  A < B
3199 ///
3200 /// <=>  Value  Definition
3201 /// 000     0   Always false
3202 /// 001     1   A >  B
3203 /// 010     2   A == B
3204 /// 011     3   A >= B
3205 /// 100     4   A <  B
3206 /// 101     5   A != B
3207 /// 110     6   A <= B
3208 /// 111     7   Always true
3209 ///  
3210 static unsigned getICmpCode(const ICmpInst *ICI) {
3211   switch (ICI->getPredicate()) {
3212     // False -> 0
3213   case ICmpInst::ICMP_UGT: return 1;  // 001
3214   case ICmpInst::ICMP_SGT: return 1;  // 001
3215   case ICmpInst::ICMP_EQ:  return 2;  // 010
3216   case ICmpInst::ICMP_UGE: return 3;  // 011
3217   case ICmpInst::ICMP_SGE: return 3;  // 011
3218   case ICmpInst::ICMP_ULT: return 4;  // 100
3219   case ICmpInst::ICMP_SLT: return 4;  // 100
3220   case ICmpInst::ICMP_NE:  return 5;  // 101
3221   case ICmpInst::ICMP_ULE: return 6;  // 110
3222   case ICmpInst::ICMP_SLE: return 6;  // 110
3223     // True -> 7
3224   default:
3225     assert(0 && "Invalid ICmp predicate!");
3226     return 0;
3227   }
3228 }
3229
3230 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3231 /// predicate into a three bit mask. It also returns whether it is an ordered
3232 /// predicate by reference.
3233 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3234   isOrdered = false;
3235   switch (CC) {
3236   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3237   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3238   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3239   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3240   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3241   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3242   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3243   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3244   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3245   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3246   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3247   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3248   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3249   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3250     // True -> 7
3251   default:
3252     // Not expecting FCMP_FALSE and FCMP_TRUE;
3253     assert(0 && "Unexpected FCmp predicate!");
3254     return 0;
3255   }
3256 }
3257
3258 /// getICmpValue - This is the complement of getICmpCode, which turns an
3259 /// opcode and two operands into either a constant true or false, or a brand 
3260 /// new ICmp instruction. The sign is passed in to determine which kind
3261 /// of predicate to use in the new icmp instruction.
3262 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3263   switch (code) {
3264   default: assert(0 && "Illegal ICmp code!");
3265   case  0: return ConstantInt::getFalse();
3266   case  1: 
3267     if (sign)
3268       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3269     else
3270       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3271   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3272   case  3: 
3273     if (sign)
3274       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3275     else
3276       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3277   case  4: 
3278     if (sign)
3279       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3280     else
3281       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3282   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3283   case  6: 
3284     if (sign)
3285       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3286     else
3287       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3288   case  7: return ConstantInt::getTrue();
3289   }
3290 }
3291
3292 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3293 /// opcode and two operands into either a FCmp instruction. isordered is passed
3294 /// in to determine which kind of predicate to use in the new fcmp instruction.
3295 static Value *getFCmpValue(bool isordered, unsigned code,
3296                            Value *LHS, Value *RHS) {
3297   switch (code) {
3298   default: assert(0 && "Illegal FCmp code!");
3299   case  0:
3300     if (isordered)
3301       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3302     else
3303       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3304   case  1: 
3305     if (isordered)
3306       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3307     else
3308       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3309   case  2: 
3310     if (isordered)
3311       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3312     else
3313       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3314   case  3: 
3315     if (isordered)
3316       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3317     else
3318       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3319   case  4: 
3320     if (isordered)
3321       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3322     else
3323       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3324   case  5: 
3325     if (isordered)
3326       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3327     else
3328       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3329   case  6: 
3330     if (isordered)
3331       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3332     else
3333       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3334   case  7: return ConstantInt::getTrue();
3335   }
3336 }
3337
3338 /// PredicatesFoldable - Return true if both predicates match sign or if at
3339 /// least one of them is an equality comparison (which is signless).
3340 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3341   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3342          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3343          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3344 }
3345
3346 namespace { 
3347 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3348 struct FoldICmpLogical {
3349   InstCombiner &IC;
3350   Value *LHS, *RHS;
3351   ICmpInst::Predicate pred;
3352   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3353     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3354       pred(ICI->getPredicate()) {}
3355   bool shouldApply(Value *V) const {
3356     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3357       if (PredicatesFoldable(pred, ICI->getPredicate()))
3358         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3359                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3360     return false;
3361   }
3362   Instruction *apply(Instruction &Log) const {
3363     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3364     if (ICI->getOperand(0) != LHS) {
3365       assert(ICI->getOperand(1) == LHS);
3366       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3367     }
3368
3369     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3370     unsigned LHSCode = getICmpCode(ICI);
3371     unsigned RHSCode = getICmpCode(RHSICI);
3372     unsigned Code;
3373     switch (Log.getOpcode()) {
3374     case Instruction::And: Code = LHSCode & RHSCode; break;
3375     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3376     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3377     default: assert(0 && "Illegal logical opcode!"); return 0;
3378     }
3379
3380     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3381                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3382       
3383     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3384     if (Instruction *I = dyn_cast<Instruction>(RV))
3385       return I;
3386     // Otherwise, it's a constant boolean value...
3387     return IC.ReplaceInstUsesWith(Log, RV);
3388   }
3389 };
3390 } // end anonymous namespace
3391
3392 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3393 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3394 // guaranteed to be a binary operator.
3395 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3396                                     ConstantInt *OpRHS,
3397                                     ConstantInt *AndRHS,
3398                                     BinaryOperator &TheAnd) {
3399   Value *X = Op->getOperand(0);
3400   Constant *Together = 0;
3401   if (!Op->isShift())
3402     Together = And(AndRHS, OpRHS);
3403
3404   switch (Op->getOpcode()) {
3405   case Instruction::Xor:
3406     if (Op->hasOneUse()) {
3407       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3408       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3409       InsertNewInstBefore(And, TheAnd);
3410       And->takeName(Op);
3411       return BinaryOperator::CreateXor(And, Together);
3412     }
3413     break;
3414   case Instruction::Or:
3415     if (Together == AndRHS) // (X | C) & C --> C
3416       return ReplaceInstUsesWith(TheAnd, AndRHS);
3417
3418     if (Op->hasOneUse() && Together != OpRHS) {
3419       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3420       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3421       InsertNewInstBefore(Or, TheAnd);
3422       Or->takeName(Op);
3423       return BinaryOperator::CreateAnd(Or, AndRHS);
3424     }
3425     break;
3426   case Instruction::Add:
3427     if (Op->hasOneUse()) {
3428       // Adding a one to a single bit bit-field should be turned into an XOR
3429       // of the bit.  First thing to check is to see if this AND is with a
3430       // single bit constant.
3431       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3432
3433       // If there is only one bit set...
3434       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3435         // Ok, at this point, we know that we are masking the result of the
3436         // ADD down to exactly one bit.  If the constant we are adding has
3437         // no bits set below this bit, then we can eliminate the ADD.
3438         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3439
3440         // Check to see if any bits below the one bit set in AndRHSV are set.
3441         if ((AddRHS & (AndRHSV-1)) == 0) {
3442           // If not, the only thing that can effect the output of the AND is
3443           // the bit specified by AndRHSV.  If that bit is set, the effect of
3444           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3445           // no effect.
3446           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3447             TheAnd.setOperand(0, X);
3448             return &TheAnd;
3449           } else {
3450             // Pull the XOR out of the AND.
3451             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3452             InsertNewInstBefore(NewAnd, TheAnd);
3453             NewAnd->takeName(Op);
3454             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3455           }
3456         }
3457       }
3458     }
3459     break;
3460
3461   case Instruction::Shl: {
3462     // We know that the AND will not produce any of the bits shifted in, so if
3463     // the anded constant includes them, clear them now!
3464     //
3465     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3466     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3467     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3468     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3469
3470     if (CI->getValue() == ShlMask) { 
3471     // Masking out bits that the shift already masks
3472       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3473     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3474       TheAnd.setOperand(1, CI);
3475       return &TheAnd;
3476     }
3477     break;
3478   }
3479   case Instruction::LShr:
3480   {
3481     // We know that the AND will not produce any of the bits shifted in, so if
3482     // the anded constant includes them, clear them now!  This only applies to
3483     // unsigned shifts, because a signed shr may bring in set bits!
3484     //
3485     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3486     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3487     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3488     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3489
3490     if (CI->getValue() == ShrMask) {   
3491     // Masking out bits that the shift already masks.
3492       return ReplaceInstUsesWith(TheAnd, Op);
3493     } else if (CI != AndRHS) {
3494       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3495       return &TheAnd;
3496     }
3497     break;
3498   }
3499   case Instruction::AShr:
3500     // Signed shr.
3501     // See if this is shifting in some sign extension, then masking it out
3502     // with an and.
3503     if (Op->hasOneUse()) {
3504       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3505       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3506       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3507       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3508       if (C == AndRHS) {          // Masking out bits shifted in.
3509         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3510         // Make the argument unsigned.
3511         Value *ShVal = Op->getOperand(0);
3512         ShVal = InsertNewInstBefore(
3513             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3514                                    Op->getName()), TheAnd);
3515         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3516       }
3517     }
3518     break;
3519   }
3520   return 0;
3521 }
3522
3523
3524 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3525 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3526 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3527 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3528 /// insert new instructions.
3529 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3530                                            bool isSigned, bool Inside, 
3531                                            Instruction &IB) {
3532   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3533             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3534          "Lo is not <= Hi in range emission code!");
3535     
3536   if (Inside) {
3537     if (Lo == Hi)  // Trivially false.
3538       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3539
3540     // V >= Min && V < Hi --> V < Hi
3541     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3542       ICmpInst::Predicate pred = (isSigned ? 
3543         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3544       return new ICmpInst(pred, V, Hi);
3545     }
3546
3547     // Emit V-Lo <u Hi-Lo
3548     Constant *NegLo = ConstantExpr::getNeg(Lo);
3549     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3550     InsertNewInstBefore(Add, IB);
3551     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3552     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3553   }
3554
3555   if (Lo == Hi)  // Trivially true.
3556     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3557
3558   // V < Min || V >= Hi -> V > Hi-1
3559   Hi = SubOne(cast<ConstantInt>(Hi));
3560   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3561     ICmpInst::Predicate pred = (isSigned ? 
3562         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3563     return new ICmpInst(pred, V, Hi);
3564   }
3565
3566   // Emit V-Lo >u Hi-1-Lo
3567   // Note that Hi has already had one subtracted from it, above.
3568   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3569   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3570   InsertNewInstBefore(Add, IB);
3571   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3572   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3573 }
3574
3575 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3576 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3577 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3578 // not, since all 1s are not contiguous.
3579 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3580   const APInt& V = Val->getValue();
3581   uint32_t BitWidth = Val->getType()->getBitWidth();
3582   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3583
3584   // look for the first zero bit after the run of ones
3585   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3586   // look for the first non-zero bit
3587   ME = V.getActiveBits(); 
3588   return true;
3589 }
3590
3591 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3592 /// where isSub determines whether the operator is a sub.  If we can fold one of
3593 /// the following xforms:
3594 /// 
3595 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3596 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3597 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3598 ///
3599 /// return (A +/- B).
3600 ///
3601 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3602                                         ConstantInt *Mask, bool isSub,
3603                                         Instruction &I) {
3604   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3605   if (!LHSI || LHSI->getNumOperands() != 2 ||
3606       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3607
3608   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3609
3610   switch (LHSI->getOpcode()) {
3611   default: return 0;
3612   case Instruction::And:
3613     if (And(N, Mask) == Mask) {
3614       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3615       if ((Mask->getValue().countLeadingZeros() + 
3616            Mask->getValue().countPopulation()) == 
3617           Mask->getValue().getBitWidth())
3618         break;
3619
3620       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3621       // part, we don't need any explicit masks to take them out of A.  If that
3622       // is all N is, ignore it.
3623       uint32_t MB = 0, ME = 0;
3624       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3625         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3626         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3627         if (MaskedValueIsZero(RHS, Mask))
3628           break;
3629       }
3630     }
3631     return 0;
3632   case Instruction::Or:
3633   case Instruction::Xor:
3634     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3635     if ((Mask->getValue().countLeadingZeros() + 
3636          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3637         && And(N, Mask)->isZero())
3638       break;
3639     return 0;
3640   }
3641   
3642   Instruction *New;
3643   if (isSub)
3644     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3645   else
3646     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3647   return InsertNewInstBefore(New, I);
3648 }
3649
3650 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3651 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3652                                           ICmpInst *LHS, ICmpInst *RHS) {
3653   Value *Val, *Val2;
3654   ConstantInt *LHSCst, *RHSCst;
3655   ICmpInst::Predicate LHSCC, RHSCC;
3656   
3657   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3658   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
3659       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
3660     return 0;
3661   
3662   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3663   // where C is a power of 2
3664   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3665       LHSCst->getValue().isPowerOf2()) {
3666     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3667     InsertNewInstBefore(NewOr, I);
3668     return new ICmpInst(LHSCC, NewOr, LHSCst);
3669   }
3670   
3671   // From here on, we only handle:
3672   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3673   if (Val != Val2) return 0;
3674   
3675   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3676   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3677       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3678       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3679       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3680     return 0;
3681   
3682   // We can't fold (ugt x, C) & (sgt x, C2).
3683   if (!PredicatesFoldable(LHSCC, RHSCC))
3684     return 0;
3685     
3686   // Ensure that the larger constant is on the RHS.
3687   bool ShouldSwap;
3688   if (ICmpInst::isSignedPredicate(LHSCC) ||
3689       (ICmpInst::isEquality(LHSCC) && 
3690        ICmpInst::isSignedPredicate(RHSCC)))
3691     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3692   else
3693     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3694     
3695   if (ShouldSwap) {
3696     std::swap(LHS, RHS);
3697     std::swap(LHSCst, RHSCst);
3698     std::swap(LHSCC, RHSCC);
3699   }
3700
3701   // At this point, we know we have have two icmp instructions
3702   // comparing a value against two constants and and'ing the result
3703   // together.  Because of the above check, we know that we only have
3704   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3705   // (from the FoldICmpLogical check above), that the two constants 
3706   // are not equal and that the larger constant is on the RHS
3707   assert(LHSCst != RHSCst && "Compares not folded above?");
3708
3709   switch (LHSCC) {
3710   default: assert(0 && "Unknown integer condition code!");
3711   case ICmpInst::ICMP_EQ:
3712     switch (RHSCC) {
3713     default: assert(0 && "Unknown integer condition code!");
3714     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3715     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3716     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3717       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3718     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3719     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3720     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3721       return ReplaceInstUsesWith(I, LHS);
3722     }
3723   case ICmpInst::ICMP_NE:
3724     switch (RHSCC) {
3725     default: assert(0 && "Unknown integer condition code!");
3726     case ICmpInst::ICMP_ULT:
3727       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3728         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3729       break;                        // (X != 13 & X u< 15) -> no change
3730     case ICmpInst::ICMP_SLT:
3731       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3732         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3733       break;                        // (X != 13 & X s< 15) -> no change
3734     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3735     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3736     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3737       return ReplaceInstUsesWith(I, RHS);
3738     case ICmpInst::ICMP_NE:
3739       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3740         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3741         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3742                                                      Val->getName()+".off");
3743         InsertNewInstBefore(Add, I);
3744         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3745                             ConstantInt::get(Add->getType(), 1));
3746       }
3747       break;                        // (X != 13 & X != 15) -> no change
3748     }
3749     break;
3750   case ICmpInst::ICMP_ULT:
3751     switch (RHSCC) {
3752     default: assert(0 && "Unknown integer condition code!");
3753     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3754     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3755       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3756     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3757       break;
3758     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3759     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3760       return ReplaceInstUsesWith(I, LHS);
3761     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3762       break;
3763     }
3764     break;
3765   case ICmpInst::ICMP_SLT:
3766     switch (RHSCC) {
3767     default: assert(0 && "Unknown integer condition code!");
3768     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3769     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3770       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3771     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3772       break;
3773     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3774     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3775       return ReplaceInstUsesWith(I, LHS);
3776     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3777       break;
3778     }
3779     break;
3780   case ICmpInst::ICMP_UGT:
3781     switch (RHSCC) {
3782     default: assert(0 && "Unknown integer condition code!");
3783     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3784     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3785       return ReplaceInstUsesWith(I, RHS);
3786     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3787       break;
3788     case ICmpInst::ICMP_NE:
3789       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3790         return new ICmpInst(LHSCC, Val, RHSCst);
3791       break;                        // (X u> 13 & X != 15) -> no change
3792     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3793       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3794     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3795       break;
3796     }
3797     break;
3798   case ICmpInst::ICMP_SGT:
3799     switch (RHSCC) {
3800     default: assert(0 && "Unknown integer condition code!");
3801     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3802     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3803       return ReplaceInstUsesWith(I, RHS);
3804     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3805       break;
3806     case ICmpInst::ICMP_NE:
3807       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3808         return new ICmpInst(LHSCC, Val, RHSCst);
3809       break;                        // (X s> 13 & X != 15) -> no change
3810     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3811       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3812     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3813       break;
3814     }
3815     break;
3816   }
3817  
3818   return 0;
3819 }
3820
3821
3822 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3823   bool Changed = SimplifyCommutative(I);
3824   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3825
3826   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3827     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3828
3829   // and X, X = X
3830   if (Op0 == Op1)
3831     return ReplaceInstUsesWith(I, Op1);
3832
3833   // See if we can simplify any instructions used by the instruction whose sole 
3834   // purpose is to compute bits we don't care about.
3835   if (!isa<VectorType>(I.getType())) {
3836     if (SimplifyDemandedInstructionBits(I))
3837       return &I;
3838   } else {
3839     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3840       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3841         return ReplaceInstUsesWith(I, I.getOperand(0));
3842     } else if (isa<ConstantAggregateZero>(Op1)) {
3843       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3844     }
3845   }
3846   
3847   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3848     const APInt& AndRHSMask = AndRHS->getValue();
3849     APInt NotAndRHS(~AndRHSMask);
3850
3851     // Optimize a variety of ((val OP C1) & C2) combinations...
3852     if (isa<BinaryOperator>(Op0)) {
3853       Instruction *Op0I = cast<Instruction>(Op0);
3854       Value *Op0LHS = Op0I->getOperand(0);
3855       Value *Op0RHS = Op0I->getOperand(1);
3856       switch (Op0I->getOpcode()) {
3857       case Instruction::Xor:
3858       case Instruction::Or:
3859         // If the mask is only needed on one incoming arm, push it up.
3860         if (Op0I->hasOneUse()) {
3861           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3862             // Not masking anything out for the LHS, move to RHS.
3863             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3864                                                    Op0RHS->getName()+".masked");
3865             InsertNewInstBefore(NewRHS, I);
3866             return BinaryOperator::Create(
3867                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3868           }
3869           if (!isa<Constant>(Op0RHS) &&
3870               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3871             // Not masking anything out for the RHS, move to LHS.
3872             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3873                                                    Op0LHS->getName()+".masked");
3874             InsertNewInstBefore(NewLHS, I);
3875             return BinaryOperator::Create(
3876                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3877           }
3878         }
3879
3880         break;
3881       case Instruction::Add:
3882         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3883         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3884         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3885         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3886           return BinaryOperator::CreateAnd(V, AndRHS);
3887         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3888           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
3889         break;
3890
3891       case Instruction::Sub:
3892         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3893         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3894         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3895         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3896           return BinaryOperator::CreateAnd(V, AndRHS);
3897
3898         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3899         // has 1's for all bits that the subtraction with A might affect.
3900         if (Op0I->hasOneUse()) {
3901           uint32_t BitWidth = AndRHSMask.getBitWidth();
3902           uint32_t Zeros = AndRHSMask.countLeadingZeros();
3903           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3904
3905           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
3906           if (!(A && A->isZero()) &&               // avoid infinite recursion.
3907               MaskedValueIsZero(Op0LHS, Mask)) {
3908             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3909             InsertNewInstBefore(NewNeg, I);
3910             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3911           }
3912         }
3913         break;
3914
3915       case Instruction::Shl:
3916       case Instruction::LShr:
3917         // (1 << x) & 1 --> zext(x == 0)
3918         // (1 >> x) & 1 --> zext(x == 0)
3919         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
3920           Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3921                                            Constant::getNullValue(I.getType()));
3922           InsertNewInstBefore(NewICmp, I);
3923           return new ZExtInst(NewICmp, I.getType());
3924         }
3925         break;
3926       }
3927
3928       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3929         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3930           return Res;
3931     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3932       // If this is an integer truncation or change from signed-to-unsigned, and
3933       // if the source is an and/or with immediate, transform it.  This
3934       // frequently occurs for bitfield accesses.
3935       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3936         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3937             CastOp->getNumOperands() == 2)
3938           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3939             if (CastOp->getOpcode() == Instruction::And) {
3940               // Change: and (cast (and X, C1) to T), C2
3941               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3942               // This will fold the two constants together, which may allow 
3943               // other simplifications.
3944               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
3945                 CastOp->getOperand(0), I.getType(), 
3946                 CastOp->getName()+".shrunk");
3947               NewCast = InsertNewInstBefore(NewCast, I);
3948               // trunc_or_bitcast(C1)&C2
3949               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3950               C3 = ConstantExpr::getAnd(C3, AndRHS);
3951               return BinaryOperator::CreateAnd(NewCast, C3);
3952             } else if (CastOp->getOpcode() == Instruction::Or) {
3953               // Change: and (cast (or X, C1) to T), C2
3954               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3955               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3956               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3957                 return ReplaceInstUsesWith(I, AndRHS);
3958             }
3959           }
3960       }
3961     }
3962
3963     // Try to fold constant and into select arguments.
3964     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3965       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3966         return R;
3967     if (isa<PHINode>(Op0))
3968       if (Instruction *NV = FoldOpIntoPhi(I))
3969         return NV;
3970   }
3971
3972   Value *Op0NotVal = dyn_castNotVal(Op0);
3973   Value *Op1NotVal = dyn_castNotVal(Op1);
3974
3975   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3976     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3977
3978   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3979   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3980     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
3981                                                I.getName()+".demorgan");
3982     InsertNewInstBefore(Or, I);
3983     return BinaryOperator::CreateNot(Or);
3984   }
3985   
3986   {
3987     Value *A = 0, *B = 0, *C = 0, *D = 0;
3988     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3989       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3990         return ReplaceInstUsesWith(I, Op1);
3991     
3992       // (A|B) & ~(A&B) -> A^B
3993       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3994         if ((A == C && B == D) || (A == D && B == C))
3995           return BinaryOperator::CreateXor(A, B);
3996       }
3997     }
3998     
3999     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4000       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4001         return ReplaceInstUsesWith(I, Op0);
4002
4003       // ~(A&B) & (A|B) -> A^B
4004       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4005         if ((A == C && B == D) || (A == D && B == C))
4006           return BinaryOperator::CreateXor(A, B);
4007       }
4008     }
4009     
4010     if (Op0->hasOneUse() &&
4011         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4012       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4013         I.swapOperands();     // Simplify below
4014         std::swap(Op0, Op1);
4015       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4016         cast<BinaryOperator>(Op0)->swapOperands();
4017         I.swapOperands();     // Simplify below
4018         std::swap(Op0, Op1);
4019       }
4020     }
4021
4022     if (Op1->hasOneUse() &&
4023         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4024       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4025         cast<BinaryOperator>(Op1)->swapOperands();
4026         std::swap(A, B);
4027       }
4028       if (A == Op0) {                                // A&(A^B) -> A & ~B
4029         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
4030         InsertNewInstBefore(NotB, I);
4031         return BinaryOperator::CreateAnd(A, NotB);
4032       }
4033     }
4034
4035     // (A&((~A)|B)) -> A&B
4036     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4037         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4038       return BinaryOperator::CreateAnd(A, Op1);
4039     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4040         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4041       return BinaryOperator::CreateAnd(A, Op0);
4042   }
4043   
4044   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4045     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4046     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4047       return R;
4048
4049     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4050       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4051         return Res;
4052   }
4053
4054   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4055   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4056     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4057       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4058         const Type *SrcTy = Op0C->getOperand(0)->getType();
4059         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4060             // Only do this if the casts both really cause code to be generated.
4061             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4062                               I.getType(), TD) &&
4063             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4064                               I.getType(), TD)) {
4065           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4066                                                          Op1C->getOperand(0),
4067                                                          I.getName());
4068           InsertNewInstBefore(NewOp, I);
4069           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4070         }
4071       }
4072     
4073   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4074   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4075     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4076       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4077           SI0->getOperand(1) == SI1->getOperand(1) &&
4078           (SI0->hasOneUse() || SI1->hasOneUse())) {
4079         Instruction *NewOp =
4080           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4081                                                         SI1->getOperand(0),
4082                                                         SI0->getName()), I);
4083         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4084                                       SI1->getOperand(1));
4085       }
4086   }
4087
4088   // If and'ing two fcmp, try combine them into one.
4089   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4090     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4091       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4092           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4093         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4094         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4095           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4096             // If either of the constants are nans, then the whole thing returns
4097             // false.
4098             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4099               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4100             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4101                                 RHS->getOperand(0));
4102           }
4103       } else {
4104         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4105         FCmpInst::Predicate Op0CC, Op1CC;
4106         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4107             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4108           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4109             // Swap RHS operands to match LHS.
4110             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4111             std::swap(Op1LHS, Op1RHS);
4112           }
4113           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4114             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4115             if (Op0CC == Op1CC)
4116               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4117             else if (Op0CC == FCmpInst::FCMP_FALSE ||
4118                      Op1CC == FCmpInst::FCMP_FALSE)
4119               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4120             else if (Op0CC == FCmpInst::FCMP_TRUE)
4121               return ReplaceInstUsesWith(I, Op1);
4122             else if (Op1CC == FCmpInst::FCMP_TRUE)
4123               return ReplaceInstUsesWith(I, Op0);
4124             bool Op0Ordered;
4125             bool Op1Ordered;
4126             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4127             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4128             if (Op1Pred == 0) {
4129               std::swap(Op0, Op1);
4130               std::swap(Op0Pred, Op1Pred);
4131               std::swap(Op0Ordered, Op1Ordered);
4132             }
4133             if (Op0Pred == 0) {
4134               // uno && ueq -> uno && (uno || eq) -> ueq
4135               // ord && olt -> ord && (ord && lt) -> olt
4136               if (Op0Ordered == Op1Ordered)
4137                 return ReplaceInstUsesWith(I, Op1);
4138               // uno && oeq -> uno && (ord && eq) -> false
4139               // uno && ord -> false
4140               if (!Op0Ordered)
4141                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4142               // ord && ueq -> ord && (uno || eq) -> oeq
4143               return cast<Instruction>(getFCmpValue(true, Op1Pred,
4144                                                     Op0LHS, Op0RHS));
4145             }
4146           }
4147         }
4148       }
4149     }
4150   }
4151
4152   return Changed ? &I : 0;
4153 }
4154
4155 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4156 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4157 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4158 /// the expression came from the corresponding "byte swapped" byte in some other
4159 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4160 /// we know that the expression deposits the low byte of %X into the high byte
4161 /// of the bswap result and that all other bytes are zero.  This expression is
4162 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4163 /// match.
4164 ///
4165 /// This function returns true if the match was unsuccessful and false if so.
4166 /// On entry to the function the "OverallLeftShift" is a signed integer value
4167 /// indicating the number of bytes that the subexpression is later shifted.  For
4168 /// example, if the expression is later right shifted by 16 bits, the
4169 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4170 /// byte of ByteValues is actually being set.
4171 ///
4172 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4173 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4174 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4175 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4176 /// always in the local (OverallLeftShift) coordinate space.
4177 ///
4178 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4179                               SmallVector<Value*, 8> &ByteValues) {
4180   if (Instruction *I = dyn_cast<Instruction>(V)) {
4181     // If this is an or instruction, it may be an inner node of the bswap.
4182     if (I->getOpcode() == Instruction::Or) {
4183       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4184                                ByteValues) ||
4185              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4186                                ByteValues);
4187     }
4188   
4189     // If this is a logical shift by a constant multiple of 8, recurse with
4190     // OverallLeftShift and ByteMask adjusted.
4191     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4192       unsigned ShAmt = 
4193         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4194       // Ensure the shift amount is defined and of a byte value.
4195       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4196         return true;
4197
4198       unsigned ByteShift = ShAmt >> 3;
4199       if (I->getOpcode() == Instruction::Shl) {
4200         // X << 2 -> collect(X, +2)
4201         OverallLeftShift += ByteShift;
4202         ByteMask >>= ByteShift;
4203       } else {
4204         // X >>u 2 -> collect(X, -2)
4205         OverallLeftShift -= ByteShift;
4206         ByteMask <<= ByteShift;
4207         ByteMask &= (~0U >> (32-ByteValues.size()));
4208       }
4209
4210       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4211       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4212
4213       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4214                                ByteValues);
4215     }
4216
4217     // If this is a logical 'and' with a mask that clears bytes, clear the
4218     // corresponding bytes in ByteMask.
4219     if (I->getOpcode() == Instruction::And &&
4220         isa<ConstantInt>(I->getOperand(1))) {
4221       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4222       unsigned NumBytes = ByteValues.size();
4223       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4224       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4225       
4226       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4227         // If this byte is masked out by a later operation, we don't care what
4228         // the and mask is.
4229         if ((ByteMask & (1 << i)) == 0)
4230           continue;
4231         
4232         // If the AndMask is all zeros for this byte, clear the bit.
4233         APInt MaskB = AndMask & Byte;
4234         if (MaskB == 0) {
4235           ByteMask &= ~(1U << i);
4236           continue;
4237         }
4238         
4239         // If the AndMask is not all ones for this byte, it's not a bytezap.
4240         if (MaskB != Byte)
4241           return true;
4242
4243         // Otherwise, this byte is kept.
4244       }
4245
4246       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4247                                ByteValues);
4248     }
4249   }
4250   
4251   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4252   // the input value to the bswap.  Some observations: 1) if more than one byte
4253   // is demanded from this input, then it could not be successfully assembled
4254   // into a byteswap.  At least one of the two bytes would not be aligned with
4255   // their ultimate destination.
4256   if (!isPowerOf2_32(ByteMask)) return true;
4257   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4258   
4259   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4260   // is demanded, it needs to go into byte 0 of the result.  This means that the
4261   // byte needs to be shifted until it lands in the right byte bucket.  The
4262   // shift amount depends on the position: if the byte is coming from the high
4263   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4264   // low part, it must be shifted left.
4265   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4266   if (InputByteNo < ByteValues.size()/2) {
4267     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4268       return true;
4269   } else {
4270     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4271       return true;
4272   }
4273   
4274   // If the destination byte value is already defined, the values are or'd
4275   // together, which isn't a bswap (unless it's an or of the same bits).
4276   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4277     return true;
4278   ByteValues[DestByteNo] = V;
4279   return false;
4280 }
4281
4282 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4283 /// If so, insert the new bswap intrinsic and return it.
4284 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4285   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4286   if (!ITy || ITy->getBitWidth() % 16 || 
4287       // ByteMask only allows up to 32-byte values.
4288       ITy->getBitWidth() > 32*8) 
4289     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4290   
4291   /// ByteValues - For each byte of the result, we keep track of which value
4292   /// defines each byte.
4293   SmallVector<Value*, 8> ByteValues;
4294   ByteValues.resize(ITy->getBitWidth()/8);
4295     
4296   // Try to find all the pieces corresponding to the bswap.
4297   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4298   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4299     return 0;
4300   
4301   // Check to see if all of the bytes come from the same value.
4302   Value *V = ByteValues[0];
4303   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4304   
4305   // Check to make sure that all of the bytes come from the same value.
4306   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4307     if (ByteValues[i] != V)
4308       return 0;
4309   const Type *Tys[] = { ITy };
4310   Module *M = I.getParent()->getParent()->getParent();
4311   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4312   return CallInst::Create(F, V);
4313 }
4314
4315 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4316 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4317 /// we can simplify this expression to "cond ? C : D or B".
4318 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4319                                          Value *C, Value *D) {
4320   // If A is not a select of -1/0, this cannot match.
4321   Value *Cond = 0;
4322   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4323     return 0;
4324
4325   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4326   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4327     return SelectInst::Create(Cond, C, B);
4328   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4329     return SelectInst::Create(Cond, C, B);
4330   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4331   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4332     return SelectInst::Create(Cond, C, D);
4333   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4334     return SelectInst::Create(Cond, C, D);
4335   return 0;
4336 }
4337
4338 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4339 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4340                                          ICmpInst *LHS, ICmpInst *RHS) {
4341   Value *Val, *Val2;
4342   ConstantInt *LHSCst, *RHSCst;
4343   ICmpInst::Predicate LHSCC, RHSCC;
4344   
4345   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4346   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4347       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4348     return 0;
4349   
4350   // From here on, we only handle:
4351   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4352   if (Val != Val2) return 0;
4353   
4354   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4355   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4356       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4357       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4358       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4359     return 0;
4360   
4361   // We can't fold (ugt x, C) | (sgt x, C2).
4362   if (!PredicatesFoldable(LHSCC, RHSCC))
4363     return 0;
4364   
4365   // Ensure that the larger constant is on the RHS.
4366   bool ShouldSwap;
4367   if (ICmpInst::isSignedPredicate(LHSCC) ||
4368       (ICmpInst::isEquality(LHSCC) && 
4369        ICmpInst::isSignedPredicate(RHSCC)))
4370     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4371   else
4372     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4373   
4374   if (ShouldSwap) {
4375     std::swap(LHS, RHS);
4376     std::swap(LHSCst, RHSCst);
4377     std::swap(LHSCC, RHSCC);
4378   }
4379   
4380   // At this point, we know we have have two icmp instructions
4381   // comparing a value against two constants and or'ing the result
4382   // together.  Because of the above check, we know that we only have
4383   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4384   // FoldICmpLogical check above), that the two constants are not
4385   // equal.
4386   assert(LHSCst != RHSCst && "Compares not folded above?");
4387
4388   switch (LHSCC) {
4389   default: assert(0 && "Unknown integer condition code!");
4390   case ICmpInst::ICMP_EQ:
4391     switch (RHSCC) {
4392     default: assert(0 && "Unknown integer condition code!");
4393     case ICmpInst::ICMP_EQ:
4394       if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4395         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4396         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4397                                                      Val->getName()+".off");
4398         InsertNewInstBefore(Add, I);
4399         AddCST = Subtract(AddOne(RHSCst), LHSCst);
4400         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4401       }
4402       break;                         // (X == 13 | X == 15) -> no change
4403     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4404     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4405       break;
4406     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4407     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4408     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4409       return ReplaceInstUsesWith(I, RHS);
4410     }
4411     break;
4412   case ICmpInst::ICMP_NE:
4413     switch (RHSCC) {
4414     default: assert(0 && "Unknown integer condition code!");
4415     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4416     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4417     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4418       return ReplaceInstUsesWith(I, LHS);
4419     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4420     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4421     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4422       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4423     }
4424     break;
4425   case ICmpInst::ICMP_ULT:
4426     switch (RHSCC) {
4427     default: assert(0 && "Unknown integer condition code!");
4428     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4429       break;
4430     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4431       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4432       // this can cause overflow.
4433       if (RHSCst->isMaxValue(false))
4434         return ReplaceInstUsesWith(I, LHS);
4435       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4436     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4437       break;
4438     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4439     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4440       return ReplaceInstUsesWith(I, RHS);
4441     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4442       break;
4443     }
4444     break;
4445   case ICmpInst::ICMP_SLT:
4446     switch (RHSCC) {
4447     default: assert(0 && "Unknown integer condition code!");
4448     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4449       break;
4450     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4451       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4452       // this can cause overflow.
4453       if (RHSCst->isMaxValue(true))
4454         return ReplaceInstUsesWith(I, LHS);
4455       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4456     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4457       break;
4458     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4459     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4460       return ReplaceInstUsesWith(I, RHS);
4461     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4462       break;
4463     }
4464     break;
4465   case ICmpInst::ICMP_UGT:
4466     switch (RHSCC) {
4467     default: assert(0 && "Unknown integer condition code!");
4468     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4469     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4470       return ReplaceInstUsesWith(I, LHS);
4471     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4472       break;
4473     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4474     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4475       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4476     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4477       break;
4478     }
4479     break;
4480   case ICmpInst::ICMP_SGT:
4481     switch (RHSCC) {
4482     default: assert(0 && "Unknown integer condition code!");
4483     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4484     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4485       return ReplaceInstUsesWith(I, LHS);
4486     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4487       break;
4488     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4489     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4490       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4491     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4492       break;
4493     }
4494     break;
4495   }
4496   return 0;
4497 }
4498
4499 /// FoldOrWithConstants - This helper function folds:
4500 ///
4501 ///     ((A | B) & C1) | (B & C2)
4502 ///
4503 /// into:
4504 /// 
4505 ///     (A & C1) | B
4506 ///
4507 /// when the XOR of the two constants is "all ones" (-1).
4508 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4509                                                Value *A, Value *B, Value *C) {
4510   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4511   if (!CI1) return 0;
4512
4513   Value *V1 = 0;
4514   ConstantInt *CI2 = 0;
4515   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4516
4517   APInt Xor = CI1->getValue() ^ CI2->getValue();
4518   if (!Xor.isAllOnesValue()) return 0;
4519
4520   if (V1 == A || V1 == B) {
4521     Instruction *NewOp =
4522       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4523     return BinaryOperator::CreateOr(NewOp, V1);
4524   }
4525
4526   return 0;
4527 }
4528
4529 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4530   bool Changed = SimplifyCommutative(I);
4531   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4532
4533   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4534     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4535
4536   // or X, X = X
4537   if (Op0 == Op1)
4538     return ReplaceInstUsesWith(I, Op0);
4539
4540   // See if we can simplify any instructions used by the instruction whose sole 
4541   // purpose is to compute bits we don't care about.
4542   if (!isa<VectorType>(I.getType())) {
4543     if (SimplifyDemandedInstructionBits(I))
4544       return &I;
4545   } else if (isa<ConstantAggregateZero>(Op1)) {
4546     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4547   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4548     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4549       return ReplaceInstUsesWith(I, I.getOperand(1));
4550   }
4551     
4552
4553   
4554   // or X, -1 == -1
4555   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4556     ConstantInt *C1 = 0; Value *X = 0;
4557     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4558     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4559       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4560       InsertNewInstBefore(Or, I);
4561       Or->takeName(Op0);
4562       return BinaryOperator::CreateAnd(Or, 
4563                ConstantInt::get(RHS->getValue() | C1->getValue()));
4564     }
4565
4566     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4567     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4568       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4569       InsertNewInstBefore(Or, I);
4570       Or->takeName(Op0);
4571       return BinaryOperator::CreateXor(Or,
4572                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4573     }
4574
4575     // Try to fold constant and into select arguments.
4576     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4577       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4578         return R;
4579     if (isa<PHINode>(Op0))
4580       if (Instruction *NV = FoldOpIntoPhi(I))
4581         return NV;
4582   }
4583
4584   Value *A = 0, *B = 0;
4585   ConstantInt *C1 = 0, *C2 = 0;
4586
4587   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4588     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4589       return ReplaceInstUsesWith(I, Op1);
4590   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4591     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4592       return ReplaceInstUsesWith(I, Op0);
4593
4594   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4595   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4596   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4597       match(Op1, m_Or(m_Value(), m_Value())) ||
4598       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4599        match(Op1, m_Shift(m_Value(), m_Value())))) {
4600     if (Instruction *BSwap = MatchBSwap(I))
4601       return BSwap;
4602   }
4603   
4604   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4605   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4606       MaskedValueIsZero(Op1, C1->getValue())) {
4607     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4608     InsertNewInstBefore(NOr, I);
4609     NOr->takeName(Op0);
4610     return BinaryOperator::CreateXor(NOr, C1);
4611   }
4612
4613   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4614   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4615       MaskedValueIsZero(Op0, C1->getValue())) {
4616     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4617     InsertNewInstBefore(NOr, I);
4618     NOr->takeName(Op0);
4619     return BinaryOperator::CreateXor(NOr, C1);
4620   }
4621
4622   // (A & C)|(B & D)
4623   Value *C = 0, *D = 0;
4624   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4625       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4626     Value *V1 = 0, *V2 = 0, *V3 = 0;
4627     C1 = dyn_cast<ConstantInt>(C);
4628     C2 = dyn_cast<ConstantInt>(D);
4629     if (C1 && C2) {  // (A & C1)|(B & C2)
4630       // If we have: ((V + N) & C1) | (V & C2)
4631       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4632       // replace with V+N.
4633       if (C1->getValue() == ~C2->getValue()) {
4634         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4635             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4636           // Add commutes, try both ways.
4637           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4638             return ReplaceInstUsesWith(I, A);
4639           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4640             return ReplaceInstUsesWith(I, A);
4641         }
4642         // Or commutes, try both ways.
4643         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4644             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4645           // Add commutes, try both ways.
4646           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4647             return ReplaceInstUsesWith(I, B);
4648           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4649             return ReplaceInstUsesWith(I, B);
4650         }
4651       }
4652       V1 = 0; V2 = 0; V3 = 0;
4653     }
4654     
4655     // Check to see if we have any common things being and'ed.  If so, find the
4656     // terms for V1 & (V2|V3).
4657     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4658       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4659         V1 = A, V2 = C, V3 = D;
4660       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4661         V1 = A, V2 = B, V3 = C;
4662       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4663         V1 = C, V2 = A, V3 = D;
4664       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4665         V1 = C, V2 = A, V3 = B;
4666       
4667       if (V1) {
4668         Value *Or =
4669           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4670         return BinaryOperator::CreateAnd(V1, Or);
4671       }
4672     }
4673
4674     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4675     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4676       return Match;
4677     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4678       return Match;
4679     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4680       return Match;
4681     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4682       return Match;
4683
4684     // ((A&~B)|(~A&B)) -> A^B
4685     if ((match(C, m_Not(m_Specific(D))) &&
4686          match(B, m_Not(m_Specific(A)))))
4687       return BinaryOperator::CreateXor(A, D);
4688     // ((~B&A)|(~A&B)) -> A^B
4689     if ((match(A, m_Not(m_Specific(D))) &&
4690          match(B, m_Not(m_Specific(C)))))
4691       return BinaryOperator::CreateXor(C, D);
4692     // ((A&~B)|(B&~A)) -> A^B
4693     if ((match(C, m_Not(m_Specific(B))) &&
4694          match(D, m_Not(m_Specific(A)))))
4695       return BinaryOperator::CreateXor(A, B);
4696     // ((~B&A)|(B&~A)) -> A^B
4697     if ((match(A, m_Not(m_Specific(B))) &&
4698          match(D, m_Not(m_Specific(C)))))
4699       return BinaryOperator::CreateXor(C, B);
4700   }
4701   
4702   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4703   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4704     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4705       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4706           SI0->getOperand(1) == SI1->getOperand(1) &&
4707           (SI0->hasOneUse() || SI1->hasOneUse())) {
4708         Instruction *NewOp =
4709         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4710                                                      SI1->getOperand(0),
4711                                                      SI0->getName()), I);
4712         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4713                                       SI1->getOperand(1));
4714       }
4715   }
4716
4717   // ((A|B)&1)|(B&-2) -> (A&1) | B
4718   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4719       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4720     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4721     if (Ret) return Ret;
4722   }
4723   // (B&-2)|((A|B)&1) -> (A&1) | B
4724   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4725       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4726     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4727     if (Ret) return Ret;
4728   }
4729
4730   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4731     if (A == Op1)   // ~A | A == -1
4732       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4733   } else {
4734     A = 0;
4735   }
4736   // Note, A is still live here!
4737   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4738     if (Op0 == B)
4739       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4740
4741     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4742     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4743       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4744                                               I.getName()+".demorgan"), I);
4745       return BinaryOperator::CreateNot(And);
4746     }
4747   }
4748
4749   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4750   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4751     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4752       return R;
4753
4754     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4755       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4756         return Res;
4757   }
4758     
4759   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4760   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4761     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4762       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4763         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4764             !isa<ICmpInst>(Op1C->getOperand(0))) {
4765           const Type *SrcTy = Op0C->getOperand(0)->getType();
4766           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4767               // Only do this if the casts both really cause code to be
4768               // generated.
4769               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4770                                 I.getType(), TD) &&
4771               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4772                                 I.getType(), TD)) {
4773             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4774                                                           Op1C->getOperand(0),
4775                                                           I.getName());
4776             InsertNewInstBefore(NewOp, I);
4777             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4778           }
4779         }
4780       }
4781   }
4782   
4783     
4784   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4785   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4786     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4787       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4788           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4789           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4790         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4791           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4792             // If either of the constants are nans, then the whole thing returns
4793             // true.
4794             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4795               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4796             
4797             // Otherwise, no need to compare the two constants, compare the
4798             // rest.
4799             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4800                                 RHS->getOperand(0));
4801           }
4802       } else {
4803         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4804         FCmpInst::Predicate Op0CC, Op1CC;
4805         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4806             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4807           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4808             // Swap RHS operands to match LHS.
4809             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4810             std::swap(Op1LHS, Op1RHS);
4811           }
4812           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4813             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4814             if (Op0CC == Op1CC)
4815               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4816             else if (Op0CC == FCmpInst::FCMP_TRUE ||
4817                      Op1CC == FCmpInst::FCMP_TRUE)
4818               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4819             else if (Op0CC == FCmpInst::FCMP_FALSE)
4820               return ReplaceInstUsesWith(I, Op1);
4821             else if (Op1CC == FCmpInst::FCMP_FALSE)
4822               return ReplaceInstUsesWith(I, Op0);
4823             bool Op0Ordered;
4824             bool Op1Ordered;
4825             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4826             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4827             if (Op0Ordered == Op1Ordered) {
4828               // If both are ordered or unordered, return a new fcmp with
4829               // or'ed predicates.
4830               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4831                                        Op0LHS, Op0RHS);
4832               if (Instruction *I = dyn_cast<Instruction>(RV))
4833                 return I;
4834               // Otherwise, it's a constant boolean value...
4835               return ReplaceInstUsesWith(I, RV);
4836             }
4837           }
4838         }
4839       }
4840     }
4841   }
4842
4843   return Changed ? &I : 0;
4844 }
4845
4846 namespace {
4847
4848 // XorSelf - Implements: X ^ X --> 0
4849 struct XorSelf {
4850   Value *RHS;
4851   XorSelf(Value *rhs) : RHS(rhs) {}
4852   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4853   Instruction *apply(BinaryOperator &Xor) const {
4854     return &Xor;
4855   }
4856 };
4857
4858 }
4859
4860 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4861   bool Changed = SimplifyCommutative(I);
4862   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4863
4864   if (isa<UndefValue>(Op1)) {
4865     if (isa<UndefValue>(Op0))
4866       // Handle undef ^ undef -> 0 special case. This is a common
4867       // idiom (misuse).
4868       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4869     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4870   }
4871
4872   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4873   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4874     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4875     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4876   }
4877   
4878   // See if we can simplify any instructions used by the instruction whose sole 
4879   // purpose is to compute bits we don't care about.
4880   if (!isa<VectorType>(I.getType())) {
4881     if (SimplifyDemandedInstructionBits(I))
4882       return &I;
4883   } else if (isa<ConstantAggregateZero>(Op1)) {
4884     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4885   }
4886
4887   // Is this a ~ operation?
4888   if (Value *NotOp = dyn_castNotVal(&I)) {
4889     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4890     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4891     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4892       if (Op0I->getOpcode() == Instruction::And || 
4893           Op0I->getOpcode() == Instruction::Or) {
4894         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4895         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4896           Instruction *NotY =
4897             BinaryOperator::CreateNot(Op0I->getOperand(1),
4898                                       Op0I->getOperand(1)->getName()+".not");
4899           InsertNewInstBefore(NotY, I);
4900           if (Op0I->getOpcode() == Instruction::And)
4901             return BinaryOperator::CreateOr(Op0NotVal, NotY);
4902           else
4903             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4904         }
4905       }
4906     }
4907   }
4908   
4909   
4910   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4911     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4912       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4913       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4914         return new ICmpInst(ICI->getInversePredicate(),
4915                             ICI->getOperand(0), ICI->getOperand(1));
4916
4917       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4918         return new FCmpInst(FCI->getInversePredicate(),
4919                             FCI->getOperand(0), FCI->getOperand(1));
4920     }
4921
4922     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4923     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4924       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4925         if (CI->hasOneUse() && Op0C->hasOneUse()) {
4926           Instruction::CastOps Opcode = Op0C->getOpcode();
4927           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4928             if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4929                                              Op0C->getDestTy())) {
4930               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4931                                      CI->getOpcode(), CI->getInversePredicate(),
4932                                      CI->getOperand(0), CI->getOperand(1)), I);
4933               NewCI->takeName(CI);
4934               return CastInst::Create(Opcode, NewCI, Op0C->getType());
4935             }
4936           }
4937         }
4938       }
4939     }
4940
4941     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4942       // ~(c-X) == X-c-1 == X+(-c-1)
4943       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4944         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4945           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4946           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4947                                               ConstantInt::get(I.getType(), 1));
4948           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
4949         }
4950           
4951       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4952         if (Op0I->getOpcode() == Instruction::Add) {
4953           // ~(X-c) --> (-c-1)-X
4954           if (RHS->isAllOnesValue()) {
4955             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4956             return BinaryOperator::CreateSub(
4957                            ConstantExpr::getSub(NegOp0CI,
4958                                              ConstantInt::get(I.getType(), 1)),
4959                                           Op0I->getOperand(0));
4960           } else if (RHS->getValue().isSignBit()) {
4961             // (X + C) ^ signbit -> (X + C + signbit)
4962             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4963             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
4964
4965           }
4966         } else if (Op0I->getOpcode() == Instruction::Or) {
4967           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4968           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4969             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4970             // Anything in both C1 and C2 is known to be zero, remove it from
4971             // NewRHS.
4972             Constant *CommonBits = And(Op0CI, RHS);
4973             NewRHS = ConstantExpr::getAnd(NewRHS, 
4974                                           ConstantExpr::getNot(CommonBits));
4975             AddToWorkList(Op0I);
4976             I.setOperand(0, Op0I->getOperand(0));
4977             I.setOperand(1, NewRHS);
4978             return &I;
4979           }
4980         }
4981       }
4982     }
4983
4984     // Try to fold constant and into select arguments.
4985     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4986       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4987         return R;
4988     if (isa<PHINode>(Op0))
4989       if (Instruction *NV = FoldOpIntoPhi(I))
4990         return NV;
4991   }
4992
4993   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4994     if (X == Op1)
4995       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4996
4997   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4998     if (X == Op0)
4999       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5000
5001   
5002   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5003   if (Op1I) {
5004     Value *A, *B;
5005     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5006       if (A == Op0) {              // B^(B|A) == (A|B)^B
5007         Op1I->swapOperands();
5008         I.swapOperands();
5009         std::swap(Op0, Op1);
5010       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5011         I.swapOperands();     // Simplified below.
5012         std::swap(Op0, Op1);
5013       }
5014     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5015       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5016     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5017       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5018     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
5019       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5020         Op1I->swapOperands();
5021         std::swap(A, B);
5022       }
5023       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5024         I.swapOperands();     // Simplified below.
5025         std::swap(Op0, Op1);
5026       }
5027     }
5028   }
5029   
5030   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5031   if (Op0I) {
5032     Value *A, *B;
5033     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5034       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5035         std::swap(A, B);
5036       if (B == Op1) {                                // (A|B)^B == A & ~B
5037         Instruction *NotB =
5038           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5039         return BinaryOperator::CreateAnd(A, NotB);
5040       }
5041     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5042       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5043     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5044       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5045     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5046       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5047         std::swap(A, B);
5048       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5049           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5050         Instruction *N =
5051           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5052         return BinaryOperator::CreateAnd(N, Op1);
5053       }
5054     }
5055   }
5056   
5057   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5058   if (Op0I && Op1I && Op0I->isShift() && 
5059       Op0I->getOpcode() == Op1I->getOpcode() && 
5060       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5061       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5062     Instruction *NewOp =
5063       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5064                                                     Op1I->getOperand(0),
5065                                                     Op0I->getName()), I);
5066     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5067                                   Op1I->getOperand(1));
5068   }
5069     
5070   if (Op0I && Op1I) {
5071     Value *A, *B, *C, *D;
5072     // (A & B)^(A | B) -> A ^ B
5073     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5074         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5075       if ((A == C && B == D) || (A == D && B == C)) 
5076         return BinaryOperator::CreateXor(A, B);
5077     }
5078     // (A | B)^(A & B) -> A ^ B
5079     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5080         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5081       if ((A == C && B == D) || (A == D && B == C)) 
5082         return BinaryOperator::CreateXor(A, B);
5083     }
5084     
5085     // (A & B)^(C & D)
5086     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5087         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5088         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5089       // (X & Y)^(X & Y) -> (Y^Z) & X
5090       Value *X = 0, *Y = 0, *Z = 0;
5091       if (A == C)
5092         X = A, Y = B, Z = D;
5093       else if (A == D)
5094         X = A, Y = B, Z = C;
5095       else if (B == C)
5096         X = B, Y = A, Z = D;
5097       else if (B == D)
5098         X = B, Y = A, Z = C;
5099       
5100       if (X) {
5101         Instruction *NewOp =
5102         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5103         return BinaryOperator::CreateAnd(NewOp, X);
5104       }
5105     }
5106   }
5107     
5108   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5109   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5110     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5111       return R;
5112
5113   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5114   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5115     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5116       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5117         const Type *SrcTy = Op0C->getOperand(0)->getType();
5118         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5119             // Only do this if the casts both really cause code to be generated.
5120             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5121                               I.getType(), TD) &&
5122             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5123                               I.getType(), TD)) {
5124           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5125                                                          Op1C->getOperand(0),
5126                                                          I.getName());
5127           InsertNewInstBefore(NewOp, I);
5128           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5129         }
5130       }
5131   }
5132
5133   return Changed ? &I : 0;
5134 }
5135
5136 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5137 /// overflowed for this type.
5138 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5139                             ConstantInt *In2, bool IsSigned = false) {
5140   Result = cast<ConstantInt>(Add(In1, In2));
5141
5142   if (IsSigned)
5143     if (In2->getValue().isNegative())
5144       return Result->getValue().sgt(In1->getValue());
5145     else
5146       return Result->getValue().slt(In1->getValue());
5147   else
5148     return Result->getValue().ult(In1->getValue());
5149 }
5150
5151 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5152 /// overflowed for this type.
5153 static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5154                             ConstantInt *In2, bool IsSigned = false) {
5155   Result = cast<ConstantInt>(Subtract(In1, In2));
5156
5157   if (IsSigned)
5158     if (In2->getValue().isNegative())
5159       return Result->getValue().slt(In1->getValue());
5160     else
5161       return Result->getValue().sgt(In1->getValue());
5162   else
5163     return Result->getValue().ugt(In1->getValue());
5164 }
5165
5166 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5167 /// code necessary to compute the offset from the base pointer (without adding
5168 /// in the base pointer).  Return the result as a signed integer of intptr size.
5169 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5170   TargetData &TD = IC.getTargetData();
5171   gep_type_iterator GTI = gep_type_begin(GEP);
5172   const Type *IntPtrTy = TD.getIntPtrType();
5173   Value *Result = Constant::getNullValue(IntPtrTy);
5174
5175   // Build a mask for high order bits.
5176   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5177   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5178
5179   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5180        ++i, ++GTI) {
5181     Value *Op = *i;
5182     uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType()) & PtrSizeMask;
5183     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5184       if (OpC->isZero()) continue;
5185       
5186       // Handle a struct index, which adds its field offset to the pointer.
5187       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5188         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5189         
5190         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5191           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
5192         else
5193           Result = IC.InsertNewInstBefore(
5194                    BinaryOperator::CreateAdd(Result,
5195                                              ConstantInt::get(IntPtrTy, Size),
5196                                              GEP->getName()+".offs"), I);
5197         continue;
5198       }
5199       
5200       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5201       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5202       Scale = ConstantExpr::getMul(OC, Scale);
5203       if (Constant *RC = dyn_cast<Constant>(Result))
5204         Result = ConstantExpr::getAdd(RC, Scale);
5205       else {
5206         // Emit an add instruction.
5207         Result = IC.InsertNewInstBefore(
5208            BinaryOperator::CreateAdd(Result, Scale,
5209                                      GEP->getName()+".offs"), I);
5210       }
5211       continue;
5212     }
5213     // Convert to correct type.
5214     if (Op->getType() != IntPtrTy) {
5215       if (Constant *OpC = dyn_cast<Constant>(Op))
5216         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5217       else
5218         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5219                                                  Op->getName()+".c"), I);
5220     }
5221     if (Size != 1) {
5222       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5223       if (Constant *OpC = dyn_cast<Constant>(Op))
5224         Op = ConstantExpr::getMul(OpC, Scale);
5225       else    // We'll let instcombine(mul) convert this to a shl if possible.
5226         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5227                                                   GEP->getName()+".idx"), I);
5228     }
5229
5230     // Emit an add instruction.
5231     if (isa<Constant>(Op) && isa<Constant>(Result))
5232       Result = ConstantExpr::getAdd(cast<Constant>(Op),
5233                                     cast<Constant>(Result));
5234     else
5235       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5236                                                   GEP->getName()+".offs"), I);
5237   }
5238   return Result;
5239 }
5240
5241
5242 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5243 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
5244 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
5245 /// complex, and scales are involved.  The above expression would also be legal
5246 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
5247 /// later form is less amenable to optimization though, and we are allowed to
5248 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5249 ///
5250 /// If we can't emit an optimized form for this expression, this returns null.
5251 /// 
5252 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5253                                           InstCombiner &IC) {
5254   TargetData &TD = IC.getTargetData();
5255   gep_type_iterator GTI = gep_type_begin(GEP);
5256
5257   // Check to see if this gep only has a single variable index.  If so, and if
5258   // any constant indices are a multiple of its scale, then we can compute this
5259   // in terms of the scale of the variable index.  For example, if the GEP
5260   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5261   // because the expression will cross zero at the same point.
5262   unsigned i, e = GEP->getNumOperands();
5263   int64_t Offset = 0;
5264   for (i = 1; i != e; ++i, ++GTI) {
5265     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5266       // Compute the aggregate offset of constant indices.
5267       if (CI->isZero()) continue;
5268
5269       // Handle a struct index, which adds its field offset to the pointer.
5270       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5271         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5272       } else {
5273         uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
5274         Offset += Size*CI->getSExtValue();
5275       }
5276     } else {
5277       // Found our variable index.
5278       break;
5279     }
5280   }
5281   
5282   // If there are no variable indices, we must have a constant offset, just
5283   // evaluate it the general way.
5284   if (i == e) return 0;
5285   
5286   Value *VariableIdx = GEP->getOperand(i);
5287   // Determine the scale factor of the variable element.  For example, this is
5288   // 4 if the variable index is into an array of i32.
5289   uint64_t VariableScale = TD.getTypePaddedSize(GTI.getIndexedType());
5290   
5291   // Verify that there are no other variable indices.  If so, emit the hard way.
5292   for (++i, ++GTI; i != e; ++i, ++GTI) {
5293     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5294     if (!CI) return 0;
5295    
5296     // Compute the aggregate offset of constant indices.
5297     if (CI->isZero()) continue;
5298     
5299     // Handle a struct index, which adds its field offset to the pointer.
5300     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5301       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5302     } else {
5303       uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
5304       Offset += Size*CI->getSExtValue();
5305     }
5306   }
5307   
5308   // Okay, we know we have a single variable index, which must be a
5309   // pointer/array/vector index.  If there is no offset, life is simple, return
5310   // the index.
5311   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5312   if (Offset == 0) {
5313     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5314     // we don't need to bother extending: the extension won't affect where the
5315     // computation crosses zero.
5316     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5317       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5318                                   VariableIdx->getNameStart(), &I);
5319     return VariableIdx;
5320   }
5321   
5322   // Otherwise, there is an index.  The computation we will do will be modulo
5323   // the pointer size, so get it.
5324   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5325   
5326   Offset &= PtrSizeMask;
5327   VariableScale &= PtrSizeMask;
5328
5329   // To do this transformation, any constant index must be a multiple of the
5330   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5331   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5332   // multiple of the variable scale.
5333   int64_t NewOffs = Offset / (int64_t)VariableScale;
5334   if (Offset != NewOffs*(int64_t)VariableScale)
5335     return 0;
5336
5337   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5338   const Type *IntPtrTy = TD.getIntPtrType();
5339   if (VariableIdx->getType() != IntPtrTy)
5340     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5341                                               true /*SExt*/, 
5342                                               VariableIdx->getNameStart(), &I);
5343   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5344   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5345 }
5346
5347
5348 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5349 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5350 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5351                                        ICmpInst::Predicate Cond,
5352                                        Instruction &I) {
5353   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5354
5355   // Look through bitcasts.
5356   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5357     RHS = BCI->getOperand(0);
5358
5359   Value *PtrBase = GEPLHS->getOperand(0);
5360   if (PtrBase == RHS) {
5361     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5362     // This transformation (ignoring the base and scales) is valid because we
5363     // know pointers can't overflow.  See if we can output an optimized form.
5364     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5365     
5366     // If not, synthesize the offset the hard way.
5367     if (Offset == 0)
5368       Offset = EmitGEPOffset(GEPLHS, I, *this);
5369     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5370                         Constant::getNullValue(Offset->getType()));
5371   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5372     // If the base pointers are different, but the indices are the same, just
5373     // compare the base pointer.
5374     if (PtrBase != GEPRHS->getOperand(0)) {
5375       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5376       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5377                         GEPRHS->getOperand(0)->getType();
5378       if (IndicesTheSame)
5379         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5380           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5381             IndicesTheSame = false;
5382             break;
5383           }
5384
5385       // If all indices are the same, just compare the base pointers.
5386       if (IndicesTheSame)
5387         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
5388                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5389
5390       // Otherwise, the base pointers are different and the indices are
5391       // different, bail out.
5392       return 0;
5393     }
5394
5395     // If one of the GEPs has all zero indices, recurse.
5396     bool AllZeros = true;
5397     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5398       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5399           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5400         AllZeros = false;
5401         break;
5402       }
5403     if (AllZeros)
5404       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5405                           ICmpInst::getSwappedPredicate(Cond), I);
5406
5407     // If the other GEP has all zero indices, recurse.
5408     AllZeros = true;
5409     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5410       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5411           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5412         AllZeros = false;
5413         break;
5414       }
5415     if (AllZeros)
5416       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5417
5418     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5419       // If the GEPs only differ by one index, compare it.
5420       unsigned NumDifferences = 0;  // Keep track of # differences.
5421       unsigned DiffOperand = 0;     // The operand that differs.
5422       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5423         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5424           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5425                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5426             // Irreconcilable differences.
5427             NumDifferences = 2;
5428             break;
5429           } else {
5430             if (NumDifferences++) break;
5431             DiffOperand = i;
5432           }
5433         }
5434
5435       if (NumDifferences == 0)   // SAME GEP?
5436         return ReplaceInstUsesWith(I, // No comparison is needed here.
5437                                    ConstantInt::get(Type::Int1Ty,
5438                                              ICmpInst::isTrueWhenEqual(Cond)));
5439
5440       else if (NumDifferences == 1) {
5441         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5442         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5443         // Make sure we do a signed comparison here.
5444         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5445       }
5446     }
5447
5448     // Only lower this if the icmp is the only user of the GEP or if we expect
5449     // the result to fold to a constant!
5450     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5451         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5452       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5453       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5454       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5455       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5456     }
5457   }
5458   return 0;
5459 }
5460
5461 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5462 ///
5463 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5464                                                 Instruction *LHSI,
5465                                                 Constant *RHSC) {
5466   if (!isa<ConstantFP>(RHSC)) return 0;
5467   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5468   
5469   // Get the width of the mantissa.  We don't want to hack on conversions that
5470   // might lose information from the integer, e.g. "i64 -> float"
5471   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5472   if (MantissaWidth == -1) return 0;  // Unknown.
5473   
5474   // Check to see that the input is converted from an integer type that is small
5475   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5476   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5477   unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5478   
5479   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5480   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5481   if (LHSUnsigned)
5482     ++InputSize;
5483   
5484   // If the conversion would lose info, don't hack on this.
5485   if ((int)InputSize > MantissaWidth)
5486     return 0;
5487   
5488   // Otherwise, we can potentially simplify the comparison.  We know that it
5489   // will always come through as an integer value and we know the constant is
5490   // not a NAN (it would have been previously simplified).
5491   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5492   
5493   ICmpInst::Predicate Pred;
5494   switch (I.getPredicate()) {
5495   default: assert(0 && "Unexpected predicate!");
5496   case FCmpInst::FCMP_UEQ:
5497   case FCmpInst::FCMP_OEQ:
5498     Pred = ICmpInst::ICMP_EQ;
5499     break;
5500   case FCmpInst::FCMP_UGT:
5501   case FCmpInst::FCMP_OGT:
5502     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5503     break;
5504   case FCmpInst::FCMP_UGE:
5505   case FCmpInst::FCMP_OGE:
5506     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5507     break;
5508   case FCmpInst::FCMP_ULT:
5509   case FCmpInst::FCMP_OLT:
5510     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5511     break;
5512   case FCmpInst::FCMP_ULE:
5513   case FCmpInst::FCMP_OLE:
5514     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5515     break;
5516   case FCmpInst::FCMP_UNE:
5517   case FCmpInst::FCMP_ONE:
5518     Pred = ICmpInst::ICMP_NE;
5519     break;
5520   case FCmpInst::FCMP_ORD:
5521     return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5522   case FCmpInst::FCMP_UNO:
5523     return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5524   }
5525   
5526   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5527   
5528   // Now we know that the APFloat is a normal number, zero or inf.
5529   
5530   // See if the FP constant is too large for the integer.  For example,
5531   // comparing an i8 to 300.0.
5532   unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5533   
5534   if (!LHSUnsigned) {
5535     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5536     // and large values.
5537     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5538     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5539                           APFloat::rmNearestTiesToEven);
5540     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5541       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5542           Pred == ICmpInst::ICMP_SLE)
5543         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5544       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5545     }
5546   } else {
5547     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5548     // +INF and large values.
5549     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5550     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5551                           APFloat::rmNearestTiesToEven);
5552     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5553       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5554           Pred == ICmpInst::ICMP_ULE)
5555         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5556       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5557     }
5558   }
5559   
5560   if (!LHSUnsigned) {
5561     // See if the RHS value is < SignedMin.
5562     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5563     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5564                           APFloat::rmNearestTiesToEven);
5565     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5566       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5567           Pred == ICmpInst::ICMP_SGE)
5568         return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5569       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5570     }
5571   }
5572
5573   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5574   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5575   // casting the FP value to the integer value and back, checking for equality.
5576   // Don't do this for zero, because -0.0 is not fractional.
5577   Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5578   if (!RHS.isZero() &&
5579       ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5580     // If we had a comparison against a fractional value, we have to adjust the
5581     // compare predicate and sometimes the value.  RHSC is rounded towards zero
5582     // at this point.
5583     switch (Pred) {
5584     default: assert(0 && "Unexpected integer comparison!");
5585     case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5586       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5587     case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5588       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5589     case ICmpInst::ICMP_ULE:
5590       // (float)int <= 4.4   --> int <= 4
5591       // (float)int <= -4.4  --> false
5592       if (RHS.isNegative())
5593         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5594       break;
5595     case ICmpInst::ICMP_SLE:
5596       // (float)int <= 4.4   --> int <= 4
5597       // (float)int <= -4.4  --> int < -4
5598       if (RHS.isNegative())
5599         Pred = ICmpInst::ICMP_SLT;
5600       break;
5601     case ICmpInst::ICMP_ULT:
5602       // (float)int < -4.4   --> false
5603       // (float)int < 4.4    --> int <= 4
5604       if (RHS.isNegative())
5605         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5606       Pred = ICmpInst::ICMP_ULE;
5607       break;
5608     case ICmpInst::ICMP_SLT:
5609       // (float)int < -4.4   --> int < -4
5610       // (float)int < 4.4    --> int <= 4
5611       if (!RHS.isNegative())
5612         Pred = ICmpInst::ICMP_SLE;
5613       break;
5614     case ICmpInst::ICMP_UGT:
5615       // (float)int > 4.4    --> int > 4
5616       // (float)int > -4.4   --> true
5617       if (RHS.isNegative())
5618         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5619       break;
5620     case ICmpInst::ICMP_SGT:
5621       // (float)int > 4.4    --> int > 4
5622       // (float)int > -4.4   --> int >= -4
5623       if (RHS.isNegative())
5624         Pred = ICmpInst::ICMP_SGE;
5625       break;
5626     case ICmpInst::ICMP_UGE:
5627       // (float)int >= -4.4   --> true
5628       // (float)int >= 4.4    --> int > 4
5629       if (!RHS.isNegative())
5630         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5631       Pred = ICmpInst::ICMP_UGT;
5632       break;
5633     case ICmpInst::ICMP_SGE:
5634       // (float)int >= -4.4   --> int >= -4
5635       // (float)int >= 4.4    --> int > 4
5636       if (!RHS.isNegative())
5637         Pred = ICmpInst::ICMP_SGT;
5638       break;
5639     }
5640   }
5641
5642   // Lower this FP comparison into an appropriate integer version of the
5643   // comparison.
5644   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5645 }
5646
5647 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5648   bool Changed = SimplifyCompare(I);
5649   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5650
5651   // Fold trivial predicates.
5652   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5653     return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5654   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5655     return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5656   
5657   // Simplify 'fcmp pred X, X'
5658   if (Op0 == Op1) {
5659     switch (I.getPredicate()) {
5660     default: assert(0 && "Unknown predicate!");
5661     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5662     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5663     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5664       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5665     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5666     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5667     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5668       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5669       
5670     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5671     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5672     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5673     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5674       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5675       I.setPredicate(FCmpInst::FCMP_UNO);
5676       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5677       return &I;
5678       
5679     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5680     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5681     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5682     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5683       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5684       I.setPredicate(FCmpInst::FCMP_ORD);
5685       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5686       return &I;
5687     }
5688   }
5689     
5690   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5691     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5692
5693   // Handle fcmp with constant RHS
5694   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5695     // If the constant is a nan, see if we can fold the comparison based on it.
5696     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5697       if (CFP->getValueAPF().isNaN()) {
5698         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5699           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5700         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5701                "Comparison must be either ordered or unordered!");
5702         // True if unordered.
5703         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5704       }
5705     }
5706     
5707     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5708       switch (LHSI->getOpcode()) {
5709       case Instruction::PHI:
5710         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5711         // block.  If in the same block, we're encouraging jump threading.  If
5712         // not, we are just pessimizing the code by making an i1 phi.
5713         if (LHSI->getParent() == I.getParent())
5714           if (Instruction *NV = FoldOpIntoPhi(I))
5715             return NV;
5716         break;
5717       case Instruction::SIToFP:
5718       case Instruction::UIToFP:
5719         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5720           return NV;
5721         break;
5722       case Instruction::Select:
5723         // If either operand of the select is a constant, we can fold the
5724         // comparison into the select arms, which will cause one to be
5725         // constant folded and the select turned into a bitwise or.
5726         Value *Op1 = 0, *Op2 = 0;
5727         if (LHSI->hasOneUse()) {
5728           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5729             // Fold the known value into the constant operand.
5730             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5731             // Insert a new FCmp of the other select operand.
5732             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5733                                                       LHSI->getOperand(2), RHSC,
5734                                                       I.getName()), I);
5735           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5736             // Fold the known value into the constant operand.
5737             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5738             // Insert a new FCmp of the other select operand.
5739             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5740                                                       LHSI->getOperand(1), RHSC,
5741                                                       I.getName()), I);
5742           }
5743         }
5744
5745         if (Op1)
5746           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5747         break;
5748       }
5749   }
5750
5751   return Changed ? &I : 0;
5752 }
5753
5754 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5755   bool Changed = SimplifyCompare(I);
5756   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5757   const Type *Ty = Op0->getType();
5758
5759   // icmp X, X
5760   if (Op0 == Op1)
5761     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5762                                                    I.isTrueWhenEqual()));
5763
5764   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5765     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5766   
5767   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5768   // addresses never equal each other!  We already know that Op0 != Op1.
5769   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5770        isa<ConstantPointerNull>(Op0)) &&
5771       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5772        isa<ConstantPointerNull>(Op1)))
5773     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5774                                                    !I.isTrueWhenEqual()));
5775
5776   // icmp's with boolean values can always be turned into bitwise operations
5777   if (Ty == Type::Int1Ty) {
5778     switch (I.getPredicate()) {
5779     default: assert(0 && "Invalid icmp instruction!");
5780     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5781       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5782       InsertNewInstBefore(Xor, I);
5783       return BinaryOperator::CreateNot(Xor);
5784     }
5785     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5786       return BinaryOperator::CreateXor(Op0, Op1);
5787
5788     case ICmpInst::ICMP_UGT:
5789       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5790       // FALL THROUGH
5791     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5792       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5793       InsertNewInstBefore(Not, I);
5794       return BinaryOperator::CreateAnd(Not, Op1);
5795     }
5796     case ICmpInst::ICMP_SGT:
5797       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5798       // FALL THROUGH
5799     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5800       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5801       InsertNewInstBefore(Not, I);
5802       return BinaryOperator::CreateAnd(Not, Op0);
5803     }
5804     case ICmpInst::ICMP_UGE:
5805       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
5806       // FALL THROUGH
5807     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
5808       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5809       InsertNewInstBefore(Not, I);
5810       return BinaryOperator::CreateOr(Not, Op1);
5811     }
5812     case ICmpInst::ICMP_SGE:
5813       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
5814       // FALL THROUGH
5815     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
5816       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5817       InsertNewInstBefore(Not, I);
5818       return BinaryOperator::CreateOr(Not, Op0);
5819     }
5820     }
5821   }
5822
5823   // See if we are doing a comparison with a constant.
5824   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5825     Value *A = 0, *B = 0;
5826     
5827     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5828     if (I.isEquality() && CI->isNullValue() &&
5829         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5830       // (icmp cond A B) if cond is equality
5831       return new ICmpInst(I.getPredicate(), A, B);
5832     }
5833     
5834     // If we have an icmp le or icmp ge instruction, turn it into the
5835     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
5836     // them being folded in the code below.
5837     switch (I.getPredicate()) {
5838     default: break;
5839     case ICmpInst::ICMP_ULE:
5840       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5841         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5842       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5843     case ICmpInst::ICMP_SLE:
5844       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5845         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5846       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5847     case ICmpInst::ICMP_UGE:
5848       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5849         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5850       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5851     case ICmpInst::ICMP_SGE:
5852       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5853         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5854       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5855     }
5856     
5857     // See if we can fold the comparison based on range information we can get
5858     // by checking whether bits are known to be zero or one in the input.
5859     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5860     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5861     
5862     // If this comparison is a normal comparison, it demands all
5863     // bits, if it is a sign bit comparison, it only demands the sign bit.
5864     bool UnusedBit;
5865     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5866     
5867     if (SimplifyDemandedBits(I.getOperandUse(0), 
5868                              isSignBit ? APInt::getSignBit(BitWidth)
5869                                        : APInt::getAllOnesValue(BitWidth),
5870                              KnownZero, KnownOne, 0))
5871       return &I;
5872         
5873     // Given the known and unknown bits, compute a range that the LHS could be
5874     // in.  Compute the Min, Max and RHS values based on the known bits. For the
5875     // EQ and NE we use unsigned values.
5876     APInt Min(BitWidth, 0), Max(BitWidth, 0);
5877     if (ICmpInst::isSignedPredicate(I.getPredicate()))
5878       ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5879     else
5880       ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5881     
5882     // If Min and Max are known to be the same, then SimplifyDemandedBits
5883     // figured out that the LHS is a constant.  Just constant fold this now so
5884     // that code below can assume that Min != Max.
5885     if (Min == Max)
5886       return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5887                                                           ConstantInt::get(Min),
5888                                                           CI));
5889     
5890     // Based on the range information we know about the LHS, see if we can
5891     // simplify this comparison.  For example, (x&4) < 8  is always true.
5892     const APInt &RHSVal = CI->getValue();
5893     switch (I.getPredicate()) {  // LE/GE have been folded already.
5894     default: assert(0 && "Unknown icmp opcode!");
5895     case ICmpInst::ICMP_EQ:
5896       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5897         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5898       break;
5899     case ICmpInst::ICMP_NE:
5900       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5901         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5902       break;
5903     case ICmpInst::ICMP_ULT:
5904       if (Max.ult(RHSVal))                    // A <u C -> true iff max(A) < C
5905         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5906       if (Min.uge(RHSVal))                    // A <u C -> false iff min(A) >= C
5907         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5908       if (RHSVal == Max)                      // A <u MAX -> A != MAX
5909         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5910       if (RHSVal == Min+1)                    // A <u MIN+1 -> A == MIN
5911         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5912         
5913       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
5914       if (CI->isMinValue(true))
5915         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5916                             ConstantInt::getAllOnesValue(Op0->getType()));
5917       break;
5918     case ICmpInst::ICMP_UGT:
5919       if (Min.ugt(RHSVal))                    // A >u C -> true iff min(A) > C
5920         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5921       if (Max.ule(RHSVal))                    // A >u C -> false iff max(A) <= C
5922         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5923         
5924       if (RHSVal == Min)                      // A >u MIN -> A != MIN
5925         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5926       if (RHSVal == Max-1)                    // A >u MAX-1 -> A == MAX
5927         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5928       
5929       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
5930       if (CI->isMaxValue(true))
5931         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5932                             ConstantInt::getNullValue(Op0->getType()));
5933       break;
5934     case ICmpInst::ICMP_SLT:
5935       if (Max.slt(RHSVal))                    // A <s C -> true iff max(A) < C
5936         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5937       if (Min.sge(RHSVal))                    // A <s C -> false iff min(A) >= C
5938         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5939       if (RHSVal == Max)                      // A <s MAX -> A != MAX
5940         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5941       if (RHSVal == Min+1)                    // A <s MIN+1 -> A == MIN
5942         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5943       break;
5944     case ICmpInst::ICMP_SGT: 
5945       if (Min.sgt(RHSVal))                    // A >s C -> true iff min(A) > C
5946         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5947       if (Max.sle(RHSVal))                    // A >s C -> false iff max(A) <= C
5948         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5949         
5950       if (RHSVal == Min)                      // A >s MIN -> A != MIN
5951         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5952       if (RHSVal == Max-1)                    // A >s MAX-1 -> A == MAX
5953         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5954       break;
5955     }
5956   }
5957
5958   // Test if the ICmpInst instruction is used exclusively by a select as
5959   // part of a minimum or maximum operation. If so, refrain from doing
5960   // any other folding. This helps out other analyses which understand
5961   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5962   // and CodeGen. And in this case, at least one of the comparison
5963   // operands has at least one user besides the compare (the select),
5964   // which would often largely negate the benefit of folding anyway.
5965   if (I.hasOneUse())
5966     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
5967       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
5968           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
5969         return 0;
5970
5971   // See if we are doing a comparison between a constant and an instruction that
5972   // can be folded into the comparison.
5973   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5974     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5975     // instruction, see if that instruction also has constants so that the 
5976     // instruction can be folded into the icmp 
5977     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5978       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5979         return Res;
5980   }
5981
5982   // Handle icmp with constant (but not simple integer constant) RHS
5983   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5984     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5985       switch (LHSI->getOpcode()) {
5986       case Instruction::GetElementPtr:
5987         if (RHSC->isNullValue()) {
5988           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5989           bool isAllZeros = true;
5990           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5991             if (!isa<Constant>(LHSI->getOperand(i)) ||
5992                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5993               isAllZeros = false;
5994               break;
5995             }
5996           if (isAllZeros)
5997             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5998                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5999         }
6000         break;
6001
6002       case Instruction::PHI:
6003         // Only fold icmp into the PHI if the phi and fcmp are in the same
6004         // block.  If in the same block, we're encouraging jump threading.  If
6005         // not, we are just pessimizing the code by making an i1 phi.
6006         if (LHSI->getParent() == I.getParent())
6007           if (Instruction *NV = FoldOpIntoPhi(I))
6008             return NV;
6009         break;
6010       case Instruction::Select: {
6011         // If either operand of the select is a constant, we can fold the
6012         // comparison into the select arms, which will cause one to be
6013         // constant folded and the select turned into a bitwise or.
6014         Value *Op1 = 0, *Op2 = 0;
6015         if (LHSI->hasOneUse()) {
6016           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6017             // Fold the known value into the constant operand.
6018             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6019             // Insert a new ICmp of the other select operand.
6020             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6021                                                    LHSI->getOperand(2), RHSC,
6022                                                    I.getName()), I);
6023           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6024             // Fold the known value into the constant operand.
6025             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6026             // Insert a new ICmp of the other select operand.
6027             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6028                                                    LHSI->getOperand(1), RHSC,
6029                                                    I.getName()), I);
6030           }
6031         }
6032
6033         if (Op1)
6034           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6035         break;
6036       }
6037       case Instruction::Malloc:
6038         // If we have (malloc != null), and if the malloc has a single use, we
6039         // can assume it is successful and remove the malloc.
6040         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6041           AddToWorkList(LHSI);
6042           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
6043                                                          !I.isTrueWhenEqual()));
6044         }
6045         break;
6046       }
6047   }
6048
6049   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6050   if (User *GEP = dyn_castGetElementPtr(Op0))
6051     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6052       return NI;
6053   if (User *GEP = dyn_castGetElementPtr(Op1))
6054     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6055                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6056       return NI;
6057
6058   // Test to see if the operands of the icmp are casted versions of other
6059   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6060   // now.
6061   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6062     if (isa<PointerType>(Op0->getType()) && 
6063         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6064       // We keep moving the cast from the left operand over to the right
6065       // operand, where it can often be eliminated completely.
6066       Op0 = CI->getOperand(0);
6067
6068       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6069       // so eliminate it as well.
6070       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6071         Op1 = CI2->getOperand(0);
6072
6073       // If Op1 is a constant, we can fold the cast into the constant.
6074       if (Op0->getType() != Op1->getType()) {
6075         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6076           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6077         } else {
6078           // Otherwise, cast the RHS right before the icmp
6079           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6080         }
6081       }
6082       return new ICmpInst(I.getPredicate(), Op0, Op1);
6083     }
6084   }
6085   
6086   if (isa<CastInst>(Op0)) {
6087     // Handle the special case of: icmp (cast bool to X), <cst>
6088     // This comes up when you have code like
6089     //   int X = A < B;
6090     //   if (X) ...
6091     // For generality, we handle any zero-extension of any operand comparison
6092     // with a constant or another cast from the same type.
6093     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6094       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6095         return R;
6096   }
6097   
6098   // See if it's the same type of instruction on the left and right.
6099   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6100     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6101       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6102           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6103         switch (Op0I->getOpcode()) {
6104         default: break;
6105         case Instruction::Add:
6106         case Instruction::Sub:
6107         case Instruction::Xor:
6108           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6109             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6110                                 Op1I->getOperand(0));
6111           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6112           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6113             if (CI->getValue().isSignBit()) {
6114               ICmpInst::Predicate Pred = I.isSignedPredicate()
6115                                              ? I.getUnsignedPredicate()
6116                                              : I.getSignedPredicate();
6117               return new ICmpInst(Pred, Op0I->getOperand(0),
6118                                   Op1I->getOperand(0));
6119             }
6120             
6121             if (CI->getValue().isMaxSignedValue()) {
6122               ICmpInst::Predicate Pred = I.isSignedPredicate()
6123                                              ? I.getUnsignedPredicate()
6124                                              : I.getSignedPredicate();
6125               Pred = I.getSwappedPredicate(Pred);
6126               return new ICmpInst(Pred, Op0I->getOperand(0),
6127                                   Op1I->getOperand(0));
6128             }
6129           }
6130           break;
6131         case Instruction::Mul:
6132           if (!I.isEquality())
6133             break;
6134
6135           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6136             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6137             // Mask = -1 >> count-trailing-zeros(Cst).
6138             if (!CI->isZero() && !CI->isOne()) {
6139               const APInt &AP = CI->getValue();
6140               ConstantInt *Mask = ConstantInt::get(
6141                                       APInt::getLowBitsSet(AP.getBitWidth(),
6142                                                            AP.getBitWidth() -
6143                                                       AP.countTrailingZeros()));
6144               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6145                                                             Mask);
6146               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6147                                                             Mask);
6148               InsertNewInstBefore(And1, I);
6149               InsertNewInstBefore(And2, I);
6150               return new ICmpInst(I.getPredicate(), And1, And2);
6151             }
6152           }
6153           break;
6154         }
6155       }
6156     }
6157   }
6158   
6159   // ~x < ~y --> y < x
6160   { Value *A, *B;
6161     if (match(Op0, m_Not(m_Value(A))) &&
6162         match(Op1, m_Not(m_Value(B))))
6163       return new ICmpInst(I.getPredicate(), B, A);
6164   }
6165   
6166   if (I.isEquality()) {
6167     Value *A, *B, *C, *D;
6168     
6169     // -x == -y --> x == y
6170     if (match(Op0, m_Neg(m_Value(A))) &&
6171         match(Op1, m_Neg(m_Value(B))))
6172       return new ICmpInst(I.getPredicate(), A, B);
6173     
6174     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6175       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6176         Value *OtherVal = A == Op1 ? B : A;
6177         return new ICmpInst(I.getPredicate(), OtherVal,
6178                             Constant::getNullValue(A->getType()));
6179       }
6180
6181       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6182         // A^c1 == C^c2 --> A == C^(c1^c2)
6183         ConstantInt *C1, *C2;
6184         if (match(B, m_ConstantInt(C1)) &&
6185             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6186           Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6187           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6188           return new ICmpInst(I.getPredicate(), A,
6189                               InsertNewInstBefore(Xor, I));
6190         }
6191         
6192         // A^B == A^D -> B == D
6193         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6194         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6195         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6196         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6197       }
6198     }
6199     
6200     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6201         (A == Op0 || B == Op0)) {
6202       // A == (A^B)  ->  B == 0
6203       Value *OtherVal = A == Op0 ? B : A;
6204       return new ICmpInst(I.getPredicate(), OtherVal,
6205                           Constant::getNullValue(A->getType()));
6206     }
6207
6208     // (A-B) == A  ->  B == 0
6209     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6210       return new ICmpInst(I.getPredicate(), B, 
6211                           Constant::getNullValue(B->getType()));
6212
6213     // A == (A-B)  ->  B == 0
6214     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6215       return new ICmpInst(I.getPredicate(), B,
6216                           Constant::getNullValue(B->getType()));
6217     
6218     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6219     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6220         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6221         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6222       Value *X = 0, *Y = 0, *Z = 0;
6223       
6224       if (A == C) {
6225         X = B; Y = D; Z = A;
6226       } else if (A == D) {
6227         X = B; Y = C; Z = A;
6228       } else if (B == C) {
6229         X = A; Y = D; Z = B;
6230       } else if (B == D) {
6231         X = A; Y = C; Z = B;
6232       }
6233       
6234       if (X) {   // Build (X^Y) & Z
6235         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6236         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6237         I.setOperand(0, Op1);
6238         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6239         return &I;
6240       }
6241     }
6242   }
6243   return Changed ? &I : 0;
6244 }
6245
6246
6247 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6248 /// and CmpRHS are both known to be integer constants.
6249 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6250                                           ConstantInt *DivRHS) {
6251   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6252   const APInt &CmpRHSV = CmpRHS->getValue();
6253   
6254   // FIXME: If the operand types don't match the type of the divide 
6255   // then don't attempt this transform. The code below doesn't have the
6256   // logic to deal with a signed divide and an unsigned compare (and
6257   // vice versa). This is because (x /s C1) <s C2  produces different 
6258   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6259   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6260   // work. :(  The if statement below tests that condition and bails 
6261   // if it finds it. 
6262   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6263   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6264     return 0;
6265   if (DivRHS->isZero())
6266     return 0; // The ProdOV computation fails on divide by zero.
6267   if (DivIsSigned && DivRHS->isAllOnesValue())
6268     return 0; // The overflow computation also screws up here
6269   if (DivRHS->isOne())
6270     return 0; // Not worth bothering, and eliminates some funny cases
6271               // with INT_MIN.
6272
6273   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6274   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6275   // C2 (CI). By solving for X we can turn this into a range check 
6276   // instead of computing a divide. 
6277   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6278
6279   // Determine if the product overflows by seeing if the product is
6280   // not equal to the divide. Make sure we do the same kind of divide
6281   // as in the LHS instruction that we're folding. 
6282   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6283                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6284
6285   // Get the ICmp opcode
6286   ICmpInst::Predicate Pred = ICI.getPredicate();
6287
6288   // Figure out the interval that is being checked.  For example, a comparison
6289   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6290   // Compute this interval based on the constants involved and the signedness of
6291   // the compare/divide.  This computes a half-open interval, keeping track of
6292   // whether either value in the interval overflows.  After analysis each
6293   // overflow variable is set to 0 if it's corresponding bound variable is valid
6294   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6295   int LoOverflow = 0, HiOverflow = 0;
6296   ConstantInt *LoBound = 0, *HiBound = 0;
6297   
6298   if (!DivIsSigned) {  // udiv
6299     // e.g. X/5 op 3  --> [15, 20)
6300     LoBound = Prod;
6301     HiOverflow = LoOverflow = ProdOV;
6302     if (!HiOverflow)
6303       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
6304   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6305     if (CmpRHSV == 0) {       // (X / pos) op 0
6306       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6307       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6308       HiBound = DivRHS;
6309     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6310       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6311       HiOverflow = LoOverflow = ProdOV;
6312       if (!HiOverflow)
6313         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6314     } else {                       // (X / pos) op neg
6315       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6316       HiBound = AddOne(Prod);
6317       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6318       if (!LoOverflow) {
6319         ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6320         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6321                                      true) ? -1 : 0;
6322        }
6323     }
6324   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6325     if (CmpRHSV == 0) {       // (X / neg) op 0
6326       // e.g. X/-5 op 0  --> [-4, 5)
6327       LoBound = AddOne(DivRHS);
6328       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6329       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6330         HiOverflow = 1;            // [INTMIN+1, overflow)
6331         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6332       }
6333     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6334       // e.g. X/-5 op 3  --> [-19, -14)
6335       HiBound = AddOne(Prod);
6336       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6337       if (!LoOverflow)
6338         LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
6339     } else {                       // (X / neg) op neg
6340       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6341       LoOverflow = HiOverflow = ProdOV;
6342       if (!HiOverflow)
6343         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
6344     }
6345     
6346     // Dividing by a negative swaps the condition.  LT <-> GT
6347     Pred = ICmpInst::getSwappedPredicate(Pred);
6348   }
6349
6350   Value *X = DivI->getOperand(0);
6351   switch (Pred) {
6352   default: assert(0 && "Unhandled icmp opcode!");
6353   case ICmpInst::ICMP_EQ:
6354     if (LoOverflow && HiOverflow)
6355       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6356     else if (HiOverflow)
6357       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6358                           ICmpInst::ICMP_UGE, X, LoBound);
6359     else if (LoOverflow)
6360       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6361                           ICmpInst::ICMP_ULT, X, HiBound);
6362     else
6363       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6364   case ICmpInst::ICMP_NE:
6365     if (LoOverflow && HiOverflow)
6366       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6367     else if (HiOverflow)
6368       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6369                           ICmpInst::ICMP_ULT, X, LoBound);
6370     else if (LoOverflow)
6371       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6372                           ICmpInst::ICMP_UGE, X, HiBound);
6373     else
6374       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6375   case ICmpInst::ICMP_ULT:
6376   case ICmpInst::ICMP_SLT:
6377     if (LoOverflow == +1)   // Low bound is greater than input range.
6378       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6379     if (LoOverflow == -1)   // Low bound is less than input range.
6380       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6381     return new ICmpInst(Pred, X, LoBound);
6382   case ICmpInst::ICMP_UGT:
6383   case ICmpInst::ICMP_SGT:
6384     if (HiOverflow == +1)       // High bound greater than input range.
6385       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6386     else if (HiOverflow == -1)  // High bound less than input range.
6387       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6388     if (Pred == ICmpInst::ICMP_UGT)
6389       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6390     else
6391       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6392   }
6393 }
6394
6395
6396 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6397 ///
6398 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6399                                                           Instruction *LHSI,
6400                                                           ConstantInt *RHS) {
6401   const APInt &RHSV = RHS->getValue();
6402   
6403   switch (LHSI->getOpcode()) {
6404   case Instruction::Trunc:
6405     if (ICI.isEquality() && LHSI->hasOneUse()) {
6406       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6407       // of the high bits truncated out of x are known.
6408       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6409              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6410       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6411       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6412       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6413       
6414       // If all the high bits are known, we can do this xform.
6415       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6416         // Pull in the high bits from known-ones set.
6417         APInt NewRHS(RHS->getValue());
6418         NewRHS.zext(SrcBits);
6419         NewRHS |= KnownOne;
6420         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6421                             ConstantInt::get(NewRHS));
6422       }
6423     }
6424     break;
6425       
6426   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6427     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6428       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6429       // fold the xor.
6430       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6431           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6432         Value *CompareVal = LHSI->getOperand(0);
6433         
6434         // If the sign bit of the XorCST is not set, there is no change to
6435         // the operation, just stop using the Xor.
6436         if (!XorCST->getValue().isNegative()) {
6437           ICI.setOperand(0, CompareVal);
6438           AddToWorkList(LHSI);
6439           return &ICI;
6440         }
6441         
6442         // Was the old condition true if the operand is positive?
6443         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6444         
6445         // If so, the new one isn't.
6446         isTrueIfPositive ^= true;
6447         
6448         if (isTrueIfPositive)
6449           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6450         else
6451           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6452       }
6453
6454       if (LHSI->hasOneUse()) {
6455         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6456         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6457           const APInt &SignBit = XorCST->getValue();
6458           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6459                                          ? ICI.getUnsignedPredicate()
6460                                          : ICI.getSignedPredicate();
6461           return new ICmpInst(Pred, LHSI->getOperand(0),
6462                               ConstantInt::get(RHSV ^ SignBit));
6463         }
6464
6465         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6466         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6467           const APInt &NotSignBit = XorCST->getValue();
6468           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6469                                          ? ICI.getUnsignedPredicate()
6470                                          : ICI.getSignedPredicate();
6471           Pred = ICI.getSwappedPredicate(Pred);
6472           return new ICmpInst(Pred, LHSI->getOperand(0),
6473                               ConstantInt::get(RHSV ^ NotSignBit));
6474         }
6475       }
6476     }
6477     break;
6478   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6479     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6480         LHSI->getOperand(0)->hasOneUse()) {
6481       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6482       
6483       // If the LHS is an AND of a truncating cast, we can widen the
6484       // and/compare to be the input width without changing the value
6485       // produced, eliminating a cast.
6486       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6487         // We can do this transformation if either the AND constant does not
6488         // have its sign bit set or if it is an equality comparison. 
6489         // Extending a relational comparison when we're checking the sign
6490         // bit would not work.
6491         if (Cast->hasOneUse() &&
6492             (ICI.isEquality() ||
6493              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6494           uint32_t BitWidth = 
6495             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6496           APInt NewCST = AndCST->getValue();
6497           NewCST.zext(BitWidth);
6498           APInt NewCI = RHSV;
6499           NewCI.zext(BitWidth);
6500           Instruction *NewAnd = 
6501             BinaryOperator::CreateAnd(Cast->getOperand(0),
6502                                       ConstantInt::get(NewCST),LHSI->getName());
6503           InsertNewInstBefore(NewAnd, ICI);
6504           return new ICmpInst(ICI.getPredicate(), NewAnd,
6505                               ConstantInt::get(NewCI));
6506         }
6507       }
6508       
6509       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6510       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6511       // happens a LOT in code produced by the C front-end, for bitfield
6512       // access.
6513       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6514       if (Shift && !Shift->isShift())
6515         Shift = 0;
6516       
6517       ConstantInt *ShAmt;
6518       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6519       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6520       const Type *AndTy = AndCST->getType();          // Type of the and.
6521       
6522       // We can fold this as long as we can't shift unknown bits
6523       // into the mask.  This can only happen with signed shift
6524       // rights, as they sign-extend.
6525       if (ShAmt) {
6526         bool CanFold = Shift->isLogicalShift();
6527         if (!CanFold) {
6528           // To test for the bad case of the signed shr, see if any
6529           // of the bits shifted in could be tested after the mask.
6530           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6531           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6532           
6533           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6534           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6535                AndCST->getValue()) == 0)
6536             CanFold = true;
6537         }
6538         
6539         if (CanFold) {
6540           Constant *NewCst;
6541           if (Shift->getOpcode() == Instruction::Shl)
6542             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6543           else
6544             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6545           
6546           // Check to see if we are shifting out any of the bits being
6547           // compared.
6548           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6549             // If we shifted bits out, the fold is not going to work out.
6550             // As a special case, check to see if this means that the
6551             // result is always true or false now.
6552             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6553               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6554             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6555               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6556           } else {
6557             ICI.setOperand(1, NewCst);
6558             Constant *NewAndCST;
6559             if (Shift->getOpcode() == Instruction::Shl)
6560               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6561             else
6562               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6563             LHSI->setOperand(1, NewAndCST);
6564             LHSI->setOperand(0, Shift->getOperand(0));
6565             AddToWorkList(Shift); // Shift is dead.
6566             AddUsesToWorkList(ICI);
6567             return &ICI;
6568           }
6569         }
6570       }
6571       
6572       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6573       // preferable because it allows the C<<Y expression to be hoisted out
6574       // of a loop if Y is invariant and X is not.
6575       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6576           ICI.isEquality() && !Shift->isArithmeticShift() &&
6577           isa<Instruction>(Shift->getOperand(0))) {
6578         // Compute C << Y.
6579         Value *NS;
6580         if (Shift->getOpcode() == Instruction::LShr) {
6581           NS = BinaryOperator::CreateShl(AndCST, 
6582                                          Shift->getOperand(1), "tmp");
6583         } else {
6584           // Insert a logical shift.
6585           NS = BinaryOperator::CreateLShr(AndCST,
6586                                           Shift->getOperand(1), "tmp");
6587         }
6588         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6589         
6590         // Compute X & (C << Y).
6591         Instruction *NewAnd = 
6592           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6593         InsertNewInstBefore(NewAnd, ICI);
6594         
6595         ICI.setOperand(0, NewAnd);
6596         return &ICI;
6597       }
6598     }
6599     break;
6600     
6601   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6602     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6603     if (!ShAmt) break;
6604     
6605     uint32_t TypeBits = RHSV.getBitWidth();
6606     
6607     // Check that the shift amount is in range.  If not, don't perform
6608     // undefined shifts.  When the shift is visited it will be
6609     // simplified.
6610     if (ShAmt->uge(TypeBits))
6611       break;
6612     
6613     if (ICI.isEquality()) {
6614       // If we are comparing against bits always shifted out, the
6615       // comparison cannot succeed.
6616       Constant *Comp =
6617         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6618       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6619         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6620         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6621         return ReplaceInstUsesWith(ICI, Cst);
6622       }
6623       
6624       if (LHSI->hasOneUse()) {
6625         // Otherwise strength reduce the shift into an and.
6626         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6627         Constant *Mask =
6628           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6629         
6630         Instruction *AndI =
6631           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6632                                     Mask, LHSI->getName()+".mask");
6633         Value *And = InsertNewInstBefore(AndI, ICI);
6634         return new ICmpInst(ICI.getPredicate(), And,
6635                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
6636       }
6637     }
6638     
6639     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6640     bool TrueIfSigned = false;
6641     if (LHSI->hasOneUse() &&
6642         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6643       // (X << 31) <s 0  --> (X&1) != 0
6644       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6645                                            (TypeBits-ShAmt->getZExtValue()-1));
6646       Instruction *AndI =
6647         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6648                                   Mask, LHSI->getName()+".mask");
6649       Value *And = InsertNewInstBefore(AndI, ICI);
6650       
6651       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6652                           And, Constant::getNullValue(And->getType()));
6653     }
6654     break;
6655   }
6656     
6657   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6658   case Instruction::AShr: {
6659     // Only handle equality comparisons of shift-by-constant.
6660     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6661     if (!ShAmt || !ICI.isEquality()) break;
6662
6663     // Check that the shift amount is in range.  If not, don't perform
6664     // undefined shifts.  When the shift is visited it will be
6665     // simplified.
6666     uint32_t TypeBits = RHSV.getBitWidth();
6667     if (ShAmt->uge(TypeBits))
6668       break;
6669     
6670     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6671       
6672     // If we are comparing against bits always shifted out, the
6673     // comparison cannot succeed.
6674     APInt Comp = RHSV << ShAmtVal;
6675     if (LHSI->getOpcode() == Instruction::LShr)
6676       Comp = Comp.lshr(ShAmtVal);
6677     else
6678       Comp = Comp.ashr(ShAmtVal);
6679     
6680     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6681       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6682       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6683       return ReplaceInstUsesWith(ICI, Cst);
6684     }
6685     
6686     // Otherwise, check to see if the bits shifted out are known to be zero.
6687     // If so, we can compare against the unshifted value:
6688     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6689     if (LHSI->hasOneUse() &&
6690         MaskedValueIsZero(LHSI->getOperand(0), 
6691                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6692       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6693                           ConstantExpr::getShl(RHS, ShAmt));
6694     }
6695       
6696     if (LHSI->hasOneUse()) {
6697       // Otherwise strength reduce the shift into an and.
6698       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6699       Constant *Mask = ConstantInt::get(Val);
6700       
6701       Instruction *AndI =
6702         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6703                                   Mask, LHSI->getName()+".mask");
6704       Value *And = InsertNewInstBefore(AndI, ICI);
6705       return new ICmpInst(ICI.getPredicate(), And,
6706                           ConstantExpr::getShl(RHS, ShAmt));
6707     }
6708     break;
6709   }
6710     
6711   case Instruction::SDiv:
6712   case Instruction::UDiv:
6713     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6714     // Fold this div into the comparison, producing a range check. 
6715     // Determine, based on the divide type, what the range is being 
6716     // checked.  If there is an overflow on the low or high side, remember 
6717     // it, otherwise compute the range [low, hi) bounding the new value.
6718     // See: InsertRangeTest above for the kinds of replacements possible.
6719     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6720       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6721                                           DivRHS))
6722         return R;
6723     break;
6724
6725   case Instruction::Add:
6726     // Fold: icmp pred (add, X, C1), C2
6727
6728     if (!ICI.isEquality()) {
6729       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6730       if (!LHSC) break;
6731       const APInt &LHSV = LHSC->getValue();
6732
6733       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6734                             .subtract(LHSV);
6735
6736       if (ICI.isSignedPredicate()) {
6737         if (CR.getLower().isSignBit()) {
6738           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6739                               ConstantInt::get(CR.getUpper()));
6740         } else if (CR.getUpper().isSignBit()) {
6741           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6742                               ConstantInt::get(CR.getLower()));
6743         }
6744       } else {
6745         if (CR.getLower().isMinValue()) {
6746           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6747                               ConstantInt::get(CR.getUpper()));
6748         } else if (CR.getUpper().isMinValue()) {
6749           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6750                               ConstantInt::get(CR.getLower()));
6751         }
6752       }
6753     }
6754     break;
6755   }
6756   
6757   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6758   if (ICI.isEquality()) {
6759     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6760     
6761     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6762     // the second operand is a constant, simplify a bit.
6763     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6764       switch (BO->getOpcode()) {
6765       case Instruction::SRem:
6766         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6767         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6768           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6769           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6770             Instruction *NewRem =
6771               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6772                                          BO->getName());
6773             InsertNewInstBefore(NewRem, ICI);
6774             return new ICmpInst(ICI.getPredicate(), NewRem, 
6775                                 Constant::getNullValue(BO->getType()));
6776           }
6777         }
6778         break;
6779       case Instruction::Add:
6780         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6781         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6782           if (BO->hasOneUse())
6783             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6784                                 Subtract(RHS, BOp1C));
6785         } else if (RHSV == 0) {
6786           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6787           // efficiently invertible, or if the add has just this one use.
6788           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6789           
6790           if (Value *NegVal = dyn_castNegVal(BOp1))
6791             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6792           else if (Value *NegVal = dyn_castNegVal(BOp0))
6793             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6794           else if (BO->hasOneUse()) {
6795             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6796             InsertNewInstBefore(Neg, ICI);
6797             Neg->takeName(BO);
6798             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6799           }
6800         }
6801         break;
6802       case Instruction::Xor:
6803         // For the xor case, we can xor two constants together, eliminating
6804         // the explicit xor.
6805         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6806           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6807                               ConstantExpr::getXor(RHS, BOC));
6808         
6809         // FALLTHROUGH
6810       case Instruction::Sub:
6811         // Replace (([sub|xor] A, B) != 0) with (A != B)
6812         if (RHSV == 0)
6813           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6814                               BO->getOperand(1));
6815         break;
6816         
6817       case Instruction::Or:
6818         // If bits are being or'd in that are not present in the constant we
6819         // are comparing against, then the comparison could never succeed!
6820         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6821           Constant *NotCI = ConstantExpr::getNot(RHS);
6822           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6823             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
6824                                                              isICMP_NE));
6825         }
6826         break;
6827         
6828       case Instruction::And:
6829         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6830           // If bits are being compared against that are and'd out, then the
6831           // comparison can never succeed!
6832           if ((RHSV & ~BOC->getValue()) != 0)
6833             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6834                                                              isICMP_NE));
6835           
6836           // If we have ((X & C) == C), turn it into ((X & C) != 0).
6837           if (RHS == BOC && RHSV.isPowerOf2())
6838             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6839                                 ICmpInst::ICMP_NE, LHSI,
6840                                 Constant::getNullValue(RHS->getType()));
6841           
6842           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6843           if (BOC->getValue().isSignBit()) {
6844             Value *X = BO->getOperand(0);
6845             Constant *Zero = Constant::getNullValue(X->getType());
6846             ICmpInst::Predicate pred = isICMP_NE ? 
6847               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6848             return new ICmpInst(pred, X, Zero);
6849           }
6850           
6851           // ((X & ~7) == 0) --> X < 8
6852           if (RHSV == 0 && isHighOnes(BOC)) {
6853             Value *X = BO->getOperand(0);
6854             Constant *NegX = ConstantExpr::getNeg(BOC);
6855             ICmpInst::Predicate pred = isICMP_NE ? 
6856               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6857             return new ICmpInst(pred, X, NegX);
6858           }
6859         }
6860       default: break;
6861       }
6862     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6863       // Handle icmp {eq|ne} <intrinsic>, intcst.
6864       if (II->getIntrinsicID() == Intrinsic::bswap) {
6865         AddToWorkList(II);
6866         ICI.setOperand(0, II->getOperand(1));
6867         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6868         return &ICI;
6869       }
6870     }
6871   }
6872   return 0;
6873 }
6874
6875 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6876 /// We only handle extending casts so far.
6877 ///
6878 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6879   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6880   Value *LHSCIOp        = LHSCI->getOperand(0);
6881   const Type *SrcTy     = LHSCIOp->getType();
6882   const Type *DestTy    = LHSCI->getType();
6883   Value *RHSCIOp;
6884
6885   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
6886   // integer type is the same size as the pointer type.
6887   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6888       getTargetData().getPointerSizeInBits() == 
6889          cast<IntegerType>(DestTy)->getBitWidth()) {
6890     Value *RHSOp = 0;
6891     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6892       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6893     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6894       RHSOp = RHSC->getOperand(0);
6895       // If the pointer types don't match, insert a bitcast.
6896       if (LHSCIOp->getType() != RHSOp->getType())
6897         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6898     }
6899
6900     if (RHSOp)
6901       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6902   }
6903   
6904   // The code below only handles extension cast instructions, so far.
6905   // Enforce this.
6906   if (LHSCI->getOpcode() != Instruction::ZExt &&
6907       LHSCI->getOpcode() != Instruction::SExt)
6908     return 0;
6909
6910   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6911   bool isSignedCmp = ICI.isSignedPredicate();
6912
6913   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6914     // Not an extension from the same type?
6915     RHSCIOp = CI->getOperand(0);
6916     if (RHSCIOp->getType() != LHSCIOp->getType()) 
6917       return 0;
6918     
6919     // If the signedness of the two casts doesn't agree (i.e. one is a sext
6920     // and the other is a zext), then we can't handle this.
6921     if (CI->getOpcode() != LHSCI->getOpcode())
6922       return 0;
6923
6924     // Deal with equality cases early.
6925     if (ICI.isEquality())
6926       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6927
6928     // A signed comparison of sign extended values simplifies into a
6929     // signed comparison.
6930     if (isSignedCmp && isSignedExt)
6931       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6932
6933     // The other three cases all fold into an unsigned comparison.
6934     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6935   }
6936
6937   // If we aren't dealing with a constant on the RHS, exit early
6938   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6939   if (!CI)
6940     return 0;
6941
6942   // Compute the constant that would happen if we truncated to SrcTy then
6943   // reextended to DestTy.
6944   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6945   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6946
6947   // If the re-extended constant didn't change...
6948   if (Res2 == CI) {
6949     // Make sure that sign of the Cmp and the sign of the Cast are the same.
6950     // For example, we might have:
6951     //    %A = sext short %X to uint
6952     //    %B = icmp ugt uint %A, 1330
6953     // It is incorrect to transform this into 
6954     //    %B = icmp ugt short %X, 1330 
6955     // because %A may have negative value. 
6956     //
6957     // However, we allow this when the compare is EQ/NE, because they are
6958     // signless.
6959     if (isSignedExt == isSignedCmp || ICI.isEquality())
6960       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6961     return 0;
6962   }
6963
6964   // The re-extended constant changed so the constant cannot be represented 
6965   // in the shorter type. Consequently, we cannot emit a simple comparison.
6966
6967   // First, handle some easy cases. We know the result cannot be equal at this
6968   // point so handle the ICI.isEquality() cases
6969   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6970     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6971   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6972     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6973
6974   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6975   // should have been folded away previously and not enter in here.
6976   Value *Result;
6977   if (isSignedCmp) {
6978     // We're performing a signed comparison.
6979     if (cast<ConstantInt>(CI)->getValue().isNegative())
6980       Result = ConstantInt::getFalse();          // X < (small) --> false
6981     else
6982       Result = ConstantInt::getTrue();           // X < (large) --> true
6983   } else {
6984     // We're performing an unsigned comparison.
6985     if (isSignedExt) {
6986       // We're performing an unsigned comp with a sign extended value.
6987       // This is true if the input is >= 0. [aka >s -1]
6988       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6989       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6990                                    NegOne, ICI.getName()), ICI);
6991     } else {
6992       // Unsigned extend & unsigned compare -> always true.
6993       Result = ConstantInt::getTrue();
6994     }
6995   }
6996
6997   // Finally, return the value computed.
6998   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6999       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7000     return ReplaceInstUsesWith(ICI, Result);
7001
7002   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7003           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7004          "ICmp should be folded!");
7005   if (Constant *CI = dyn_cast<Constant>(Result))
7006     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7007   return BinaryOperator::CreateNot(Result);
7008 }
7009
7010 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7011   return commonShiftTransforms(I);
7012 }
7013
7014 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7015   return commonShiftTransforms(I);
7016 }
7017
7018 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7019   if (Instruction *R = commonShiftTransforms(I))
7020     return R;
7021   
7022   Value *Op0 = I.getOperand(0);
7023   
7024   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7025   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7026     if (CSI->isAllOnesValue())
7027       return ReplaceInstUsesWith(I, CSI);
7028   
7029   // See if we can turn a signed shr into an unsigned shr.
7030   if (!isa<VectorType>(I.getType()) &&
7031       MaskedValueIsZero(Op0,
7032                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
7033     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7034
7035   // Arithmetic shifting an all-sign-bit value is a no-op.
7036   unsigned NumSignBits = ComputeNumSignBits(Op0);
7037   if (NumSignBits == Op0->getType()->getPrimitiveSizeInBits())
7038     return ReplaceInstUsesWith(I, Op0);
7039
7040   return 0;
7041 }
7042
7043 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7044   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7045   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7046
7047   // shl X, 0 == X and shr X, 0 == X
7048   // shl 0, X == 0 and shr 0, X == 0
7049   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7050       Op0 == Constant::getNullValue(Op0->getType()))
7051     return ReplaceInstUsesWith(I, Op0);
7052   
7053   if (isa<UndefValue>(Op0)) {            
7054     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7055       return ReplaceInstUsesWith(I, Op0);
7056     else                                    // undef << X -> 0, undef >>u X -> 0
7057       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7058   }
7059   if (isa<UndefValue>(Op1)) {
7060     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7061       return ReplaceInstUsesWith(I, Op0);          
7062     else                                     // X << undef, X >>u undef -> 0
7063       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7064   }
7065
7066   // Try to fold constant and into select arguments.
7067   if (isa<Constant>(Op0))
7068     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7069       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7070         return R;
7071
7072   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7073     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7074       return Res;
7075   return 0;
7076 }
7077
7078 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7079                                                BinaryOperator &I) {
7080   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7081
7082   // See if we can simplify any instructions used by the instruction whose sole 
7083   // purpose is to compute bits we don't care about.
7084   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
7085   if (SimplifyDemandedInstructionBits(I))
7086     return &I;
7087   
7088   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
7089   // of a signed value.
7090   //
7091   if (Op1->uge(TypeBits)) {
7092     if (I.getOpcode() != Instruction::AShr)
7093       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7094     else {
7095       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7096       return &I;
7097     }
7098   }
7099   
7100   // ((X*C1) << C2) == (X * (C1 << C2))
7101   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7102     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7103       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7104         return BinaryOperator::CreateMul(BO->getOperand(0),
7105                                          ConstantExpr::getShl(BOOp, Op1));
7106   
7107   // Try to fold constant and into select arguments.
7108   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7109     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7110       return R;
7111   if (isa<PHINode>(Op0))
7112     if (Instruction *NV = FoldOpIntoPhi(I))
7113       return NV;
7114   
7115   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7116   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7117     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7118     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7119     // place.  Don't try to do this transformation in this case.  Also, we
7120     // require that the input operand is a shift-by-constant so that we have
7121     // confidence that the shifts will get folded together.  We could do this
7122     // xform in more cases, but it is unlikely to be profitable.
7123     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7124         isa<ConstantInt>(TrOp->getOperand(1))) {
7125       // Okay, we'll do this xform.  Make the shift of shift.
7126       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7127       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7128                                                 I.getName());
7129       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7130
7131       // For logical shifts, the truncation has the effect of making the high
7132       // part of the register be zeros.  Emulate this by inserting an AND to
7133       // clear the top bits as needed.  This 'and' will usually be zapped by
7134       // other xforms later if dead.
7135       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7136       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7137       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7138       
7139       // The mask we constructed says what the trunc would do if occurring
7140       // between the shifts.  We want to know the effect *after* the second
7141       // shift.  We know that it is a logical shift by a constant, so adjust the
7142       // mask as appropriate.
7143       if (I.getOpcode() == Instruction::Shl)
7144         MaskV <<= Op1->getZExtValue();
7145       else {
7146         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7147         MaskV = MaskV.lshr(Op1->getZExtValue());
7148       }
7149
7150       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
7151                                                    TI->getName());
7152       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7153
7154       // Return the value truncated to the interesting size.
7155       return new TruncInst(And, I.getType());
7156     }
7157   }
7158   
7159   if (Op0->hasOneUse()) {
7160     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7161       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7162       Value *V1, *V2;
7163       ConstantInt *CC;
7164       switch (Op0BO->getOpcode()) {
7165         default: break;
7166         case Instruction::Add:
7167         case Instruction::And:
7168         case Instruction::Or:
7169         case Instruction::Xor: {
7170           // These operators commute.
7171           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7172           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7173               match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
7174             Instruction *YS = BinaryOperator::CreateShl(
7175                                             Op0BO->getOperand(0), Op1,
7176                                             Op0BO->getName());
7177             InsertNewInstBefore(YS, I); // (Y << C)
7178             Instruction *X = 
7179               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7180                                      Op0BO->getOperand(1)->getName());
7181             InsertNewInstBefore(X, I);  // (X + (Y << C))
7182             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7183             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7184                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7185           }
7186           
7187           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7188           Value *Op0BOOp1 = Op0BO->getOperand(1);
7189           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7190               match(Op0BOOp1, 
7191                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7192                           m_ConstantInt(CC))) &&
7193               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7194             Instruction *YS = BinaryOperator::CreateShl(
7195                                                      Op0BO->getOperand(0), Op1,
7196                                                      Op0BO->getName());
7197             InsertNewInstBefore(YS, I); // (Y << C)
7198             Instruction *XM =
7199               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7200                                         V1->getName()+".mask");
7201             InsertNewInstBefore(XM, I); // X & (CC << C)
7202             
7203             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7204           }
7205         }
7206           
7207         // FALL THROUGH.
7208         case Instruction::Sub: {
7209           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7210           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7211               match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
7212             Instruction *YS = BinaryOperator::CreateShl(
7213                                                      Op0BO->getOperand(1), Op1,
7214                                                      Op0BO->getName());
7215             InsertNewInstBefore(YS, I); // (Y << C)
7216             Instruction *X =
7217               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7218                                      Op0BO->getOperand(0)->getName());
7219             InsertNewInstBefore(X, I);  // (X + (Y << C))
7220             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7221             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7222                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7223           }
7224           
7225           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7226           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7227               match(Op0BO->getOperand(0),
7228                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7229                           m_ConstantInt(CC))) && V2 == Op1 &&
7230               cast<BinaryOperator>(Op0BO->getOperand(0))
7231                   ->getOperand(0)->hasOneUse()) {
7232             Instruction *YS = BinaryOperator::CreateShl(
7233                                                      Op0BO->getOperand(1), Op1,
7234                                                      Op0BO->getName());
7235             InsertNewInstBefore(YS, I); // (Y << C)
7236             Instruction *XM =
7237               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7238                                         V1->getName()+".mask");
7239             InsertNewInstBefore(XM, I); // X & (CC << C)
7240             
7241             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7242           }
7243           
7244           break;
7245         }
7246       }
7247       
7248       
7249       // If the operand is an bitwise operator with a constant RHS, and the
7250       // shift is the only use, we can pull it out of the shift.
7251       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7252         bool isValid = true;     // Valid only for And, Or, Xor
7253         bool highBitSet = false; // Transform if high bit of constant set?
7254         
7255         switch (Op0BO->getOpcode()) {
7256           default: isValid = false; break;   // Do not perform transform!
7257           case Instruction::Add:
7258             isValid = isLeftShift;
7259             break;
7260           case Instruction::Or:
7261           case Instruction::Xor:
7262             highBitSet = false;
7263             break;
7264           case Instruction::And:
7265             highBitSet = true;
7266             break;
7267         }
7268         
7269         // If this is a signed shift right, and the high bit is modified
7270         // by the logical operation, do not perform the transformation.
7271         // The highBitSet boolean indicates the value of the high bit of
7272         // the constant which would cause it to be modified for this
7273         // operation.
7274         //
7275         if (isValid && I.getOpcode() == Instruction::AShr)
7276           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7277         
7278         if (isValid) {
7279           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7280           
7281           Instruction *NewShift =
7282             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7283           InsertNewInstBefore(NewShift, I);
7284           NewShift->takeName(Op0BO);
7285           
7286           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7287                                         NewRHS);
7288         }
7289       }
7290     }
7291   }
7292   
7293   // Find out if this is a shift of a shift by a constant.
7294   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7295   if (ShiftOp && !ShiftOp->isShift())
7296     ShiftOp = 0;
7297   
7298   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7299     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7300     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7301     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7302     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7303     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7304     Value *X = ShiftOp->getOperand(0);
7305     
7306     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7307     if (AmtSum > TypeBits)
7308       AmtSum = TypeBits;
7309     
7310     const IntegerType *Ty = cast<IntegerType>(I.getType());
7311     
7312     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7313     if (I.getOpcode() == ShiftOp->getOpcode()) {
7314       return BinaryOperator::Create(I.getOpcode(), X,
7315                                     ConstantInt::get(Ty, AmtSum));
7316     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7317                I.getOpcode() == Instruction::AShr) {
7318       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7319       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7320     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7321                I.getOpcode() == Instruction::LShr) {
7322       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7323       Instruction *Shift =
7324         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7325       InsertNewInstBefore(Shift, I);
7326
7327       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7328       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7329     }
7330     
7331     // Okay, if we get here, one shift must be left, and the other shift must be
7332     // right.  See if the amounts are equal.
7333     if (ShiftAmt1 == ShiftAmt2) {
7334       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7335       if (I.getOpcode() == Instruction::Shl) {
7336         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7337         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7338       }
7339       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7340       if (I.getOpcode() == Instruction::LShr) {
7341         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7342         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7343       }
7344       // We can simplify ((X << C) >>s C) into a trunc + sext.
7345       // NOTE: we could do this for any C, but that would make 'unusual' integer
7346       // types.  For now, just stick to ones well-supported by the code
7347       // generators.
7348       const Type *SExtType = 0;
7349       switch (Ty->getBitWidth() - ShiftAmt1) {
7350       case 1  :
7351       case 8  :
7352       case 16 :
7353       case 32 :
7354       case 64 :
7355       case 128:
7356         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7357         break;
7358       default: break;
7359       }
7360       if (SExtType) {
7361         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7362         InsertNewInstBefore(NewTrunc, I);
7363         return new SExtInst(NewTrunc, Ty);
7364       }
7365       // Otherwise, we can't handle it yet.
7366     } else if (ShiftAmt1 < ShiftAmt2) {
7367       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7368       
7369       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7370       if (I.getOpcode() == Instruction::Shl) {
7371         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7372                ShiftOp->getOpcode() == Instruction::AShr);
7373         Instruction *Shift =
7374           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7375         InsertNewInstBefore(Shift, I);
7376         
7377         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7378         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7379       }
7380       
7381       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7382       if (I.getOpcode() == Instruction::LShr) {
7383         assert(ShiftOp->getOpcode() == Instruction::Shl);
7384         Instruction *Shift =
7385           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7386         InsertNewInstBefore(Shift, I);
7387         
7388         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7389         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7390       }
7391       
7392       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7393     } else {
7394       assert(ShiftAmt2 < ShiftAmt1);
7395       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7396
7397       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7398       if (I.getOpcode() == Instruction::Shl) {
7399         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7400                ShiftOp->getOpcode() == Instruction::AShr);
7401         Instruction *Shift =
7402           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7403                                  ConstantInt::get(Ty, ShiftDiff));
7404         InsertNewInstBefore(Shift, I);
7405         
7406         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7407         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7408       }
7409       
7410       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7411       if (I.getOpcode() == Instruction::LShr) {
7412         assert(ShiftOp->getOpcode() == Instruction::Shl);
7413         Instruction *Shift =
7414           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7415         InsertNewInstBefore(Shift, I);
7416         
7417         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7418         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7419       }
7420       
7421       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7422     }
7423   }
7424   return 0;
7425 }
7426
7427
7428 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7429 /// expression.  If so, decompose it, returning some value X, such that Val is
7430 /// X*Scale+Offset.
7431 ///
7432 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7433                                         int &Offset) {
7434   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7435   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7436     Offset = CI->getZExtValue();
7437     Scale  = 0;
7438     return ConstantInt::get(Type::Int32Ty, 0);
7439   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7440     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7441       if (I->getOpcode() == Instruction::Shl) {
7442         // This is a value scaled by '1 << the shift amt'.
7443         Scale = 1U << RHS->getZExtValue();
7444         Offset = 0;
7445         return I->getOperand(0);
7446       } else if (I->getOpcode() == Instruction::Mul) {
7447         // This value is scaled by 'RHS'.
7448         Scale = RHS->getZExtValue();
7449         Offset = 0;
7450         return I->getOperand(0);
7451       } else if (I->getOpcode() == Instruction::Add) {
7452         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7453         // where C1 is divisible by C2.
7454         unsigned SubScale;
7455         Value *SubVal = 
7456           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7457         Offset += RHS->getZExtValue();
7458         Scale = SubScale;
7459         return SubVal;
7460       }
7461     }
7462   }
7463
7464   // Otherwise, we can't look past this.
7465   Scale = 1;
7466   Offset = 0;
7467   return Val;
7468 }
7469
7470
7471 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7472 /// try to eliminate the cast by moving the type information into the alloc.
7473 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7474                                                    AllocationInst &AI) {
7475   const PointerType *PTy = cast<PointerType>(CI.getType());
7476   
7477   // Remove any uses of AI that are dead.
7478   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7479   
7480   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7481     Instruction *User = cast<Instruction>(*UI++);
7482     if (isInstructionTriviallyDead(User)) {
7483       while (UI != E && *UI == User)
7484         ++UI; // If this instruction uses AI more than once, don't break UI.
7485       
7486       ++NumDeadInst;
7487       DOUT << "IC: DCE: " << *User;
7488       EraseInstFromFunction(*User);
7489     }
7490   }
7491   
7492   // Get the type really allocated and the type casted to.
7493   const Type *AllocElTy = AI.getAllocatedType();
7494   const Type *CastElTy = PTy->getElementType();
7495   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7496
7497   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7498   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7499   if (CastElTyAlign < AllocElTyAlign) return 0;
7500
7501   // If the allocation has multiple uses, only promote it if we are strictly
7502   // increasing the alignment of the resultant allocation.  If we keep it the
7503   // same, we open the door to infinite loops of various kinds.
7504   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7505
7506   uint64_t AllocElTySize = TD->getTypePaddedSize(AllocElTy);
7507   uint64_t CastElTySize = TD->getTypePaddedSize(CastElTy);
7508   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7509
7510   // See if we can satisfy the modulus by pulling a scale out of the array
7511   // size argument.
7512   unsigned ArraySizeScale;
7513   int ArrayOffset;
7514   Value *NumElements = // See if the array size is a decomposable linear expr.
7515     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7516  
7517   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7518   // do the xform.
7519   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7520       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7521
7522   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7523   Value *Amt = 0;
7524   if (Scale == 1) {
7525     Amt = NumElements;
7526   } else {
7527     // If the allocation size is constant, form a constant mul expression
7528     Amt = ConstantInt::get(Type::Int32Ty, Scale);
7529     if (isa<ConstantInt>(NumElements))
7530       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
7531     // otherwise multiply the amount and the number of elements
7532     else if (Scale != 1) {
7533       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7534       Amt = InsertNewInstBefore(Tmp, AI);
7535     }
7536   }
7537   
7538   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7539     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
7540     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7541     Amt = InsertNewInstBefore(Tmp, AI);
7542   }
7543   
7544   AllocationInst *New;
7545   if (isa<MallocInst>(AI))
7546     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7547   else
7548     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7549   InsertNewInstBefore(New, AI);
7550   New->takeName(&AI);
7551   
7552   // If the allocation has multiple uses, insert a cast and change all things
7553   // that used it to use the new cast.  This will also hack on CI, but it will
7554   // die soon.
7555   if (!AI.hasOneUse()) {
7556     AddUsesToWorkList(AI);
7557     // New is the allocation instruction, pointer typed. AI is the original
7558     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7559     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7560     InsertNewInstBefore(NewCast, AI);
7561     AI.replaceAllUsesWith(NewCast);
7562   }
7563   return ReplaceInstUsesWith(CI, New);
7564 }
7565
7566 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7567 /// and return it as type Ty without inserting any new casts and without
7568 /// changing the computed value.  This is used by code that tries to decide
7569 /// whether promoting or shrinking integer operations to wider or smaller types
7570 /// will allow us to eliminate a truncate or extend.
7571 ///
7572 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7573 /// extension operation if Ty is larger.
7574 ///
7575 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7576 /// should return true if trunc(V) can be computed by computing V in the smaller
7577 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7578 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7579 /// efficiently truncated.
7580 ///
7581 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7582 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7583 /// the final result.
7584 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7585                                               unsigned CastOpc,
7586                                               int &NumCastsRemoved){
7587   // We can always evaluate constants in another type.
7588   if (isa<ConstantInt>(V))
7589     return true;
7590   
7591   Instruction *I = dyn_cast<Instruction>(V);
7592   if (!I) return false;
7593   
7594   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7595   
7596   // If this is an extension or truncate, we can often eliminate it.
7597   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7598     // If this is a cast from the destination type, we can trivially eliminate
7599     // it, and this will remove a cast overall.
7600     if (I->getOperand(0)->getType() == Ty) {
7601       // If the first operand is itself a cast, and is eliminable, do not count
7602       // this as an eliminable cast.  We would prefer to eliminate those two
7603       // casts first.
7604       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7605         ++NumCastsRemoved;
7606       return true;
7607     }
7608   }
7609
7610   // We can't extend or shrink something that has multiple uses: doing so would
7611   // require duplicating the instruction in general, which isn't profitable.
7612   if (!I->hasOneUse()) return false;
7613
7614   unsigned Opc = I->getOpcode();
7615   switch (Opc) {
7616   case Instruction::Add:
7617   case Instruction::Sub:
7618   case Instruction::Mul:
7619   case Instruction::And:
7620   case Instruction::Or:
7621   case Instruction::Xor:
7622     // These operators can all arbitrarily be extended or truncated.
7623     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7624                                       NumCastsRemoved) &&
7625            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7626                                       NumCastsRemoved);
7627
7628   case Instruction::Shl:
7629     // If we are truncating the result of this SHL, and if it's a shift of a
7630     // constant amount, we can always perform a SHL in a smaller type.
7631     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7632       uint32_t BitWidth = Ty->getBitWidth();
7633       if (BitWidth < OrigTy->getBitWidth() && 
7634           CI->getLimitedValue(BitWidth) < BitWidth)
7635         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7636                                           NumCastsRemoved);
7637     }
7638     break;
7639   case Instruction::LShr:
7640     // If this is a truncate of a logical shr, we can truncate it to a smaller
7641     // lshr iff we know that the bits we would otherwise be shifting in are
7642     // already zeros.
7643     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7644       uint32_t OrigBitWidth = OrigTy->getBitWidth();
7645       uint32_t BitWidth = Ty->getBitWidth();
7646       if (BitWidth < OrigBitWidth &&
7647           MaskedValueIsZero(I->getOperand(0),
7648             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7649           CI->getLimitedValue(BitWidth) < BitWidth) {
7650         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7651                                           NumCastsRemoved);
7652       }
7653     }
7654     break;
7655   case Instruction::ZExt:
7656   case Instruction::SExt:
7657   case Instruction::Trunc:
7658     // If this is the same kind of case as our original (e.g. zext+zext), we
7659     // can safely replace it.  Note that replacing it does not reduce the number
7660     // of casts in the input.
7661     if (Opc == CastOpc)
7662       return true;
7663
7664     // sext (zext ty1), ty2 -> zext ty2
7665     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7666       return true;
7667     break;
7668   case Instruction::Select: {
7669     SelectInst *SI = cast<SelectInst>(I);
7670     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7671                                       NumCastsRemoved) &&
7672            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7673                                       NumCastsRemoved);
7674   }
7675   case Instruction::PHI: {
7676     // We can change a phi if we can change all operands.
7677     PHINode *PN = cast<PHINode>(I);
7678     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7679       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7680                                       NumCastsRemoved))
7681         return false;
7682     return true;
7683   }
7684   default:
7685     // TODO: Can handle more cases here.
7686     break;
7687   }
7688   
7689   return false;
7690 }
7691
7692 /// EvaluateInDifferentType - Given an expression that 
7693 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7694 /// evaluate the expression.
7695 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7696                                              bool isSigned) {
7697   if (Constant *C = dyn_cast<Constant>(V))
7698     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7699
7700   // Otherwise, it must be an instruction.
7701   Instruction *I = cast<Instruction>(V);
7702   Instruction *Res = 0;
7703   unsigned Opc = I->getOpcode();
7704   switch (Opc) {
7705   case Instruction::Add:
7706   case Instruction::Sub:
7707   case Instruction::Mul:
7708   case Instruction::And:
7709   case Instruction::Or:
7710   case Instruction::Xor:
7711   case Instruction::AShr:
7712   case Instruction::LShr:
7713   case Instruction::Shl: {
7714     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7715     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7716     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7717     break;
7718   }    
7719   case Instruction::Trunc:
7720   case Instruction::ZExt:
7721   case Instruction::SExt:
7722     // If the source type of the cast is the type we're trying for then we can
7723     // just return the source.  There's no need to insert it because it is not
7724     // new.
7725     if (I->getOperand(0)->getType() == Ty)
7726       return I->getOperand(0);
7727     
7728     // Otherwise, must be the same type of cast, so just reinsert a new one.
7729     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7730                            Ty);
7731     break;
7732   case Instruction::Select: {
7733     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7734     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7735     Res = SelectInst::Create(I->getOperand(0), True, False);
7736     break;
7737   }
7738   case Instruction::PHI: {
7739     PHINode *OPN = cast<PHINode>(I);
7740     PHINode *NPN = PHINode::Create(Ty);
7741     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7742       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7743       NPN->addIncoming(V, OPN->getIncomingBlock(i));
7744     }
7745     Res = NPN;
7746     break;
7747   }
7748   default: 
7749     // TODO: Can handle more cases here.
7750     assert(0 && "Unreachable!");
7751     break;
7752   }
7753   
7754   Res->takeName(I);
7755   return InsertNewInstBefore(Res, *I);
7756 }
7757
7758 /// @brief Implement the transforms common to all CastInst visitors.
7759 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7760   Value *Src = CI.getOperand(0);
7761
7762   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7763   // eliminate it now.
7764   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7765     if (Instruction::CastOps opc = 
7766         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7767       // The first cast (CSrc) is eliminable so we need to fix up or replace
7768       // the second cast (CI). CSrc will then have a good chance of being dead.
7769       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7770     }
7771   }
7772
7773   // If we are casting a select then fold the cast into the select
7774   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7775     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7776       return NV;
7777
7778   // If we are casting a PHI then fold the cast into the PHI
7779   if (isa<PHINode>(Src))
7780     if (Instruction *NV = FoldOpIntoPhi(CI))
7781       return NV;
7782   
7783   return 0;
7784 }
7785
7786 /// FindElementAtOffset - Given a type and a constant offset, determine whether
7787 /// or not there is a sequence of GEP indices into the type that will land us at
7788 /// the specified offset.  If so, fill them into NewIndices and return the
7789 /// resultant element type, otherwise return null.
7790 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
7791                                        SmallVectorImpl<Value*> &NewIndices,
7792                                        const TargetData *TD) {
7793   if (!Ty->isSized()) return 0;
7794   
7795   // Start with the index over the outer type.  Note that the type size
7796   // might be zero (even if the offset isn't zero) if the indexed type
7797   // is something like [0 x {int, int}]
7798   const Type *IntPtrTy = TD->getIntPtrType();
7799   int64_t FirstIdx = 0;
7800   if (int64_t TySize = TD->getTypePaddedSize(Ty)) {
7801     FirstIdx = Offset/TySize;
7802     Offset -= FirstIdx*TySize;
7803     
7804     // Handle hosts where % returns negative instead of values [0..TySize).
7805     if (Offset < 0) {
7806       --FirstIdx;
7807       Offset += TySize;
7808       assert(Offset >= 0);
7809     }
7810     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
7811   }
7812   
7813   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7814     
7815   // Index into the types.  If we fail, set OrigBase to null.
7816   while (Offset) {
7817     // Indexing into tail padding between struct/array elements.
7818     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
7819       return 0;
7820     
7821     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
7822       const StructLayout *SL = TD->getStructLayout(STy);
7823       assert(Offset < (int64_t)SL->getSizeInBytes() &&
7824              "Offset must stay within the indexed type");
7825       
7826       unsigned Elt = SL->getElementContainingOffset(Offset);
7827       NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7828       
7829       Offset -= SL->getElementOffset(Elt);
7830       Ty = STy->getElementType(Elt);
7831     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
7832       uint64_t EltSize = TD->getTypePaddedSize(AT->getElementType());
7833       assert(EltSize && "Cannot index into a zero-sized array");
7834       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7835       Offset %= EltSize;
7836       Ty = AT->getElementType();
7837     } else {
7838       // Otherwise, we can't index into the middle of this atomic type, bail.
7839       return 0;
7840     }
7841   }
7842   
7843   return Ty;
7844 }
7845
7846 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7847 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7848   Value *Src = CI.getOperand(0);
7849   
7850   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7851     // If casting the result of a getelementptr instruction with no offset, turn
7852     // this into a cast of the original pointer!
7853     if (GEP->hasAllZeroIndices()) {
7854       // Changing the cast operand is usually not a good idea but it is safe
7855       // here because the pointer operand is being replaced with another 
7856       // pointer operand so the opcode doesn't need to change.
7857       AddToWorkList(GEP);
7858       CI.setOperand(0, GEP->getOperand(0));
7859       return &CI;
7860     }
7861     
7862     // If the GEP has a single use, and the base pointer is a bitcast, and the
7863     // GEP computes a constant offset, see if we can convert these three
7864     // instructions into fewer.  This typically happens with unions and other
7865     // non-type-safe code.
7866     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7867       if (GEP->hasAllConstantIndices()) {
7868         // We are guaranteed to get a constant from EmitGEPOffset.
7869         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7870         int64_t Offset = OffsetV->getSExtValue();
7871         
7872         // Get the base pointer input of the bitcast, and the type it points to.
7873         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7874         const Type *GEPIdxTy =
7875           cast<PointerType>(OrigBase->getType())->getElementType();
7876         SmallVector<Value*, 8> NewIndices;
7877         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
7878           // If we were able to index down into an element, create the GEP
7879           // and bitcast the result.  This eliminates one bitcast, potentially
7880           // two.
7881           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
7882                                                         NewIndices.begin(),
7883                                                         NewIndices.end(), "");
7884           InsertNewInstBefore(NGEP, CI);
7885           NGEP->takeName(GEP);
7886           
7887           if (isa<BitCastInst>(CI))
7888             return new BitCastInst(NGEP, CI.getType());
7889           assert(isa<PtrToIntInst>(CI));
7890           return new PtrToIntInst(NGEP, CI.getType());
7891         }
7892       }      
7893     }
7894   }
7895     
7896   return commonCastTransforms(CI);
7897 }
7898
7899
7900 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7901 /// integer types. This function implements the common transforms for all those
7902 /// cases.
7903 /// @brief Implement the transforms common to CastInst with integer operands
7904 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7905   if (Instruction *Result = commonCastTransforms(CI))
7906     return Result;
7907
7908   Value *Src = CI.getOperand(0);
7909   const Type *SrcTy = Src->getType();
7910   const Type *DestTy = CI.getType();
7911   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7912   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7913
7914   // See if we can simplify any instructions used by the LHS whose sole 
7915   // purpose is to compute bits we don't care about.
7916   if (SimplifyDemandedInstructionBits(CI))
7917     return &CI;
7918
7919   // If the source isn't an instruction or has more than one use then we
7920   // can't do anything more. 
7921   Instruction *SrcI = dyn_cast<Instruction>(Src);
7922   if (!SrcI || !Src->hasOneUse())
7923     return 0;
7924
7925   // Attempt to propagate the cast into the instruction for int->int casts.
7926   int NumCastsRemoved = 0;
7927   if (!isa<BitCastInst>(CI) &&
7928       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7929                                  CI.getOpcode(), NumCastsRemoved)) {
7930     // If this cast is a truncate, evaluting in a different type always
7931     // eliminates the cast, so it is always a win.  If this is a zero-extension,
7932     // we need to do an AND to maintain the clear top-part of the computation,
7933     // so we require that the input have eliminated at least one cast.  If this
7934     // is a sign extension, we insert two new casts (to do the extension) so we
7935     // require that two casts have been eliminated.
7936     bool DoXForm = false;
7937     bool JustReplace = false;
7938     switch (CI.getOpcode()) {
7939     default:
7940       // All the others use floating point so we shouldn't actually 
7941       // get here because of the check above.
7942       assert(0 && "Unknown cast type");
7943     case Instruction::Trunc:
7944       DoXForm = true;
7945       break;
7946     case Instruction::ZExt: {
7947       DoXForm = NumCastsRemoved >= 1;
7948       if (!DoXForm && 0) {
7949         // If it's unnecessary to issue an AND to clear the high bits, it's
7950         // always profitable to do this xform.
7951         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
7952         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
7953         if (MaskedValueIsZero(TryRes, Mask))
7954           return ReplaceInstUsesWith(CI, TryRes);
7955         
7956         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
7957           if (TryI->use_empty())
7958             EraseInstFromFunction(*TryI);
7959       }
7960       break;
7961     }
7962     case Instruction::SExt: {
7963       DoXForm = NumCastsRemoved >= 2;
7964       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
7965         // If we do not have to emit the truncate + sext pair, then it's always
7966         // profitable to do this xform.
7967         //
7968         // It's not safe to eliminate the trunc + sext pair if one of the
7969         // eliminated cast is a truncate. e.g.
7970         // t2 = trunc i32 t1 to i16
7971         // t3 = sext i16 t2 to i32
7972         // !=
7973         // i32 t1
7974         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
7975         unsigned NumSignBits = ComputeNumSignBits(TryRes);
7976         if (NumSignBits > (DestBitSize - SrcBitSize))
7977           return ReplaceInstUsesWith(CI, TryRes);
7978         
7979         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
7980           if (TryI->use_empty())
7981             EraseInstFromFunction(*TryI);
7982       }
7983       break;
7984     }
7985     }
7986     
7987     if (DoXForm) {
7988       DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
7989            << " cast: " << CI;
7990       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
7991                                            CI.getOpcode() == Instruction::SExt);
7992       if (JustReplace)
7993         // Just replace this cast with the result.
7994         return ReplaceInstUsesWith(CI, Res);
7995
7996       assert(Res->getType() == DestTy);
7997       switch (CI.getOpcode()) {
7998       default: assert(0 && "Unknown cast type!");
7999       case Instruction::Trunc:
8000       case Instruction::BitCast:
8001         // Just replace this cast with the result.
8002         return ReplaceInstUsesWith(CI, Res);
8003       case Instruction::ZExt: {
8004         assert(SrcBitSize < DestBitSize && "Not a zext?");
8005
8006         // If the high bits are already zero, just replace this cast with the
8007         // result.
8008         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8009         if (MaskedValueIsZero(Res, Mask))
8010           return ReplaceInstUsesWith(CI, Res);
8011
8012         // We need to emit an AND to clear the high bits.
8013         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
8014                                                             SrcBitSize));
8015         return BinaryOperator::CreateAnd(Res, C);
8016       }
8017       case Instruction::SExt: {
8018         // If the high bits are already filled with sign bit, just replace this
8019         // cast with the result.
8020         unsigned NumSignBits = ComputeNumSignBits(Res);
8021         if (NumSignBits > (DestBitSize - SrcBitSize))
8022           return ReplaceInstUsesWith(CI, Res);
8023
8024         // We need to emit a cast to truncate, then a cast to sext.
8025         return CastInst::Create(Instruction::SExt,
8026             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8027                              CI), DestTy);
8028       }
8029       }
8030     }
8031   }
8032   
8033   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8034   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8035
8036   switch (SrcI->getOpcode()) {
8037   case Instruction::Add:
8038   case Instruction::Mul:
8039   case Instruction::And:
8040   case Instruction::Or:
8041   case Instruction::Xor:
8042     // If we are discarding information, rewrite.
8043     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8044       // Don't insert two casts if they cannot be eliminated.  We allow 
8045       // two casts to be inserted if the sizes are the same.  This could 
8046       // only be converting signedness, which is a noop.
8047       if (DestBitSize == SrcBitSize || 
8048           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8049           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8050         Instruction::CastOps opcode = CI.getOpcode();
8051         Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8052         Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8053         return BinaryOperator::Create(
8054             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8055       }
8056     }
8057
8058     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8059     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8060         SrcI->getOpcode() == Instruction::Xor &&
8061         Op1 == ConstantInt::getTrue() &&
8062         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8063       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8064       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
8065     }
8066     break;
8067   case Instruction::SDiv:
8068   case Instruction::UDiv:
8069   case Instruction::SRem:
8070   case Instruction::URem:
8071     // If we are just changing the sign, rewrite.
8072     if (DestBitSize == SrcBitSize) {
8073       // Don't insert two casts if they cannot be eliminated.  We allow 
8074       // two casts to be inserted if the sizes are the same.  This could 
8075       // only be converting signedness, which is a noop.
8076       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
8077           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8078         Value *Op0c = InsertCastBefore(Instruction::BitCast, 
8079                                        Op0, DestTy, *SrcI);
8080         Value *Op1c = InsertCastBefore(Instruction::BitCast, 
8081                                        Op1, DestTy, *SrcI);
8082         return BinaryOperator::Create(
8083           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8084       }
8085     }
8086     break;
8087
8088   case Instruction::Shl:
8089     // Allow changing the sign of the source operand.  Do not allow 
8090     // changing the size of the shift, UNLESS the shift amount is a 
8091     // constant.  We must not change variable sized shifts to a smaller 
8092     // size, because it is undefined to shift more bits out than exist 
8093     // in the value.
8094     if (DestBitSize == SrcBitSize ||
8095         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
8096       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8097           Instruction::BitCast : Instruction::Trunc);
8098       Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8099       Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8100       return BinaryOperator::CreateShl(Op0c, Op1c);
8101     }
8102     break;
8103   case Instruction::AShr:
8104     // If this is a signed shr, and if all bits shifted in are about to be
8105     // truncated off, turn it into an unsigned shr to allow greater
8106     // simplifications.
8107     if (DestBitSize < SrcBitSize &&
8108         isa<ConstantInt>(Op1)) {
8109       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
8110       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8111         // Insert the new logical shift right.
8112         return BinaryOperator::CreateLShr(Op0, Op1);
8113       }
8114     }
8115     break;
8116   }
8117   return 0;
8118 }
8119
8120 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8121   if (Instruction *Result = commonIntCastTransforms(CI))
8122     return Result;
8123   
8124   Value *Src = CI.getOperand(0);
8125   const Type *Ty = CI.getType();
8126   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
8127   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
8128   
8129   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
8130     switch (SrcI->getOpcode()) {
8131     default: break;
8132     case Instruction::LShr:
8133       // We can shrink lshr to something smaller if we know the bits shifted in
8134       // are already zeros.
8135       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
8136         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8137         
8138         // Get a mask for the bits shifting in.
8139         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8140         Value* SrcIOp0 = SrcI->getOperand(0);
8141         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
8142           if (ShAmt >= DestBitWidth)        // All zeros.
8143             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8144
8145           // Okay, we can shrink this.  Truncate the input, then return a new
8146           // shift.
8147           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
8148           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
8149                                        Ty, CI);
8150           return BinaryOperator::CreateLShr(V1, V2);
8151         }
8152       } else {     // This is a variable shr.
8153         
8154         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
8155         // more LLVM instructions, but allows '1 << Y' to be hoisted if
8156         // loop-invariant and CSE'd.
8157         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
8158           Value *One = ConstantInt::get(SrcI->getType(), 1);
8159
8160           Value *V = InsertNewInstBefore(
8161               BinaryOperator::CreateShl(One, SrcI->getOperand(1),
8162                                      "tmp"), CI);
8163           V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
8164                                                             SrcI->getOperand(0),
8165                                                             "tmp"), CI);
8166           Value *Zero = Constant::getNullValue(V->getType());
8167           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
8168         }
8169       }
8170       break;
8171     }
8172   }
8173   
8174   return 0;
8175 }
8176
8177 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8178 /// in order to eliminate the icmp.
8179 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8180                                              bool DoXform) {
8181   // If we are just checking for a icmp eq of a single bit and zext'ing it
8182   // to an integer, then shift the bit to the appropriate place and then
8183   // cast to integer to avoid the comparison.
8184   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8185     const APInt &Op1CV = Op1C->getValue();
8186       
8187     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8188     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8189     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8190         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8191       if (!DoXform) return ICI;
8192
8193       Value *In = ICI->getOperand(0);
8194       Value *Sh = ConstantInt::get(In->getType(),
8195                                    In->getType()->getPrimitiveSizeInBits()-1);
8196       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8197                                                         In->getName()+".lobit"),
8198                                CI);
8199       if (In->getType() != CI.getType())
8200         In = CastInst::CreateIntegerCast(In, CI.getType(),
8201                                          false/*ZExt*/, "tmp", &CI);
8202
8203       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8204         Constant *One = ConstantInt::get(In->getType(), 1);
8205         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8206                                                          In->getName()+".not"),
8207                                  CI);
8208       }
8209
8210       return ReplaceInstUsesWith(CI, In);
8211     }
8212       
8213       
8214       
8215     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8216     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8217     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8218     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8219     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8220     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8221     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8222     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8223     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8224         // This only works for EQ and NE
8225         ICI->isEquality()) {
8226       // If Op1C some other power of two, convert:
8227       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8228       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8229       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8230       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8231         
8232       APInt KnownZeroMask(~KnownZero);
8233       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8234         if (!DoXform) return ICI;
8235
8236         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8237         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8238           // (X&4) == 2 --> false
8239           // (X&4) != 2 --> true
8240           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8241           Res = ConstantExpr::getZExt(Res, CI.getType());
8242           return ReplaceInstUsesWith(CI, Res);
8243         }
8244           
8245         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8246         Value *In = ICI->getOperand(0);
8247         if (ShiftAmt) {
8248           // Perform a logical shr by shiftamt.
8249           // Insert the shift to put the result in the low bit.
8250           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8251                                   ConstantInt::get(In->getType(), ShiftAmt),
8252                                                    In->getName()+".lobit"), CI);
8253         }
8254           
8255         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8256           Constant *One = ConstantInt::get(In->getType(), 1);
8257           In = BinaryOperator::CreateXor(In, One, "tmp");
8258           InsertNewInstBefore(cast<Instruction>(In), CI);
8259         }
8260           
8261         if (CI.getType() == In->getType())
8262           return ReplaceInstUsesWith(CI, In);
8263         else
8264           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8265       }
8266     }
8267   }
8268
8269   return 0;
8270 }
8271
8272 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8273   // If one of the common conversion will work ..
8274   if (Instruction *Result = commonIntCastTransforms(CI))
8275     return Result;
8276
8277   Value *Src = CI.getOperand(0);
8278
8279   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8280   // types and if the sizes are just right we can convert this into a logical
8281   // 'and' which will be much cheaper than the pair of casts.
8282   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8283     // Get the sizes of the types involved.  We know that the intermediate type
8284     // will be smaller than A or C, but don't know the relation between A and C.
8285     Value *A = CSrc->getOperand(0);
8286     unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
8287     unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8288     unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8289     // If we're actually extending zero bits, then if
8290     // SrcSize <  DstSize: zext(a & mask)
8291     // SrcSize == DstSize: a & mask
8292     // SrcSize  > DstSize: trunc(a) & mask
8293     if (SrcSize < DstSize) {
8294       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8295       Constant *AndConst = ConstantInt::get(AndValue);
8296       Instruction *And =
8297         BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8298       InsertNewInstBefore(And, CI);
8299       return new ZExtInst(And, CI.getType());
8300     } else if (SrcSize == DstSize) {
8301       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8302       return BinaryOperator::CreateAnd(A, ConstantInt::get(AndValue));
8303     } else if (SrcSize > DstSize) {
8304       Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8305       InsertNewInstBefore(Trunc, CI);
8306       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8307       return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(AndValue));
8308     }
8309   }
8310
8311   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8312     return transformZExtICmp(ICI, CI);
8313
8314   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8315   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8316     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8317     // of the (zext icmp) will be transformed.
8318     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8319     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8320     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8321         (transformZExtICmp(LHS, CI, false) ||
8322          transformZExtICmp(RHS, CI, false))) {
8323       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8324       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8325       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8326     }
8327   }
8328
8329   return 0;
8330 }
8331
8332 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8333   if (Instruction *I = commonIntCastTransforms(CI))
8334     return I;
8335   
8336   Value *Src = CI.getOperand(0);
8337   
8338   // Canonicalize sign-extend from i1 to a select.
8339   if (Src->getType() == Type::Int1Ty)
8340     return SelectInst::Create(Src,
8341                               ConstantInt::getAllOnesValue(CI.getType()),
8342                               Constant::getNullValue(CI.getType()));
8343
8344   // See if the value being truncated is already sign extended.  If so, just
8345   // eliminate the trunc/sext pair.
8346   if (getOpcode(Src) == Instruction::Trunc) {
8347     Value *Op = cast<User>(Src)->getOperand(0);
8348     unsigned OpBits   = cast<IntegerType>(Op->getType())->getBitWidth();
8349     unsigned MidBits  = cast<IntegerType>(Src->getType())->getBitWidth();
8350     unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8351     unsigned NumSignBits = ComputeNumSignBits(Op);
8352
8353     if (OpBits == DestBits) {
8354       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8355       // bits, it is already ready.
8356       if (NumSignBits > DestBits-MidBits)
8357         return ReplaceInstUsesWith(CI, Op);
8358     } else if (OpBits < DestBits) {
8359       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8360       // bits, just sext from i32.
8361       if (NumSignBits > OpBits-MidBits)
8362         return new SExtInst(Op, CI.getType(), "tmp");
8363     } else {
8364       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8365       // bits, just truncate to i32.
8366       if (NumSignBits > OpBits-MidBits)
8367         return new TruncInst(Op, CI.getType(), "tmp");
8368     }
8369   }
8370
8371   // If the input is a shl/ashr pair of a same constant, then this is a sign
8372   // extension from a smaller value.  If we could trust arbitrary bitwidth
8373   // integers, we could turn this into a truncate to the smaller bit and then
8374   // use a sext for the whole extension.  Since we don't, look deeper and check
8375   // for a truncate.  If the source and dest are the same type, eliminate the
8376   // trunc and extend and just do shifts.  For example, turn:
8377   //   %a = trunc i32 %i to i8
8378   //   %b = shl i8 %a, 6
8379   //   %c = ashr i8 %b, 6
8380   //   %d = sext i8 %c to i32
8381   // into:
8382   //   %a = shl i32 %i, 30
8383   //   %d = ashr i32 %a, 30
8384   Value *A = 0;
8385   ConstantInt *BA = 0, *CA = 0;
8386   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8387                         m_ConstantInt(CA))) &&
8388       BA == CA && isa<TruncInst>(A)) {
8389     Value *I = cast<TruncInst>(A)->getOperand(0);
8390     if (I->getType() == CI.getType()) {
8391       unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8392       unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8393       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8394       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8395       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8396                                                         CI.getName()), CI);
8397       return BinaryOperator::CreateAShr(I, ShAmtV);
8398     }
8399   }
8400   
8401   return 0;
8402 }
8403
8404 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8405 /// in the specified FP type without changing its value.
8406 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
8407   bool losesInfo;
8408   APFloat F = CFP->getValueAPF();
8409   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8410   if (!losesInfo)
8411     return ConstantFP::get(F);
8412   return 0;
8413 }
8414
8415 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8416 /// through it until we get the source value.
8417 static Value *LookThroughFPExtensions(Value *V) {
8418   if (Instruction *I = dyn_cast<Instruction>(V))
8419     if (I->getOpcode() == Instruction::FPExt)
8420       return LookThroughFPExtensions(I->getOperand(0));
8421   
8422   // If this value is a constant, return the constant in the smallest FP type
8423   // that can accurately represent it.  This allows us to turn
8424   // (float)((double)X+2.0) into x+2.0f.
8425   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8426     if (CFP->getType() == Type::PPC_FP128Ty)
8427       return V;  // No constant folding of this.
8428     // See if the value can be truncated to float and then reextended.
8429     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
8430       return V;
8431     if (CFP->getType() == Type::DoubleTy)
8432       return V;  // Won't shrink.
8433     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
8434       return V;
8435     // Don't try to shrink to various long double types.
8436   }
8437   
8438   return V;
8439 }
8440
8441 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8442   if (Instruction *I = commonCastTransforms(CI))
8443     return I;
8444   
8445   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8446   // smaller than the destination type, we can eliminate the truncate by doing
8447   // the add as the smaller type.  This applies to add/sub/mul/div as well as
8448   // many builtins (sqrt, etc).
8449   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8450   if (OpI && OpI->hasOneUse()) {
8451     switch (OpI->getOpcode()) {
8452     default: break;
8453     case Instruction::Add:
8454     case Instruction::Sub:
8455     case Instruction::Mul:
8456     case Instruction::FDiv:
8457     case Instruction::FRem:
8458       const Type *SrcTy = OpI->getType();
8459       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8460       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8461       if (LHSTrunc->getType() != SrcTy && 
8462           RHSTrunc->getType() != SrcTy) {
8463         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8464         // If the source types were both smaller than the destination type of
8465         // the cast, do this xform.
8466         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8467             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8468           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8469                                       CI.getType(), CI);
8470           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8471                                       CI.getType(), CI);
8472           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8473         }
8474       }
8475       break;  
8476     }
8477   }
8478   return 0;
8479 }
8480
8481 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8482   return commonCastTransforms(CI);
8483 }
8484
8485 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8486   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8487   if (OpI == 0)
8488     return commonCastTransforms(FI);
8489
8490   // fptoui(uitofp(X)) --> X
8491   // fptoui(sitofp(X)) --> X
8492   // This is safe if the intermediate type has enough bits in its mantissa to
8493   // accurately represent all values of X.  For example, do not do this with
8494   // i64->float->i64.  This is also safe for sitofp case, because any negative
8495   // 'X' value would cause an undefined result for the fptoui. 
8496   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8497       OpI->getOperand(0)->getType() == FI.getType() &&
8498       (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8499                     OpI->getType()->getFPMantissaWidth())
8500     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8501
8502   return commonCastTransforms(FI);
8503 }
8504
8505 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8506   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8507   if (OpI == 0)
8508     return commonCastTransforms(FI);
8509   
8510   // fptosi(sitofp(X)) --> X
8511   // fptosi(uitofp(X)) --> X
8512   // This is safe if the intermediate type has enough bits in its mantissa to
8513   // accurately represent all values of X.  For example, do not do this with
8514   // i64->float->i64.  This is also safe for sitofp case, because any negative
8515   // 'X' value would cause an undefined result for the fptoui. 
8516   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8517       OpI->getOperand(0)->getType() == FI.getType() &&
8518       (int)FI.getType()->getPrimitiveSizeInBits() <= 
8519                     OpI->getType()->getFPMantissaWidth())
8520     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8521   
8522   return commonCastTransforms(FI);
8523 }
8524
8525 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8526   return commonCastTransforms(CI);
8527 }
8528
8529 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8530   return commonCastTransforms(CI);
8531 }
8532
8533 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
8534   return commonPointerCastTransforms(CI);
8535 }
8536
8537 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8538   if (Instruction *I = commonCastTransforms(CI))
8539     return I;
8540   
8541   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8542   if (!DestPointee->isSized()) return 0;
8543
8544   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8545   ConstantInt *Cst;
8546   Value *X;
8547   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8548                                     m_ConstantInt(Cst)))) {
8549     // If the source and destination operands have the same type, see if this
8550     // is a single-index GEP.
8551     if (X->getType() == CI.getType()) {
8552       // Get the size of the pointee type.
8553       uint64_t Size = TD->getTypePaddedSize(DestPointee);
8554
8555       // Convert the constant to intptr type.
8556       APInt Offset = Cst->getValue();
8557       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8558
8559       // If Offset is evenly divisible by Size, we can do this xform.
8560       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8561         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8562         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
8563       }
8564     }
8565     // TODO: Could handle other cases, e.g. where add is indexing into field of
8566     // struct etc.
8567   } else if (CI.getOperand(0)->hasOneUse() &&
8568              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8569     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8570     // "inttoptr+GEP" instead of "add+intptr".
8571     
8572     // Get the size of the pointee type.
8573     uint64_t Size = TD->getTypePaddedSize(DestPointee);
8574     
8575     // Convert the constant to intptr type.
8576     APInt Offset = Cst->getValue();
8577     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8578     
8579     // If Offset is evenly divisible by Size, we can do this xform.
8580     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8581       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8582       
8583       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8584                                                             "tmp"), CI);
8585       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
8586     }
8587   }
8588   return 0;
8589 }
8590
8591 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8592   // If the operands are integer typed then apply the integer transforms,
8593   // otherwise just apply the common ones.
8594   Value *Src = CI.getOperand(0);
8595   const Type *SrcTy = Src->getType();
8596   const Type *DestTy = CI.getType();
8597
8598   if (SrcTy->isInteger() && DestTy->isInteger()) {
8599     if (Instruction *Result = commonIntCastTransforms(CI))
8600       return Result;
8601   } else if (isa<PointerType>(SrcTy)) {
8602     if (Instruction *I = commonPointerCastTransforms(CI))
8603       return I;
8604   } else {
8605     if (Instruction *Result = commonCastTransforms(CI))
8606       return Result;
8607   }
8608
8609
8610   // Get rid of casts from one type to the same type. These are useless and can
8611   // be replaced by the operand.
8612   if (DestTy == Src->getType())
8613     return ReplaceInstUsesWith(CI, Src);
8614
8615   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8616     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8617     const Type *DstElTy = DstPTy->getElementType();
8618     const Type *SrcElTy = SrcPTy->getElementType();
8619     
8620     // If the address spaces don't match, don't eliminate the bitcast, which is
8621     // required for changing types.
8622     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8623       return 0;
8624     
8625     // If we are casting a malloc or alloca to a pointer to a type of the same
8626     // size, rewrite the allocation instruction to allocate the "right" type.
8627     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8628       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8629         return V;
8630     
8631     // If the source and destination are pointers, and this cast is equivalent
8632     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8633     // This can enhance SROA and other transforms that want type-safe pointers.
8634     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8635     unsigned NumZeros = 0;
8636     while (SrcElTy != DstElTy && 
8637            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8638            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8639       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8640       ++NumZeros;
8641     }
8642
8643     // If we found a path from the src to dest, create the getelementptr now.
8644     if (SrcElTy == DstElTy) {
8645       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8646       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
8647                                        ((Instruction*) NULL));
8648     }
8649   }
8650
8651   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8652     if (SVI->hasOneUse()) {
8653       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8654       // a bitconvert to a vector with the same # elts.
8655       if (isa<VectorType>(DestTy) && 
8656           cast<VectorType>(DestTy)->getNumElements() ==
8657                 SVI->getType()->getNumElements() &&
8658           SVI->getType()->getNumElements() ==
8659             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8660         CastInst *Tmp;
8661         // If either of the operands is a cast from CI.getType(), then
8662         // evaluating the shuffle in the casted destination's type will allow
8663         // us to eliminate at least one cast.
8664         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8665              Tmp->getOperand(0)->getType() == DestTy) ||
8666             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8667              Tmp->getOperand(0)->getType() == DestTy)) {
8668           Value *LHS = InsertCastBefore(Instruction::BitCast,
8669                                         SVI->getOperand(0), DestTy, CI);
8670           Value *RHS = InsertCastBefore(Instruction::BitCast,
8671                                         SVI->getOperand(1), DestTy, CI);
8672           // Return a new shuffle vector.  Use the same element ID's, as we
8673           // know the vector types match #elts.
8674           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8675         }
8676       }
8677     }
8678   }
8679   return 0;
8680 }
8681
8682 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8683 ///   %C = or %A, %B
8684 ///   %D = select %cond, %C, %A
8685 /// into:
8686 ///   %C = select %cond, %B, 0
8687 ///   %D = or %A, %C
8688 ///
8689 /// Assuming that the specified instruction is an operand to the select, return
8690 /// a bitmask indicating which operands of this instruction are foldable if they
8691 /// equal the other incoming value of the select.
8692 ///
8693 static unsigned GetSelectFoldableOperands(Instruction *I) {
8694   switch (I->getOpcode()) {
8695   case Instruction::Add:
8696   case Instruction::Mul:
8697   case Instruction::And:
8698   case Instruction::Or:
8699   case Instruction::Xor:
8700     return 3;              // Can fold through either operand.
8701   case Instruction::Sub:   // Can only fold on the amount subtracted.
8702   case Instruction::Shl:   // Can only fold on the shift amount.
8703   case Instruction::LShr:
8704   case Instruction::AShr:
8705     return 1;
8706   default:
8707     return 0;              // Cannot fold
8708   }
8709 }
8710
8711 /// GetSelectFoldableConstant - For the same transformation as the previous
8712 /// function, return the identity constant that goes into the select.
8713 static Constant *GetSelectFoldableConstant(Instruction *I) {
8714   switch (I->getOpcode()) {
8715   default: assert(0 && "This cannot happen!"); abort();
8716   case Instruction::Add:
8717   case Instruction::Sub:
8718   case Instruction::Or:
8719   case Instruction::Xor:
8720   case Instruction::Shl:
8721   case Instruction::LShr:
8722   case Instruction::AShr:
8723     return Constant::getNullValue(I->getType());
8724   case Instruction::And:
8725     return Constant::getAllOnesValue(I->getType());
8726   case Instruction::Mul:
8727     return ConstantInt::get(I->getType(), 1);
8728   }
8729 }
8730
8731 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8732 /// have the same opcode and only one use each.  Try to simplify this.
8733 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8734                                           Instruction *FI) {
8735   if (TI->getNumOperands() == 1) {
8736     // If this is a non-volatile load or a cast from the same type,
8737     // merge.
8738     if (TI->isCast()) {
8739       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8740         return 0;
8741     } else {
8742       return 0;  // unknown unary op.
8743     }
8744
8745     // Fold this by inserting a select from the input values.
8746     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8747                                            FI->getOperand(0), SI.getName()+".v");
8748     InsertNewInstBefore(NewSI, SI);
8749     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
8750                             TI->getType());
8751   }
8752
8753   // Only handle binary operators here.
8754   if (!isa<BinaryOperator>(TI))
8755     return 0;
8756
8757   // Figure out if the operations have any operands in common.
8758   Value *MatchOp, *OtherOpT, *OtherOpF;
8759   bool MatchIsOpZero;
8760   if (TI->getOperand(0) == FI->getOperand(0)) {
8761     MatchOp  = TI->getOperand(0);
8762     OtherOpT = TI->getOperand(1);
8763     OtherOpF = FI->getOperand(1);
8764     MatchIsOpZero = true;
8765   } else if (TI->getOperand(1) == FI->getOperand(1)) {
8766     MatchOp  = TI->getOperand(1);
8767     OtherOpT = TI->getOperand(0);
8768     OtherOpF = FI->getOperand(0);
8769     MatchIsOpZero = false;
8770   } else if (!TI->isCommutative()) {
8771     return 0;
8772   } else if (TI->getOperand(0) == FI->getOperand(1)) {
8773     MatchOp  = TI->getOperand(0);
8774     OtherOpT = TI->getOperand(1);
8775     OtherOpF = FI->getOperand(0);
8776     MatchIsOpZero = true;
8777   } else if (TI->getOperand(1) == FI->getOperand(0)) {
8778     MatchOp  = TI->getOperand(1);
8779     OtherOpT = TI->getOperand(0);
8780     OtherOpF = FI->getOperand(1);
8781     MatchIsOpZero = true;
8782   } else {
8783     return 0;
8784   }
8785
8786   // If we reach here, they do have operations in common.
8787   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8788                                          OtherOpF, SI.getName()+".v");
8789   InsertNewInstBefore(NewSI, SI);
8790
8791   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8792     if (MatchIsOpZero)
8793       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8794     else
8795       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8796   }
8797   assert(0 && "Shouldn't get here");
8798   return 0;
8799 }
8800
8801 /// visitSelectInstWithICmp - Visit a SelectInst that has an
8802 /// ICmpInst as its first operand.
8803 ///
8804 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
8805                                                    ICmpInst *ICI) {
8806   bool Changed = false;
8807   ICmpInst::Predicate Pred = ICI->getPredicate();
8808   Value *CmpLHS = ICI->getOperand(0);
8809   Value *CmpRHS = ICI->getOperand(1);
8810   Value *TrueVal = SI.getTrueValue();
8811   Value *FalseVal = SI.getFalseValue();
8812
8813   // Check cases where the comparison is with a constant that
8814   // can be adjusted to fit the min/max idiom. We may edit ICI in
8815   // place here, so make sure the select is the only user.
8816   if (ICI->hasOneUse())
8817     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
8818       switch (Pred) {
8819       default: break;
8820       case ICmpInst::ICMP_ULT:
8821       case ICmpInst::ICMP_SLT: {
8822         // X < MIN ? T : F  -->  F
8823         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
8824           return ReplaceInstUsesWith(SI, FalseVal);
8825         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
8826         Constant *AdjustedRHS = SubOne(CI);
8827         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8828             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8829           Pred = ICmpInst::getSwappedPredicate(Pred);
8830           CmpRHS = AdjustedRHS;
8831           std::swap(FalseVal, TrueVal);
8832           ICI->setPredicate(Pred);
8833           ICI->setOperand(1, CmpRHS);
8834           SI.setOperand(1, TrueVal);
8835           SI.setOperand(2, FalseVal);
8836           Changed = true;
8837         }
8838         break;
8839       }
8840       case ICmpInst::ICMP_UGT:
8841       case ICmpInst::ICMP_SGT: {
8842         // X > MAX ? T : F  -->  F
8843         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
8844           return ReplaceInstUsesWith(SI, FalseVal);
8845         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
8846         Constant *AdjustedRHS = AddOne(CI);
8847         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8848             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8849           Pred = ICmpInst::getSwappedPredicate(Pred);
8850           CmpRHS = AdjustedRHS;
8851           std::swap(FalseVal, TrueVal);
8852           ICI->setPredicate(Pred);
8853           ICI->setOperand(1, CmpRHS);
8854           SI.setOperand(1, TrueVal);
8855           SI.setOperand(2, FalseVal);
8856           Changed = true;
8857         }
8858         break;
8859       }
8860       }
8861
8862       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
8863       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
8864       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
8865       if (match(TrueVal, m_ConstantInt<-1>()) &&
8866           match(FalseVal, m_ConstantInt<0>()))
8867         Pred = ICI->getPredicate();
8868       else if (match(TrueVal, m_ConstantInt<0>()) &&
8869                match(FalseVal, m_ConstantInt<-1>()))
8870         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
8871       
8872       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
8873         // If we are just checking for a icmp eq of a single bit and zext'ing it
8874         // to an integer, then shift the bit to the appropriate place and then
8875         // cast to integer to avoid the comparison.
8876         const APInt &Op1CV = CI->getValue();
8877     
8878         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
8879         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
8880         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8881             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
8882           Value *In = ICI->getOperand(0);
8883           Value *Sh = ConstantInt::get(In->getType(),
8884                                        In->getType()->getPrimitiveSizeInBits()-1);
8885           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
8886                                                           In->getName()+".lobit"),
8887                                    *ICI);
8888           if (In->getType() != SI.getType())
8889             In = CastInst::CreateIntegerCast(In, SI.getType(),
8890                                              true/*SExt*/, "tmp", ICI);
8891     
8892           if (Pred == ICmpInst::ICMP_SGT)
8893             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
8894                                        In->getName()+".not"), *ICI);
8895     
8896           return ReplaceInstUsesWith(SI, In);
8897         }
8898       }
8899     }
8900
8901   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
8902     // Transform (X == Y) ? X : Y  -> Y
8903     if (Pred == ICmpInst::ICMP_EQ)
8904       return ReplaceInstUsesWith(SI, FalseVal);
8905     // Transform (X != Y) ? X : Y  -> X
8906     if (Pred == ICmpInst::ICMP_NE)
8907       return ReplaceInstUsesWith(SI, TrueVal);
8908     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8909
8910   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
8911     // Transform (X == Y) ? Y : X  -> X
8912     if (Pred == ICmpInst::ICMP_EQ)
8913       return ReplaceInstUsesWith(SI, FalseVal);
8914     // Transform (X != Y) ? Y : X  -> Y
8915     if (Pred == ICmpInst::ICMP_NE)
8916       return ReplaceInstUsesWith(SI, TrueVal);
8917     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8918   }
8919
8920   /// NOTE: if we wanted to, this is where to detect integer ABS
8921
8922   return Changed ? &SI : 0;
8923 }
8924
8925 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8926   Value *CondVal = SI.getCondition();
8927   Value *TrueVal = SI.getTrueValue();
8928   Value *FalseVal = SI.getFalseValue();
8929
8930   // select true, X, Y  -> X
8931   // select false, X, Y -> Y
8932   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8933     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8934
8935   // select C, X, X -> X
8936   if (TrueVal == FalseVal)
8937     return ReplaceInstUsesWith(SI, TrueVal);
8938
8939   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
8940     return ReplaceInstUsesWith(SI, FalseVal);
8941   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
8942     return ReplaceInstUsesWith(SI, TrueVal);
8943   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
8944     if (isa<Constant>(TrueVal))
8945       return ReplaceInstUsesWith(SI, TrueVal);
8946     else
8947       return ReplaceInstUsesWith(SI, FalseVal);
8948   }
8949
8950   if (SI.getType() == Type::Int1Ty) {
8951     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8952       if (C->getZExtValue()) {
8953         // Change: A = select B, true, C --> A = or B, C
8954         return BinaryOperator::CreateOr(CondVal, FalseVal);
8955       } else {
8956         // Change: A = select B, false, C --> A = and !B, C
8957         Value *NotCond =
8958           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8959                                              "not."+CondVal->getName()), SI);
8960         return BinaryOperator::CreateAnd(NotCond, FalseVal);
8961       }
8962     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8963       if (C->getZExtValue() == false) {
8964         // Change: A = select B, C, false --> A = and B, C
8965         return BinaryOperator::CreateAnd(CondVal, TrueVal);
8966       } else {
8967         // Change: A = select B, C, true --> A = or !B, C
8968         Value *NotCond =
8969           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8970                                              "not."+CondVal->getName()), SI);
8971         return BinaryOperator::CreateOr(NotCond, TrueVal);
8972       }
8973     }
8974     
8975     // select a, b, a  -> a&b
8976     // select a, a, b  -> a|b
8977     if (CondVal == TrueVal)
8978       return BinaryOperator::CreateOr(CondVal, FalseVal);
8979     else if (CondVal == FalseVal)
8980       return BinaryOperator::CreateAnd(CondVal, TrueVal);
8981   }
8982
8983   // Selecting between two integer constants?
8984   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8985     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8986       // select C, 1, 0 -> zext C to int
8987       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8988         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
8989       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8990         // select C, 0, 1 -> zext !C to int
8991         Value *NotCond =
8992           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8993                                                "not."+CondVal->getName()), SI);
8994         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
8995       }
8996
8997       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8998
8999         // (x <s 0) ? -1 : 0 -> ashr x, 31
9000         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
9001           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
9002             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
9003               // The comparison constant and the result are not neccessarily the
9004               // same width. Make an all-ones value by inserting a AShr.
9005               Value *X = IC->getOperand(0);
9006               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
9007               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
9008               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
9009                                                         ShAmt, "ones");
9010               InsertNewInstBefore(SRA, SI);
9011
9012               // Then cast to the appropriate width.
9013               return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
9014             }
9015           }
9016
9017
9018         // If one of the constants is zero (we know they can't both be) and we
9019         // have an icmp instruction with zero, and we have an 'and' with the
9020         // non-constant value, eliminate this whole mess.  This corresponds to
9021         // cases like this: ((X & 27) ? 27 : 0)
9022         if (TrueValC->isZero() || FalseValC->isZero())
9023           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9024               cast<Constant>(IC->getOperand(1))->isNullValue())
9025             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9026               if (ICA->getOpcode() == Instruction::And &&
9027                   isa<ConstantInt>(ICA->getOperand(1)) &&
9028                   (ICA->getOperand(1) == TrueValC ||
9029                    ICA->getOperand(1) == FalseValC) &&
9030                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9031                 // Okay, now we know that everything is set up, we just don't
9032                 // know whether we have a icmp_ne or icmp_eq and whether the 
9033                 // true or false val is the zero.
9034                 bool ShouldNotVal = !TrueValC->isZero();
9035                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9036                 Value *V = ICA;
9037                 if (ShouldNotVal)
9038                   V = InsertNewInstBefore(BinaryOperator::Create(
9039                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9040                 return ReplaceInstUsesWith(SI, V);
9041               }
9042       }
9043     }
9044
9045   // See if we are selecting two values based on a comparison of the two values.
9046   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9047     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9048       // Transform (X == Y) ? X : Y  -> Y
9049       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9050         // This is not safe in general for floating point:  
9051         // consider X== -0, Y== +0.
9052         // It becomes safe if either operand is a nonzero constant.
9053         ConstantFP *CFPt, *CFPf;
9054         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9055               !CFPt->getValueAPF().isZero()) ||
9056             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9057              !CFPf->getValueAPF().isZero()))
9058         return ReplaceInstUsesWith(SI, FalseVal);
9059       }
9060       // Transform (X != Y) ? X : Y  -> X
9061       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9062         return ReplaceInstUsesWith(SI, TrueVal);
9063       // NOTE: if we wanted to, this is where to detect MIN/MAX
9064
9065     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9066       // Transform (X == Y) ? Y : X  -> X
9067       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9068         // This is not safe in general for floating point:  
9069         // consider X== -0, Y== +0.
9070         // It becomes safe if either operand is a nonzero constant.
9071         ConstantFP *CFPt, *CFPf;
9072         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9073               !CFPt->getValueAPF().isZero()) ||
9074             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9075              !CFPf->getValueAPF().isZero()))
9076           return ReplaceInstUsesWith(SI, FalseVal);
9077       }
9078       // Transform (X != Y) ? Y : X  -> Y
9079       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9080         return ReplaceInstUsesWith(SI, TrueVal);
9081       // NOTE: if we wanted to, this is where to detect MIN/MAX
9082     }
9083     // NOTE: if we wanted to, this is where to detect ABS
9084   }
9085
9086   // See if we are selecting two values based on a comparison of the two values.
9087   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9088     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9089       return Result;
9090
9091   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9092     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9093       if (TI->hasOneUse() && FI->hasOneUse()) {
9094         Instruction *AddOp = 0, *SubOp = 0;
9095
9096         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9097         if (TI->getOpcode() == FI->getOpcode())
9098           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9099             return IV;
9100
9101         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9102         // even legal for FP.
9103         if (TI->getOpcode() == Instruction::Sub &&
9104             FI->getOpcode() == Instruction::Add) {
9105           AddOp = FI; SubOp = TI;
9106         } else if (FI->getOpcode() == Instruction::Sub &&
9107                    TI->getOpcode() == Instruction::Add) {
9108           AddOp = TI; SubOp = FI;
9109         }
9110
9111         if (AddOp) {
9112           Value *OtherAddOp = 0;
9113           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9114             OtherAddOp = AddOp->getOperand(1);
9115           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9116             OtherAddOp = AddOp->getOperand(0);
9117           }
9118
9119           if (OtherAddOp) {
9120             // So at this point we know we have (Y -> OtherAddOp):
9121             //        select C, (add X, Y), (sub X, Z)
9122             Value *NegVal;  // Compute -Z
9123             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9124               NegVal = ConstantExpr::getNeg(C);
9125             } else {
9126               NegVal = InsertNewInstBefore(
9127                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
9128             }
9129
9130             Value *NewTrueOp = OtherAddOp;
9131             Value *NewFalseOp = NegVal;
9132             if (AddOp != TI)
9133               std::swap(NewTrueOp, NewFalseOp);
9134             Instruction *NewSel =
9135               SelectInst::Create(CondVal, NewTrueOp,
9136                                  NewFalseOp, SI.getName() + ".p");
9137
9138             NewSel = InsertNewInstBefore(NewSel, SI);
9139             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9140           }
9141         }
9142       }
9143
9144   // See if we can fold the select into one of our operands.
9145   if (SI.getType()->isInteger()) {
9146     // See the comment above GetSelectFoldableOperands for a description of the
9147     // transformation we are doing here.
9148     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
9149       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9150           !isa<Constant>(FalseVal))
9151         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9152           unsigned OpToFold = 0;
9153           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9154             OpToFold = 1;
9155           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9156             OpToFold = 2;
9157           }
9158
9159           if (OpToFold) {
9160             Constant *C = GetSelectFoldableConstant(TVI);
9161             Instruction *NewSel =
9162               SelectInst::Create(SI.getCondition(),
9163                                  TVI->getOperand(2-OpToFold), C);
9164             InsertNewInstBefore(NewSel, SI);
9165             NewSel->takeName(TVI);
9166             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9167               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9168             else {
9169               assert(0 && "Unknown instruction!!");
9170             }
9171           }
9172         }
9173
9174     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
9175       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9176           !isa<Constant>(TrueVal))
9177         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9178           unsigned OpToFold = 0;
9179           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9180             OpToFold = 1;
9181           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9182             OpToFold = 2;
9183           }
9184
9185           if (OpToFold) {
9186             Constant *C = GetSelectFoldableConstant(FVI);
9187             Instruction *NewSel =
9188               SelectInst::Create(SI.getCondition(), C,
9189                                  FVI->getOperand(2-OpToFold));
9190             InsertNewInstBefore(NewSel, SI);
9191             NewSel->takeName(FVI);
9192             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9193               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9194             else
9195               assert(0 && "Unknown instruction!!");
9196           }
9197         }
9198   }
9199
9200   if (BinaryOperator::isNot(CondVal)) {
9201     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9202     SI.setOperand(1, FalseVal);
9203     SI.setOperand(2, TrueVal);
9204     return &SI;
9205   }
9206
9207   return 0;
9208 }
9209
9210 /// EnforceKnownAlignment - If the specified pointer points to an object that
9211 /// we control, modify the object's alignment to PrefAlign. This isn't
9212 /// often possible though. If alignment is important, a more reliable approach
9213 /// is to simply align all global variables and allocation instructions to
9214 /// their preferred alignment from the beginning.
9215 ///
9216 static unsigned EnforceKnownAlignment(Value *V,
9217                                       unsigned Align, unsigned PrefAlign) {
9218
9219   User *U = dyn_cast<User>(V);
9220   if (!U) return Align;
9221
9222   switch (getOpcode(U)) {
9223   default: break;
9224   case Instruction::BitCast:
9225     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9226   case Instruction::GetElementPtr: {
9227     // If all indexes are zero, it is just the alignment of the base pointer.
9228     bool AllZeroOperands = true;
9229     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9230       if (!isa<Constant>(*i) ||
9231           !cast<Constant>(*i)->isNullValue()) {
9232         AllZeroOperands = false;
9233         break;
9234       }
9235
9236     if (AllZeroOperands) {
9237       // Treat this like a bitcast.
9238       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9239     }
9240     break;
9241   }
9242   }
9243
9244   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9245     // If there is a large requested alignment and we can, bump up the alignment
9246     // of the global.
9247     if (!GV->isDeclaration()) {
9248       if (GV->getAlignment() >= PrefAlign)
9249         Align = GV->getAlignment();
9250       else {
9251         GV->setAlignment(PrefAlign);
9252         Align = PrefAlign;
9253       }
9254     }
9255   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9256     // If there is a requested alignment and if this is an alloca, round up.  We
9257     // don't do this for malloc, because some systems can't respect the request.
9258     if (isa<AllocaInst>(AI)) {
9259       if (AI->getAlignment() >= PrefAlign)
9260         Align = AI->getAlignment();
9261       else {
9262         AI->setAlignment(PrefAlign);
9263         Align = PrefAlign;
9264       }
9265     }
9266   }
9267
9268   return Align;
9269 }
9270
9271 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9272 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9273 /// and it is more than the alignment of the ultimate object, see if we can
9274 /// increase the alignment of the ultimate object, making this check succeed.
9275 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9276                                                   unsigned PrefAlign) {
9277   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9278                       sizeof(PrefAlign) * CHAR_BIT;
9279   APInt Mask = APInt::getAllOnesValue(BitWidth);
9280   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9281   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9282   unsigned TrailZ = KnownZero.countTrailingOnes();
9283   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9284
9285   if (PrefAlign > Align)
9286     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9287   
9288     // We don't need to make any adjustment.
9289   return Align;
9290 }
9291
9292 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9293   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9294   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9295   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9296   unsigned CopyAlign = MI->getAlignment()->getZExtValue();
9297
9298   if (CopyAlign < MinAlign) {
9299     MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
9300     return MI;
9301   }
9302   
9303   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9304   // load/store.
9305   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9306   if (MemOpLength == 0) return 0;
9307   
9308   // Source and destination pointer types are always "i8*" for intrinsic.  See
9309   // if the size is something we can handle with a single primitive load/store.
9310   // A single load+store correctly handles overlapping memory in the memmove
9311   // case.
9312   unsigned Size = MemOpLength->getZExtValue();
9313   if (Size == 0) return MI;  // Delete this mem transfer.
9314   
9315   if (Size > 8 || (Size&(Size-1)))
9316     return 0;  // If not 1/2/4/8 bytes, exit.
9317   
9318   // Use an integer load+store unless we can find something better.
9319   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
9320   
9321   // Memcpy forces the use of i8* for the source and destination.  That means
9322   // that if you're using memcpy to move one double around, you'll get a cast
9323   // from double* to i8*.  We'd much rather use a double load+store rather than
9324   // an i64 load+store, here because this improves the odds that the source or
9325   // dest address will be promotable.  See if we can find a better type than the
9326   // integer datatype.
9327   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9328     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9329     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9330       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9331       // down through these levels if so.
9332       while (!SrcETy->isSingleValueType()) {
9333         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9334           if (STy->getNumElements() == 1)
9335             SrcETy = STy->getElementType(0);
9336           else
9337             break;
9338         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9339           if (ATy->getNumElements() == 1)
9340             SrcETy = ATy->getElementType();
9341           else
9342             break;
9343         } else
9344           break;
9345       }
9346       
9347       if (SrcETy->isSingleValueType())
9348         NewPtrTy = PointerType::getUnqual(SrcETy);
9349     }
9350   }
9351   
9352   
9353   // If the memcpy/memmove provides better alignment info than we can
9354   // infer, use it.
9355   SrcAlign = std::max(SrcAlign, CopyAlign);
9356   DstAlign = std::max(DstAlign, CopyAlign);
9357   
9358   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9359   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9360   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9361   InsertNewInstBefore(L, *MI);
9362   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9363
9364   // Set the size of the copy to 0, it will be deleted on the next iteration.
9365   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9366   return MI;
9367 }
9368
9369 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9370   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9371   if (MI->getAlignment()->getZExtValue() < Alignment) {
9372     MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9373     return MI;
9374   }
9375   
9376   // Extract the length and alignment and fill if they are constant.
9377   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9378   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9379   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9380     return 0;
9381   uint64_t Len = LenC->getZExtValue();
9382   Alignment = MI->getAlignment()->getZExtValue();
9383   
9384   // If the length is zero, this is a no-op
9385   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9386   
9387   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9388   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9389     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
9390     
9391     Value *Dest = MI->getDest();
9392     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9393
9394     // Alignment 0 is identity for alignment 1 for memset, but not store.
9395     if (Alignment == 0) Alignment = 1;
9396     
9397     // Extract the fill value and store.
9398     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9399     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9400                                       Alignment), *MI);
9401     
9402     // Set the size of the copy to 0, it will be deleted on the next iteration.
9403     MI->setLength(Constant::getNullValue(LenC->getType()));
9404     return MI;
9405   }
9406
9407   return 0;
9408 }
9409
9410
9411 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9412 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9413 /// the heavy lifting.
9414 ///
9415 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9416   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9417   if (!II) return visitCallSite(&CI);
9418   
9419   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9420   // visitCallSite.
9421   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9422     bool Changed = false;
9423
9424     // memmove/cpy/set of zero bytes is a noop.
9425     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9426       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9427
9428       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9429         if (CI->getZExtValue() == 1) {
9430           // Replace the instruction with just byte operations.  We would
9431           // transform other cases to loads/stores, but we don't know if
9432           // alignment is sufficient.
9433         }
9434     }
9435
9436     // If we have a memmove and the source operation is a constant global,
9437     // then the source and dest pointers can't alias, so we can change this
9438     // into a call to memcpy.
9439     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9440       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9441         if (GVSrc->isConstant()) {
9442           Module *M = CI.getParent()->getParent()->getParent();
9443           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9444           const Type *Tys[1];
9445           Tys[0] = CI.getOperand(3)->getType();
9446           CI.setOperand(0, 
9447                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9448           Changed = true;
9449         }
9450
9451       // memmove(x,x,size) -> noop.
9452       if (MMI->getSource() == MMI->getDest())
9453         return EraseInstFromFunction(CI);
9454     }
9455
9456     // If we can determine a pointer alignment that is bigger than currently
9457     // set, update the alignment.
9458     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
9459       if (Instruction *I = SimplifyMemTransfer(MI))
9460         return I;
9461     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9462       if (Instruction *I = SimplifyMemSet(MSI))
9463         return I;
9464     }
9465           
9466     if (Changed) return II;
9467   }
9468   
9469   switch (II->getIntrinsicID()) {
9470   default: break;
9471   case Intrinsic::bswap:
9472     // bswap(bswap(x)) -> x
9473     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9474       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9475         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9476     break;
9477   case Intrinsic::ppc_altivec_lvx:
9478   case Intrinsic::ppc_altivec_lvxl:
9479   case Intrinsic::x86_sse_loadu_ps:
9480   case Intrinsic::x86_sse2_loadu_pd:
9481   case Intrinsic::x86_sse2_loadu_dq:
9482     // Turn PPC lvx     -> load if the pointer is known aligned.
9483     // Turn X86 loadups -> load if the pointer is known aligned.
9484     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9485       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9486                                        PointerType::getUnqual(II->getType()),
9487                                        CI);
9488       return new LoadInst(Ptr);
9489     }
9490     break;
9491   case Intrinsic::ppc_altivec_stvx:
9492   case Intrinsic::ppc_altivec_stvxl:
9493     // Turn stvx -> store if the pointer is known aligned.
9494     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9495       const Type *OpPtrTy = 
9496         PointerType::getUnqual(II->getOperand(1)->getType());
9497       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9498       return new StoreInst(II->getOperand(1), Ptr);
9499     }
9500     break;
9501   case Intrinsic::x86_sse_storeu_ps:
9502   case Intrinsic::x86_sse2_storeu_pd:
9503   case Intrinsic::x86_sse2_storeu_dq:
9504     // Turn X86 storeu -> store if the pointer is known aligned.
9505     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9506       const Type *OpPtrTy = 
9507         PointerType::getUnqual(II->getOperand(2)->getType());
9508       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9509       return new StoreInst(II->getOperand(2), Ptr);
9510     }
9511     break;
9512     
9513   case Intrinsic::x86_sse_cvttss2si: {
9514     // These intrinsics only demands the 0th element of its input vector.  If
9515     // we can simplify the input based on that, do so now.
9516     unsigned VWidth =
9517       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9518     APInt DemandedElts(VWidth, 1);
9519     APInt UndefElts(VWidth, 0);
9520     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9521                                               UndefElts)) {
9522       II->setOperand(1, V);
9523       return II;
9524     }
9525     break;
9526   }
9527     
9528   case Intrinsic::ppc_altivec_vperm:
9529     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9530     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9531       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9532       
9533       // Check that all of the elements are integer constants or undefs.
9534       bool AllEltsOk = true;
9535       for (unsigned i = 0; i != 16; ++i) {
9536         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9537             !isa<UndefValue>(Mask->getOperand(i))) {
9538           AllEltsOk = false;
9539           break;
9540         }
9541       }
9542       
9543       if (AllEltsOk) {
9544         // Cast the input vectors to byte vectors.
9545         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9546         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9547         Value *Result = UndefValue::get(Op0->getType());
9548         
9549         // Only extract each element once.
9550         Value *ExtractedElts[32];
9551         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9552         
9553         for (unsigned i = 0; i != 16; ++i) {
9554           if (isa<UndefValue>(Mask->getOperand(i)))
9555             continue;
9556           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9557           Idx &= 31;  // Match the hardware behavior.
9558           
9559           if (ExtractedElts[Idx] == 0) {
9560             Instruction *Elt = 
9561               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9562             InsertNewInstBefore(Elt, CI);
9563             ExtractedElts[Idx] = Elt;
9564           }
9565         
9566           // Insert this value into the result vector.
9567           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9568                                              i, "tmp");
9569           InsertNewInstBefore(cast<Instruction>(Result), CI);
9570         }
9571         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9572       }
9573     }
9574     break;
9575
9576   case Intrinsic::stackrestore: {
9577     // If the save is right next to the restore, remove the restore.  This can
9578     // happen when variable allocas are DCE'd.
9579     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9580       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9581         BasicBlock::iterator BI = SS;
9582         if (&*++BI == II)
9583           return EraseInstFromFunction(CI);
9584       }
9585     }
9586     
9587     // Scan down this block to see if there is another stack restore in the
9588     // same block without an intervening call/alloca.
9589     BasicBlock::iterator BI = II;
9590     TerminatorInst *TI = II->getParent()->getTerminator();
9591     bool CannotRemove = false;
9592     for (++BI; &*BI != TI; ++BI) {
9593       if (isa<AllocaInst>(BI)) {
9594         CannotRemove = true;
9595         break;
9596       }
9597       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9598         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9599           // If there is a stackrestore below this one, remove this one.
9600           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9601             return EraseInstFromFunction(CI);
9602           // Otherwise, ignore the intrinsic.
9603         } else {
9604           // If we found a non-intrinsic call, we can't remove the stack
9605           // restore.
9606           CannotRemove = true;
9607           break;
9608         }
9609       }
9610     }
9611     
9612     // If the stack restore is in a return/unwind block and if there are no
9613     // allocas or calls between the restore and the return, nuke the restore.
9614     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9615       return EraseInstFromFunction(CI);
9616     break;
9617   }
9618   }
9619
9620   return visitCallSite(II);
9621 }
9622
9623 // InvokeInst simplification
9624 //
9625 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9626   return visitCallSite(&II);
9627 }
9628
9629 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9630 /// passed through the varargs area, we can eliminate the use of the cast.
9631 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9632                                          const CastInst * const CI,
9633                                          const TargetData * const TD,
9634                                          const int ix) {
9635   if (!CI->isLosslessCast())
9636     return false;
9637
9638   // The size of ByVal arguments is derived from the type, so we
9639   // can't change to a type with a different size.  If the size were
9640   // passed explicitly we could avoid this check.
9641   if (!CS.paramHasAttr(ix, Attribute::ByVal))
9642     return true;
9643
9644   const Type* SrcTy = 
9645             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9646   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9647   if (!SrcTy->isSized() || !DstTy->isSized())
9648     return false;
9649   if (TD->getTypePaddedSize(SrcTy) != TD->getTypePaddedSize(DstTy))
9650     return false;
9651   return true;
9652 }
9653
9654 // visitCallSite - Improvements for call and invoke instructions.
9655 //
9656 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9657   bool Changed = false;
9658
9659   // If the callee is a constexpr cast of a function, attempt to move the cast
9660   // to the arguments of the call/invoke.
9661   if (transformConstExprCastCall(CS)) return 0;
9662
9663   Value *Callee = CS.getCalledValue();
9664
9665   if (Function *CalleeF = dyn_cast<Function>(Callee))
9666     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9667       Instruction *OldCall = CS.getInstruction();
9668       // If the call and callee calling conventions don't match, this call must
9669       // be unreachable, as the call is undefined.
9670       new StoreInst(ConstantInt::getTrue(),
9671                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
9672                                     OldCall);
9673       if (!OldCall->use_empty())
9674         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9675       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
9676         return EraseInstFromFunction(*OldCall);
9677       return 0;
9678     }
9679
9680   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9681     // This instruction is not reachable, just remove it.  We insert a store to
9682     // undef so that we know that this code is not reachable, despite the fact
9683     // that we can't modify the CFG here.
9684     new StoreInst(ConstantInt::getTrue(),
9685                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9686                   CS.getInstruction());
9687
9688     if (!CS.getInstruction()->use_empty())
9689       CS.getInstruction()->
9690         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9691
9692     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9693       // Don't break the CFG, insert a dummy cond branch.
9694       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9695                          ConstantInt::getTrue(), II);
9696     }
9697     return EraseInstFromFunction(*CS.getInstruction());
9698   }
9699
9700   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9701     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9702       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9703         return transformCallThroughTrampoline(CS);
9704
9705   const PointerType *PTy = cast<PointerType>(Callee->getType());
9706   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9707   if (FTy->isVarArg()) {
9708     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9709     // See if we can optimize any arguments passed through the varargs area of
9710     // the call.
9711     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9712            E = CS.arg_end(); I != E; ++I, ++ix) {
9713       CastInst *CI = dyn_cast<CastInst>(*I);
9714       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9715         *I = CI->getOperand(0);
9716         Changed = true;
9717       }
9718     }
9719   }
9720
9721   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
9722     // Inline asm calls cannot throw - mark them 'nounwind'.
9723     CS.setDoesNotThrow();
9724     Changed = true;
9725   }
9726
9727   return Changed ? CS.getInstruction() : 0;
9728 }
9729
9730 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
9731 // attempt to move the cast to the arguments of the call/invoke.
9732 //
9733 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9734   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9735   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9736   if (CE->getOpcode() != Instruction::BitCast || 
9737       !isa<Function>(CE->getOperand(0)))
9738     return false;
9739   Function *Callee = cast<Function>(CE->getOperand(0));
9740   Instruction *Caller = CS.getInstruction();
9741   const AttrListPtr &CallerPAL = CS.getAttributes();
9742
9743   // Okay, this is a cast from a function to a different type.  Unless doing so
9744   // would cause a type conversion of one of our arguments, change this call to
9745   // be a direct call with arguments casted to the appropriate types.
9746   //
9747   const FunctionType *FT = Callee->getFunctionType();
9748   const Type *OldRetTy = Caller->getType();
9749   const Type *NewRetTy = FT->getReturnType();
9750
9751   if (isa<StructType>(NewRetTy))
9752     return false; // TODO: Handle multiple return values.
9753
9754   // Check to see if we are changing the return type...
9755   if (OldRetTy != NewRetTy) {
9756     if (Callee->isDeclaration() &&
9757         // Conversion is ok if changing from one pointer type to another or from
9758         // a pointer to an integer of the same size.
9759         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
9760           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
9761       return false;   // Cannot transform this return value.
9762
9763     if (!Caller->use_empty() &&
9764         // void -> non-void is handled specially
9765         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
9766       return false;   // Cannot transform this return value.
9767
9768     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9769       Attributes RAttrs = CallerPAL.getRetAttributes();
9770       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
9771         return false;   // Attribute not compatible with transformed value.
9772     }
9773
9774     // If the callsite is an invoke instruction, and the return value is used by
9775     // a PHI node in a successor, we cannot change the return type of the call
9776     // because there is no place to put the cast instruction (without breaking
9777     // the critical edge).  Bail out in this case.
9778     if (!Caller->use_empty())
9779       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9780         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9781              UI != E; ++UI)
9782           if (PHINode *PN = dyn_cast<PHINode>(*UI))
9783             if (PN->getParent() == II->getNormalDest() ||
9784                 PN->getParent() == II->getUnwindDest())
9785               return false;
9786   }
9787
9788   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9789   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9790
9791   CallSite::arg_iterator AI = CS.arg_begin();
9792   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9793     const Type *ParamTy = FT->getParamType(i);
9794     const Type *ActTy = (*AI)->getType();
9795
9796     if (!CastInst::isCastable(ActTy, ParamTy))
9797       return false;   // Cannot transform this parameter value.
9798
9799     if (CallerPAL.getParamAttributes(i + 1) 
9800         & Attribute::typeIncompatible(ParamTy))
9801       return false;   // Attribute not compatible with transformed value.
9802
9803     // Converting from one pointer type to another or between a pointer and an
9804     // integer of the same size is safe even if we do not have a body.
9805     bool isConvertible = ActTy == ParamTy ||
9806       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9807        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
9808     if (Callee->isDeclaration() && !isConvertible) return false;
9809   }
9810
9811   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9812       Callee->isDeclaration())
9813     return false;   // Do not delete arguments unless we have a function body.
9814
9815   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9816       !CallerPAL.isEmpty())
9817     // In this case we have more arguments than the new function type, but we
9818     // won't be dropping them.  Check that these extra arguments have attributes
9819     // that are compatible with being a vararg call argument.
9820     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9821       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
9822         break;
9823       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
9824       if (PAttrs & Attribute::VarArgsIncompatible)
9825         return false;
9826     }
9827
9828   // Okay, we decided that this is a safe thing to do: go ahead and start
9829   // inserting cast instructions as necessary...
9830   std::vector<Value*> Args;
9831   Args.reserve(NumActualArgs);
9832   SmallVector<AttributeWithIndex, 8> attrVec;
9833   attrVec.reserve(NumCommonArgs);
9834
9835   // Get any return attributes.
9836   Attributes RAttrs = CallerPAL.getRetAttributes();
9837
9838   // If the return value is not being used, the type may not be compatible
9839   // with the existing attributes.  Wipe out any problematic attributes.
9840   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
9841
9842   // Add the new return attributes.
9843   if (RAttrs)
9844     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
9845
9846   AI = CS.arg_begin();
9847   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9848     const Type *ParamTy = FT->getParamType(i);
9849     if ((*AI)->getType() == ParamTy) {
9850       Args.push_back(*AI);
9851     } else {
9852       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9853           false, ParamTy, false);
9854       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
9855       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9856     }
9857
9858     // Add any parameter attributes.
9859     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
9860       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
9861   }
9862
9863   // If the function takes more arguments than the call was taking, add them
9864   // now...
9865   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9866     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9867
9868   // If we are removing arguments to the function, emit an obnoxious warning...
9869   if (FT->getNumParams() < NumActualArgs) {
9870     if (!FT->isVarArg()) {
9871       cerr << "WARNING: While resolving call to function '"
9872            << Callee->getName() << "' arguments were dropped!\n";
9873     } else {
9874       // Add all of the arguments in their promoted form to the arg list...
9875       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9876         const Type *PTy = getPromotedType((*AI)->getType());
9877         if (PTy != (*AI)->getType()) {
9878           // Must promote to pass through va_arg area!
9879           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
9880                                                                 PTy, false);
9881           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
9882           InsertNewInstBefore(Cast, *Caller);
9883           Args.push_back(Cast);
9884         } else {
9885           Args.push_back(*AI);
9886         }
9887
9888         // Add any parameter attributes.
9889         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
9890           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
9891       }
9892     }
9893   }
9894
9895   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
9896     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
9897
9898   if (NewRetTy == Type::VoidTy)
9899     Caller->setName("");   // Void type should not have a name.
9900
9901   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
9902
9903   Instruction *NC;
9904   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9905     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9906                             Args.begin(), Args.end(),
9907                             Caller->getName(), Caller);
9908     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
9909     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
9910   } else {
9911     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9912                           Caller->getName(), Caller);
9913     CallInst *CI = cast<CallInst>(Caller);
9914     if (CI->isTailCall())
9915       cast<CallInst>(NC)->setTailCall();
9916     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
9917     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
9918   }
9919
9920   // Insert a cast of the return type as necessary.
9921   Value *NV = NC;
9922   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
9923     if (NV->getType() != Type::VoidTy) {
9924       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
9925                                                             OldRetTy, false);
9926       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
9927
9928       // If this is an invoke instruction, we should insert it after the first
9929       // non-phi, instruction in the normal successor block.
9930       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9931         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
9932         InsertNewInstBefore(NC, *I);
9933       } else {
9934         // Otherwise, it's a call, just insert cast right after the call instr
9935         InsertNewInstBefore(NC, *Caller);
9936       }
9937       AddUsersToWorkList(*Caller);
9938     } else {
9939       NV = UndefValue::get(Caller->getType());
9940     }
9941   }
9942
9943   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9944     Caller->replaceAllUsesWith(NV);
9945   Caller->eraseFromParent();
9946   RemoveFromWorkList(Caller);
9947   return true;
9948 }
9949
9950 // transformCallThroughTrampoline - Turn a call to a function created by the
9951 // init_trampoline intrinsic into a direct call to the underlying function.
9952 //
9953 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9954   Value *Callee = CS.getCalledValue();
9955   const PointerType *PTy = cast<PointerType>(Callee->getType());
9956   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9957   const AttrListPtr &Attrs = CS.getAttributes();
9958
9959   // If the call already has the 'nest' attribute somewhere then give up -
9960   // otherwise 'nest' would occur twice after splicing in the chain.
9961   if (Attrs.hasAttrSomewhere(Attribute::Nest))
9962     return 0;
9963
9964   IntrinsicInst *Tramp =
9965     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9966
9967   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9968   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9969   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9970
9971   const AttrListPtr &NestAttrs = NestF->getAttributes();
9972   if (!NestAttrs.isEmpty()) {
9973     unsigned NestIdx = 1;
9974     const Type *NestTy = 0;
9975     Attributes NestAttr = Attribute::None;
9976
9977     // Look for a parameter marked with the 'nest' attribute.
9978     for (FunctionType::param_iterator I = NestFTy->param_begin(),
9979          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9980       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
9981         // Record the parameter type and any other attributes.
9982         NestTy = *I;
9983         NestAttr = NestAttrs.getParamAttributes(NestIdx);
9984         break;
9985       }
9986
9987     if (NestTy) {
9988       Instruction *Caller = CS.getInstruction();
9989       std::vector<Value*> NewArgs;
9990       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9991
9992       SmallVector<AttributeWithIndex, 8> NewAttrs;
9993       NewAttrs.reserve(Attrs.getNumSlots() + 1);
9994
9995       // Insert the nest argument into the call argument list, which may
9996       // mean appending it.  Likewise for attributes.
9997
9998       // Add any result attributes.
9999       if (Attributes Attr = Attrs.getRetAttributes())
10000         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10001
10002       {
10003         unsigned Idx = 1;
10004         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10005         do {
10006           if (Idx == NestIdx) {
10007             // Add the chain argument and attributes.
10008             Value *NestVal = Tramp->getOperand(3);
10009             if (NestVal->getType() != NestTy)
10010               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10011             NewArgs.push_back(NestVal);
10012             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10013           }
10014
10015           if (I == E)
10016             break;
10017
10018           // Add the original argument and attributes.
10019           NewArgs.push_back(*I);
10020           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10021             NewAttrs.push_back
10022               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10023
10024           ++Idx, ++I;
10025         } while (1);
10026       }
10027
10028       // Add any function attributes.
10029       if (Attributes Attr = Attrs.getFnAttributes())
10030         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10031
10032       // The trampoline may have been bitcast to a bogus type (FTy).
10033       // Handle this by synthesizing a new function type, equal to FTy
10034       // with the chain parameter inserted.
10035
10036       std::vector<const Type*> NewTypes;
10037       NewTypes.reserve(FTy->getNumParams()+1);
10038
10039       // Insert the chain's type into the list of parameter types, which may
10040       // mean appending it.
10041       {
10042         unsigned Idx = 1;
10043         FunctionType::param_iterator I = FTy->param_begin(),
10044           E = FTy->param_end();
10045
10046         do {
10047           if (Idx == NestIdx)
10048             // Add the chain's type.
10049             NewTypes.push_back(NestTy);
10050
10051           if (I == E)
10052             break;
10053
10054           // Add the original type.
10055           NewTypes.push_back(*I);
10056
10057           ++Idx, ++I;
10058         } while (1);
10059       }
10060
10061       // Replace the trampoline call with a direct call.  Let the generic
10062       // code sort out any function type mismatches.
10063       FunctionType *NewFTy =
10064         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
10065       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
10066         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
10067       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
10068
10069       Instruction *NewCaller;
10070       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10071         NewCaller = InvokeInst::Create(NewCallee,
10072                                        II->getNormalDest(), II->getUnwindDest(),
10073                                        NewArgs.begin(), NewArgs.end(),
10074                                        Caller->getName(), Caller);
10075         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10076         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10077       } else {
10078         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10079                                      Caller->getName(), Caller);
10080         if (cast<CallInst>(Caller)->isTailCall())
10081           cast<CallInst>(NewCaller)->setTailCall();
10082         cast<CallInst>(NewCaller)->
10083           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10084         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10085       }
10086       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10087         Caller->replaceAllUsesWith(NewCaller);
10088       Caller->eraseFromParent();
10089       RemoveFromWorkList(Caller);
10090       return 0;
10091     }
10092   }
10093
10094   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10095   // parameter, there is no need to adjust the argument list.  Let the generic
10096   // code sort out any function type mismatches.
10097   Constant *NewCallee =
10098     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
10099   CS.setCalledFunction(NewCallee);
10100   return CS.getInstruction();
10101 }
10102
10103 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10104 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10105 /// and a single binop.
10106 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10107   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10108   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10109   unsigned Opc = FirstInst->getOpcode();
10110   Value *LHSVal = FirstInst->getOperand(0);
10111   Value *RHSVal = FirstInst->getOperand(1);
10112     
10113   const Type *LHSType = LHSVal->getType();
10114   const Type *RHSType = RHSVal->getType();
10115   
10116   // Scan to see if all operands are the same opcode, all have one use, and all
10117   // kill their operands (i.e. the operands have one use).
10118   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10119     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10120     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10121         // Verify type of the LHS matches so we don't fold cmp's of different
10122         // types or GEP's with different index types.
10123         I->getOperand(0)->getType() != LHSType ||
10124         I->getOperand(1)->getType() != RHSType)
10125       return 0;
10126
10127     // If they are CmpInst instructions, check their predicates
10128     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10129       if (cast<CmpInst>(I)->getPredicate() !=
10130           cast<CmpInst>(FirstInst)->getPredicate())
10131         return 0;
10132     
10133     // Keep track of which operand needs a phi node.
10134     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10135     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10136   }
10137   
10138   // Otherwise, this is safe to transform!
10139   
10140   Value *InLHS = FirstInst->getOperand(0);
10141   Value *InRHS = FirstInst->getOperand(1);
10142   PHINode *NewLHS = 0, *NewRHS = 0;
10143   if (LHSVal == 0) {
10144     NewLHS = PHINode::Create(LHSType,
10145                              FirstInst->getOperand(0)->getName() + ".pn");
10146     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10147     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10148     InsertNewInstBefore(NewLHS, PN);
10149     LHSVal = NewLHS;
10150   }
10151   
10152   if (RHSVal == 0) {
10153     NewRHS = PHINode::Create(RHSType,
10154                              FirstInst->getOperand(1)->getName() + ".pn");
10155     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10156     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10157     InsertNewInstBefore(NewRHS, PN);
10158     RHSVal = NewRHS;
10159   }
10160   
10161   // Add all operands to the new PHIs.
10162   if (NewLHS || NewRHS) {
10163     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10164       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10165       if (NewLHS) {
10166         Value *NewInLHS = InInst->getOperand(0);
10167         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10168       }
10169       if (NewRHS) {
10170         Value *NewInRHS = InInst->getOperand(1);
10171         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10172       }
10173     }
10174   }
10175     
10176   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10177     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10178   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10179   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10180                          RHSVal);
10181 }
10182
10183 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10184   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10185   
10186   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10187                                         FirstInst->op_end());
10188   // This is true if all GEP bases are allocas and if all indices into them are
10189   // constants.
10190   bool AllBasePointersAreAllocas = true;
10191   
10192   // Scan to see if all operands are the same opcode, all have one use, and all
10193   // kill their operands (i.e. the operands have one use).
10194   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10195     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10196     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10197       GEP->getNumOperands() != FirstInst->getNumOperands())
10198       return 0;
10199
10200     // Keep track of whether or not all GEPs are of alloca pointers.
10201     if (AllBasePointersAreAllocas &&
10202         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10203          !GEP->hasAllConstantIndices()))
10204       AllBasePointersAreAllocas = false;
10205     
10206     // Compare the operand lists.
10207     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10208       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10209         continue;
10210       
10211       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10212       // if one of the PHIs has a constant for the index.  The index may be
10213       // substantially cheaper to compute for the constants, so making it a
10214       // variable index could pessimize the path.  This also handles the case
10215       // for struct indices, which must always be constant.
10216       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10217           isa<ConstantInt>(GEP->getOperand(op)))
10218         return 0;
10219       
10220       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10221         return 0;
10222       FixedOperands[op] = 0;  // Needs a PHI.
10223     }
10224   }
10225   
10226   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10227   // bother doing this transformation.  At best, this will just save a bit of
10228   // offset calculation, but all the predecessors will have to materialize the
10229   // stack address into a register anyway.  We'd actually rather *clone* the
10230   // load up into the predecessors so that we have a load of a gep of an alloca,
10231   // which can usually all be folded into the load.
10232   if (AllBasePointersAreAllocas)
10233     return 0;
10234   
10235   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10236   // that is variable.
10237   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10238   
10239   bool HasAnyPHIs = false;
10240   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10241     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10242     Value *FirstOp = FirstInst->getOperand(i);
10243     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10244                                      FirstOp->getName()+".pn");
10245     InsertNewInstBefore(NewPN, PN);
10246     
10247     NewPN->reserveOperandSpace(e);
10248     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10249     OperandPhis[i] = NewPN;
10250     FixedOperands[i] = NewPN;
10251     HasAnyPHIs = true;
10252   }
10253
10254   
10255   // Add all operands to the new PHIs.
10256   if (HasAnyPHIs) {
10257     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10258       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10259       BasicBlock *InBB = PN.getIncomingBlock(i);
10260       
10261       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10262         if (PHINode *OpPhi = OperandPhis[op])
10263           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10264     }
10265   }
10266   
10267   Value *Base = FixedOperands[0];
10268   return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10269                                    FixedOperands.end());
10270 }
10271
10272
10273 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10274 /// sink the load out of the block that defines it.  This means that it must be
10275 /// obvious the value of the load is not changed from the point of the load to
10276 /// the end of the block it is in.
10277 ///
10278 /// Finally, it is safe, but not profitable, to sink a load targetting a
10279 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10280 /// to a register.
10281 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10282   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10283   
10284   for (++BBI; BBI != E; ++BBI)
10285     if (BBI->mayWriteToMemory())
10286       return false;
10287   
10288   // Check for non-address taken alloca.  If not address-taken already, it isn't
10289   // profitable to do this xform.
10290   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10291     bool isAddressTaken = false;
10292     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10293          UI != E; ++UI) {
10294       if (isa<LoadInst>(UI)) continue;
10295       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10296         // If storing TO the alloca, then the address isn't taken.
10297         if (SI->getOperand(1) == AI) continue;
10298       }
10299       isAddressTaken = true;
10300       break;
10301     }
10302     
10303     if (!isAddressTaken && AI->isStaticAlloca())
10304       return false;
10305   }
10306   
10307   // If this load is a load from a GEP with a constant offset from an alloca,
10308   // then we don't want to sink it.  In its present form, it will be
10309   // load [constant stack offset].  Sinking it will cause us to have to
10310   // materialize the stack addresses in each predecessor in a register only to
10311   // do a shared load from register in the successor.
10312   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10313     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10314       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10315         return false;
10316   
10317   return true;
10318 }
10319
10320
10321 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10322 // operator and they all are only used by the PHI, PHI together their
10323 // inputs, and do the operation once, to the result of the PHI.
10324 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10325   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10326
10327   // Scan the instruction, looking for input operations that can be folded away.
10328   // If all input operands to the phi are the same instruction (e.g. a cast from
10329   // the same type or "+42") we can pull the operation through the PHI, reducing
10330   // code size and simplifying code.
10331   Constant *ConstantOp = 0;
10332   const Type *CastSrcTy = 0;
10333   bool isVolatile = false;
10334   if (isa<CastInst>(FirstInst)) {
10335     CastSrcTy = FirstInst->getOperand(0)->getType();
10336   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10337     // Can fold binop, compare or shift here if the RHS is a constant, 
10338     // otherwise call FoldPHIArgBinOpIntoPHI.
10339     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10340     if (ConstantOp == 0)
10341       return FoldPHIArgBinOpIntoPHI(PN);
10342   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10343     isVolatile = LI->isVolatile();
10344     // We can't sink the load if the loaded value could be modified between the
10345     // load and the PHI.
10346     if (LI->getParent() != PN.getIncomingBlock(0) ||
10347         !isSafeAndProfitableToSinkLoad(LI))
10348       return 0;
10349     
10350     // If the PHI is of volatile loads and the load block has multiple
10351     // successors, sinking it would remove a load of the volatile value from
10352     // the path through the other successor.
10353     if (isVolatile &&
10354         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10355       return 0;
10356     
10357   } else if (isa<GetElementPtrInst>(FirstInst)) {
10358     return FoldPHIArgGEPIntoPHI(PN);
10359   } else {
10360     return 0;  // Cannot fold this operation.
10361   }
10362
10363   // Check to see if all arguments are the same operation.
10364   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10365     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10366     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10367     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10368       return 0;
10369     if (CastSrcTy) {
10370       if (I->getOperand(0)->getType() != CastSrcTy)
10371         return 0;  // Cast operation must match.
10372     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10373       // We can't sink the load if the loaded value could be modified between 
10374       // the load and the PHI.
10375       if (LI->isVolatile() != isVolatile ||
10376           LI->getParent() != PN.getIncomingBlock(i) ||
10377           !isSafeAndProfitableToSinkLoad(LI))
10378         return 0;
10379       
10380       // If the PHI is of volatile loads and the load block has multiple
10381       // successors, sinking it would remove a load of the volatile value from
10382       // the path through the other successor.
10383       if (isVolatile &&
10384           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10385         return 0;
10386       
10387     } else if (I->getOperand(1) != ConstantOp) {
10388       return 0;
10389     }
10390   }
10391
10392   // Okay, they are all the same operation.  Create a new PHI node of the
10393   // correct type, and PHI together all of the LHS's of the instructions.
10394   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10395                                    PN.getName()+".in");
10396   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10397
10398   Value *InVal = FirstInst->getOperand(0);
10399   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10400
10401   // Add all operands to the new PHI.
10402   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10403     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10404     if (NewInVal != InVal)
10405       InVal = 0;
10406     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10407   }
10408
10409   Value *PhiVal;
10410   if (InVal) {
10411     // The new PHI unions all of the same values together.  This is really
10412     // common, so we handle it intelligently here for compile-time speed.
10413     PhiVal = InVal;
10414     delete NewPN;
10415   } else {
10416     InsertNewInstBefore(NewPN, PN);
10417     PhiVal = NewPN;
10418   }
10419
10420   // Insert and return the new operation.
10421   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10422     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10423   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10424     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10425   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10426     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
10427                            PhiVal, ConstantOp);
10428   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10429   
10430   // If this was a volatile load that we are merging, make sure to loop through
10431   // and mark all the input loads as non-volatile.  If we don't do this, we will
10432   // insert a new volatile load and the old ones will not be deletable.
10433   if (isVolatile)
10434     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10435       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10436   
10437   return new LoadInst(PhiVal, "", isVolatile);
10438 }
10439
10440 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10441 /// that is dead.
10442 static bool DeadPHICycle(PHINode *PN,
10443                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10444   if (PN->use_empty()) return true;
10445   if (!PN->hasOneUse()) return false;
10446
10447   // Remember this node, and if we find the cycle, return.
10448   if (!PotentiallyDeadPHIs.insert(PN))
10449     return true;
10450   
10451   // Don't scan crazily complex things.
10452   if (PotentiallyDeadPHIs.size() == 16)
10453     return false;
10454
10455   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10456     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10457
10458   return false;
10459 }
10460
10461 /// PHIsEqualValue - Return true if this phi node is always equal to
10462 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10463 ///   z = some value; x = phi (y, z); y = phi (x, z)
10464 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10465                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10466   // See if we already saw this PHI node.
10467   if (!ValueEqualPHIs.insert(PN))
10468     return true;
10469   
10470   // Don't scan crazily complex things.
10471   if (ValueEqualPHIs.size() == 16)
10472     return false;
10473  
10474   // Scan the operands to see if they are either phi nodes or are equal to
10475   // the value.
10476   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10477     Value *Op = PN->getIncomingValue(i);
10478     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10479       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10480         return false;
10481     } else if (Op != NonPhiInVal)
10482       return false;
10483   }
10484   
10485   return true;
10486 }
10487
10488
10489 // PHINode simplification
10490 //
10491 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10492   // If LCSSA is around, don't mess with Phi nodes
10493   if (MustPreserveLCSSA) return 0;
10494   
10495   if (Value *V = PN.hasConstantValue())
10496     return ReplaceInstUsesWith(PN, V);
10497
10498   // If all PHI operands are the same operation, pull them through the PHI,
10499   // reducing code size.
10500   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10501       isa<Instruction>(PN.getIncomingValue(1)) &&
10502       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10503       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10504       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10505       // than themselves more than once.
10506       PN.getIncomingValue(0)->hasOneUse())
10507     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10508       return Result;
10509
10510   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10511   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10512   // PHI)... break the cycle.
10513   if (PN.hasOneUse()) {
10514     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10515     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10516       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10517       PotentiallyDeadPHIs.insert(&PN);
10518       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10519         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10520     }
10521    
10522     // If this phi has a single use, and if that use just computes a value for
10523     // the next iteration of a loop, delete the phi.  This occurs with unused
10524     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10525     // common case here is good because the only other things that catch this
10526     // are induction variable analysis (sometimes) and ADCE, which is only run
10527     // late.
10528     if (PHIUser->hasOneUse() &&
10529         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10530         PHIUser->use_back() == &PN) {
10531       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10532     }
10533   }
10534
10535   // We sometimes end up with phi cycles that non-obviously end up being the
10536   // same value, for example:
10537   //   z = some value; x = phi (y, z); y = phi (x, z)
10538   // where the phi nodes don't necessarily need to be in the same block.  Do a
10539   // quick check to see if the PHI node only contains a single non-phi value, if
10540   // so, scan to see if the phi cycle is actually equal to that value.
10541   {
10542     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10543     // Scan for the first non-phi operand.
10544     while (InValNo != NumOperandVals && 
10545            isa<PHINode>(PN.getIncomingValue(InValNo)))
10546       ++InValNo;
10547
10548     if (InValNo != NumOperandVals) {
10549       Value *NonPhiInVal = PN.getOperand(InValNo);
10550       
10551       // Scan the rest of the operands to see if there are any conflicts, if so
10552       // there is no need to recursively scan other phis.
10553       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10554         Value *OpVal = PN.getIncomingValue(InValNo);
10555         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10556           break;
10557       }
10558       
10559       // If we scanned over all operands, then we have one unique value plus
10560       // phi values.  Scan PHI nodes to see if they all merge in each other or
10561       // the value.
10562       if (InValNo == NumOperandVals) {
10563         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10564         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10565           return ReplaceInstUsesWith(PN, NonPhiInVal);
10566       }
10567     }
10568   }
10569   return 0;
10570 }
10571
10572 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10573                                    Instruction *InsertPoint,
10574                                    InstCombiner *IC) {
10575   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10576   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
10577   // We must cast correctly to the pointer type. Ensure that we
10578   // sign extend the integer value if it is smaller as this is
10579   // used for address computation.
10580   Instruction::CastOps opcode = 
10581      (VTySize < PtrSize ? Instruction::SExt :
10582       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10583   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10584 }
10585
10586
10587 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10588   Value *PtrOp = GEP.getOperand(0);
10589   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10590   // If so, eliminate the noop.
10591   if (GEP.getNumOperands() == 1)
10592     return ReplaceInstUsesWith(GEP, PtrOp);
10593
10594   if (isa<UndefValue>(GEP.getOperand(0)))
10595     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10596
10597   bool HasZeroPointerIndex = false;
10598   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10599     HasZeroPointerIndex = C->isNullValue();
10600
10601   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10602     return ReplaceInstUsesWith(GEP, PtrOp);
10603
10604   // Eliminate unneeded casts for indices.
10605   bool MadeChange = false;
10606   
10607   gep_type_iterator GTI = gep_type_begin(GEP);
10608   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10609        i != e; ++i, ++GTI) {
10610     if (isa<SequentialType>(*GTI)) {
10611       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
10612         if (CI->getOpcode() == Instruction::ZExt ||
10613             CI->getOpcode() == Instruction::SExt) {
10614           const Type *SrcTy = CI->getOperand(0)->getType();
10615           // We can eliminate a cast from i32 to i64 iff the target 
10616           // is a 32-bit pointer target.
10617           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10618             MadeChange = true;
10619             *i = CI->getOperand(0);
10620           }
10621         }
10622       }
10623       // If we are using a wider index than needed for this platform, shrink it
10624       // to what we need.  If narrower, sign-extend it to what we need.
10625       // If the incoming value needs a cast instruction,
10626       // insert it.  This explicit cast can make subsequent optimizations more
10627       // obvious.
10628       Value *Op = *i;
10629       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
10630         if (Constant *C = dyn_cast<Constant>(Op)) {
10631           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
10632           MadeChange = true;
10633         } else {
10634           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10635                                 GEP);
10636           *i = Op;
10637           MadeChange = true;
10638         }
10639       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10640         if (Constant *C = dyn_cast<Constant>(Op)) {
10641           *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10642           MadeChange = true;
10643         } else {
10644           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10645                                 GEP);
10646           *i = Op;
10647           MadeChange = true;
10648         }
10649       }
10650     }
10651   }
10652   if (MadeChange) return &GEP;
10653
10654   // Combine Indices - If the source pointer to this getelementptr instruction
10655   // is a getelementptr instruction, combine the indices of the two
10656   // getelementptr instructions into a single instruction.
10657   //
10658   SmallVector<Value*, 8> SrcGEPOperands;
10659   if (User *Src = dyn_castGetElementPtr(PtrOp))
10660     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
10661
10662   if (!SrcGEPOperands.empty()) {
10663     // Note that if our source is a gep chain itself that we wait for that
10664     // chain to be resolved before we perform this transformation.  This
10665     // avoids us creating a TON of code in some cases.
10666     //
10667     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10668         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10669       return 0;   // Wait until our source is folded to completion.
10670
10671     SmallVector<Value*, 8> Indices;
10672
10673     // Find out whether the last index in the source GEP is a sequential idx.
10674     bool EndsWithSequential = false;
10675     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10676            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
10677       EndsWithSequential = !isa<StructType>(*I);
10678
10679     // Can we combine the two pointer arithmetics offsets?
10680     if (EndsWithSequential) {
10681       // Replace: gep (gep %P, long B), long A, ...
10682       // With:    T = long A+B; gep %P, T, ...
10683       //
10684       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
10685       if (SO1 == Constant::getNullValue(SO1->getType())) {
10686         Sum = GO1;
10687       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10688         Sum = SO1;
10689       } else {
10690         // If they aren't the same type, convert both to an integer of the
10691         // target's pointer size.
10692         if (SO1->getType() != GO1->getType()) {
10693           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
10694             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
10695           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
10696             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
10697           } else {
10698             unsigned PS = TD->getPointerSizeInBits();
10699             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
10700               // Convert GO1 to SO1's type.
10701               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
10702
10703             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
10704               // Convert SO1 to GO1's type.
10705               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
10706             } else {
10707               const Type *PT = TD->getIntPtrType();
10708               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10709               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
10710             }
10711           }
10712         }
10713         if (isa<Constant>(SO1) && isa<Constant>(GO1))
10714           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10715         else {
10716           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10717           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
10718         }
10719       }
10720
10721       // Recycle the GEP we already have if possible.
10722       if (SrcGEPOperands.size() == 2) {
10723         GEP.setOperand(0, SrcGEPOperands[0]);
10724         GEP.setOperand(1, Sum);
10725         return &GEP;
10726       } else {
10727         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10728                        SrcGEPOperands.end()-1);
10729         Indices.push_back(Sum);
10730         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10731       }
10732     } else if (isa<Constant>(*GEP.idx_begin()) &&
10733                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10734                SrcGEPOperands.size() != 1) {
10735       // Otherwise we can do the fold if the first index of the GEP is a zero
10736       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10737                      SrcGEPOperands.end());
10738       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10739     }
10740
10741     if (!Indices.empty())
10742       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10743                                        Indices.end(), GEP.getName());
10744
10745   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
10746     // GEP of global variable.  If all of the indices for this GEP are
10747     // constants, we can promote this to a constexpr instead of an instruction.
10748
10749     // Scan for nonconstants...
10750     SmallVector<Constant*, 8> Indices;
10751     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10752     for (; I != E && isa<Constant>(*I); ++I)
10753       Indices.push_back(cast<Constant>(*I));
10754
10755     if (I == E) {  // If they are all constants...
10756       Constant *CE = ConstantExpr::getGetElementPtr(GV,
10757                                                     &Indices[0],Indices.size());
10758
10759       // Replace all uses of the GEP with the new constexpr...
10760       return ReplaceInstUsesWith(GEP, CE);
10761     }
10762   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
10763     if (!isa<PointerType>(X->getType())) {
10764       // Not interesting.  Source pointer must be a cast from pointer.
10765     } else if (HasZeroPointerIndex) {
10766       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10767       // into     : GEP [10 x i8]* X, i32 0, ...
10768       //
10769       // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
10770       //           into     : GEP i8* X, ...
10771       // 
10772       // This occurs when the program declares an array extern like "int X[];"
10773       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10774       const PointerType *XTy = cast<PointerType>(X->getType());
10775       if (const ArrayType *CATy =
10776           dyn_cast<ArrayType>(CPTy->getElementType())) {
10777         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
10778         if (CATy->getElementType() == XTy->getElementType()) {
10779           // -> GEP i8* X, ...
10780           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
10781           return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
10782                                            GEP.getName());
10783         } else if (const ArrayType *XATy =
10784                  dyn_cast<ArrayType>(XTy->getElementType())) {
10785           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
10786           if (CATy->getElementType() == XATy->getElementType()) {
10787             // -> GEP [10 x i8]* X, i32 0, ...
10788             // At this point, we know that the cast source type is a pointer
10789             // to an array of the same type as the destination pointer
10790             // array.  Because the array type is never stepped over (there
10791             // is a leading zero) we can fold the cast into this GEP.
10792             GEP.setOperand(0, X);
10793             return &GEP;
10794           }
10795         }
10796       }
10797     } else if (GEP.getNumOperands() == 2) {
10798       // Transform things like:
10799       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10800       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
10801       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10802       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10803       if (isa<ArrayType>(SrcElTy) &&
10804           TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10805           TD->getTypePaddedSize(ResElTy)) {
10806         Value *Idx[2];
10807         Idx[0] = Constant::getNullValue(Type::Int32Ty);
10808         Idx[1] = GEP.getOperand(1);
10809         Value *V = InsertNewInstBefore(
10810                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
10811         // V and GEP are both pointer types --> BitCast
10812         return new BitCastInst(V, GEP.getType());
10813       }
10814       
10815       // Transform things like:
10816       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
10817       //   (where tmp = 8*tmp2) into:
10818       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
10819       
10820       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
10821         uint64_t ArrayEltSize =
10822             TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType());
10823         
10824         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
10825         // allow either a mul, shift, or constant here.
10826         Value *NewIdx = 0;
10827         ConstantInt *Scale = 0;
10828         if (ArrayEltSize == 1) {
10829           NewIdx = GEP.getOperand(1);
10830           Scale = ConstantInt::get(NewIdx->getType(), 1);
10831         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10832           NewIdx = ConstantInt::get(CI->getType(), 1);
10833           Scale = CI;
10834         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10835           if (Inst->getOpcode() == Instruction::Shl &&
10836               isa<ConstantInt>(Inst->getOperand(1))) {
10837             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10838             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10839             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
10840             NewIdx = Inst->getOperand(0);
10841           } else if (Inst->getOpcode() == Instruction::Mul &&
10842                      isa<ConstantInt>(Inst->getOperand(1))) {
10843             Scale = cast<ConstantInt>(Inst->getOperand(1));
10844             NewIdx = Inst->getOperand(0);
10845           }
10846         }
10847         
10848         // If the index will be to exactly the right offset with the scale taken
10849         // out, perform the transformation. Note, we don't know whether Scale is
10850         // signed or not. We'll use unsigned version of division/modulo
10851         // operation after making sure Scale doesn't have the sign bit set.
10852         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
10853             Scale->getZExtValue() % ArrayEltSize == 0) {
10854           Scale = ConstantInt::get(Scale->getType(),
10855                                    Scale->getZExtValue() / ArrayEltSize);
10856           if (Scale->getZExtValue() != 1) {
10857             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
10858                                                        false /*ZExt*/);
10859             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
10860             NewIdx = InsertNewInstBefore(Sc, GEP);
10861           }
10862
10863           // Insert the new GEP instruction.
10864           Value *Idx[2];
10865           Idx[0] = Constant::getNullValue(Type::Int32Ty);
10866           Idx[1] = NewIdx;
10867           Instruction *NewGEP =
10868             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
10869           NewGEP = InsertNewInstBefore(NewGEP, GEP);
10870           // The NewGEP must be pointer typed, so must the old one -> BitCast
10871           return new BitCastInst(NewGEP, GEP.getType());
10872         }
10873       }
10874     }
10875   }
10876   
10877   /// See if we can simplify:
10878   ///   X = bitcast A to B*
10879   ///   Y = gep X, <...constant indices...>
10880   /// into a gep of the original struct.  This is important for SROA and alias
10881   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
10882   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
10883     if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
10884       // Determine how much the GEP moves the pointer.  We are guaranteed to get
10885       // a constant back from EmitGEPOffset.
10886       ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
10887       int64_t Offset = OffsetV->getSExtValue();
10888       
10889       // If this GEP instruction doesn't move the pointer, just replace the GEP
10890       // with a bitcast of the real input to the dest type.
10891       if (Offset == 0) {
10892         // If the bitcast is of an allocation, and the allocation will be
10893         // converted to match the type of the cast, don't touch this.
10894         if (isa<AllocationInst>(BCI->getOperand(0))) {
10895           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
10896           if (Instruction *I = visitBitCast(*BCI)) {
10897             if (I != BCI) {
10898               I->takeName(BCI);
10899               BCI->getParent()->getInstList().insert(BCI, I);
10900               ReplaceInstUsesWith(*BCI, I);
10901             }
10902             return &GEP;
10903           }
10904         }
10905         return new BitCastInst(BCI->getOperand(0), GEP.getType());
10906       }
10907       
10908       // Otherwise, if the offset is non-zero, we need to find out if there is a
10909       // field at Offset in 'A's type.  If so, we can pull the cast through the
10910       // GEP.
10911       SmallVector<Value*, 8> NewIndices;
10912       const Type *InTy =
10913         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
10914       if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
10915         Instruction *NGEP =
10916            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
10917                                      NewIndices.end());
10918         if (NGEP->getType() == GEP.getType()) return NGEP;
10919         InsertNewInstBefore(NGEP, GEP);
10920         NGEP->takeName(&GEP);
10921         return new BitCastInst(NGEP, GEP.getType());
10922       }
10923     }
10924   }    
10925     
10926   return 0;
10927 }
10928
10929 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10930   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
10931   if (AI.isArrayAllocation()) {  // Check C != 1
10932     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10933       const Type *NewTy = 
10934         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
10935       AllocationInst *New = 0;
10936
10937       // Create and insert the replacement instruction...
10938       if (isa<MallocInst>(AI))
10939         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
10940       else {
10941         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
10942         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
10943       }
10944
10945       InsertNewInstBefore(New, AI);
10946
10947       // Scan to the end of the allocation instructions, to skip over a block of
10948       // allocas if possible...
10949       //
10950       BasicBlock::iterator It = New;
10951       while (isa<AllocationInst>(*It)) ++It;
10952
10953       // Now that I is pointing to the first non-allocation-inst in the block,
10954       // insert our getelementptr instruction...
10955       //
10956       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
10957       Value *Idx[2];
10958       Idx[0] = NullIdx;
10959       Idx[1] = NullIdx;
10960       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10961                                            New->getName()+".sub", It);
10962
10963       // Now make everything use the getelementptr instead of the original
10964       // allocation.
10965       return ReplaceInstUsesWith(AI, V);
10966     } else if (isa<UndefValue>(AI.getArraySize())) {
10967       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10968     }
10969   }
10970
10971   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
10972     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10973     // Note that we only do this for alloca's, because malloc should allocate and
10974     // return a unique pointer, even for a zero byte allocation.
10975     if (TD->getTypePaddedSize(AI.getAllocatedType()) == 0)
10976       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10977
10978     // If the alignment is 0 (unspecified), assign it the preferred alignment.
10979     if (AI.getAlignment() == 0)
10980       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
10981   }
10982
10983   return 0;
10984 }
10985
10986 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10987   Value *Op = FI.getOperand(0);
10988
10989   // free undef -> unreachable.
10990   if (isa<UndefValue>(Op)) {
10991     // Insert a new store to null because we cannot modify the CFG here.
10992     new StoreInst(ConstantInt::getTrue(),
10993                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
10994     return EraseInstFromFunction(FI);
10995   }
10996   
10997   // If we have 'free null' delete the instruction.  This can happen in stl code
10998   // when lots of inlining happens.
10999   if (isa<ConstantPointerNull>(Op))
11000     return EraseInstFromFunction(FI);
11001   
11002   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11003   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11004     FI.setOperand(0, CI->getOperand(0));
11005     return &FI;
11006   }
11007   
11008   // Change free (gep X, 0,0,0,0) into free(X)
11009   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11010     if (GEPI->hasAllZeroIndices()) {
11011       AddToWorkList(GEPI);
11012       FI.setOperand(0, GEPI->getOperand(0));
11013       return &FI;
11014     }
11015   }
11016   
11017   // Change free(malloc) into nothing, if the malloc has a single use.
11018   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11019     if (MI->hasOneUse()) {
11020       EraseInstFromFunction(FI);
11021       return EraseInstFromFunction(*MI);
11022     }
11023
11024   return 0;
11025 }
11026
11027
11028 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11029 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11030                                         const TargetData *TD) {
11031   User *CI = cast<User>(LI.getOperand(0));
11032   Value *CastOp = CI->getOperand(0);
11033
11034   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11035     // Instead of loading constant c string, use corresponding integer value
11036     // directly if string length is small enough.
11037     std::string Str;
11038     if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11039       unsigned len = Str.length();
11040       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11041       unsigned numBits = Ty->getPrimitiveSizeInBits();
11042       // Replace LI with immediate integer store.
11043       if ((numBits >> 3) == len + 1) {
11044         APInt StrVal(numBits, 0);
11045         APInt SingleChar(numBits, 0);
11046         if (TD->isLittleEndian()) {
11047           for (signed i = len-1; i >= 0; i--) {
11048             SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11049             StrVal = (StrVal << 8) | SingleChar;
11050           }
11051         } else {
11052           for (unsigned i = 0; i < len; i++) {
11053             SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11054             StrVal = (StrVal << 8) | SingleChar;
11055           }
11056           // Append NULL at the end.
11057           SingleChar = 0;
11058           StrVal = (StrVal << 8) | SingleChar;
11059         }
11060         Value *NL = ConstantInt::get(StrVal);
11061         return IC.ReplaceInstUsesWith(LI, NL);
11062       }
11063     }
11064   }
11065
11066   const PointerType *DestTy = cast<PointerType>(CI->getType());
11067   const Type *DestPTy = DestTy->getElementType();
11068   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11069
11070     // If the address spaces don't match, don't eliminate the cast.
11071     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11072       return 0;
11073
11074     const Type *SrcPTy = SrcTy->getElementType();
11075
11076     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11077          isa<VectorType>(DestPTy)) {
11078       // If the source is an array, the code below will not succeed.  Check to
11079       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11080       // constants.
11081       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11082         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11083           if (ASrcTy->getNumElements() != 0) {
11084             Value *Idxs[2];
11085             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
11086             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11087             SrcTy = cast<PointerType>(CastOp->getType());
11088             SrcPTy = SrcTy->getElementType();
11089           }
11090
11091       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11092             isa<VectorType>(SrcPTy)) &&
11093           // Do not allow turning this into a load of an integer, which is then
11094           // casted to a pointer, this pessimizes pointer analysis a lot.
11095           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11096           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11097                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11098
11099         // Okay, we are casting from one integer or pointer type to another of
11100         // the same size.  Instead of casting the pointer before the load, cast
11101         // the result of the loaded value.
11102         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11103                                                              CI->getName(),
11104                                                          LI.isVolatile()),LI);
11105         // Now cast the result of the load.
11106         return new BitCastInst(NewLoad, LI.getType());
11107       }
11108     }
11109   }
11110   return 0;
11111 }
11112
11113 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
11114 /// from this value cannot trap.  If it is not obviously safe to load from the
11115 /// specified pointer, we do a quick local scan of the basic block containing
11116 /// ScanFrom, to determine if the address is already accessed.
11117 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
11118   // If it is an alloca it is always safe to load from.
11119   if (isa<AllocaInst>(V)) return true;
11120
11121   // If it is a global variable it is mostly safe to load from.
11122   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
11123     // Don't try to evaluate aliases.  External weak GV can be null.
11124     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
11125
11126   // Otherwise, be a little bit agressive by scanning the local block where we
11127   // want to check to see if the pointer is already being loaded or stored
11128   // from/to.  If so, the previous load or store would have already trapped,
11129   // so there is no harm doing an extra load (also, CSE will later eliminate
11130   // the load entirely).
11131   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
11132
11133   while (BBI != E) {
11134     --BBI;
11135
11136     // If we see a free or a call (which might do a free) the pointer could be
11137     // marked invalid.
11138     if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
11139       return false;
11140     
11141     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11142       if (LI->getOperand(0) == V) return true;
11143     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
11144       if (SI->getOperand(1) == V) return true;
11145     }
11146
11147   }
11148   return false;
11149 }
11150
11151 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11152   Value *Op = LI.getOperand(0);
11153
11154   // Attempt to improve the alignment.
11155   unsigned KnownAlign =
11156     GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11157   if (KnownAlign >
11158       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11159                                 LI.getAlignment()))
11160     LI.setAlignment(KnownAlign);
11161
11162   // load (cast X) --> cast (load X) iff safe
11163   if (isa<CastInst>(Op))
11164     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11165       return Res;
11166
11167   // None of the following transforms are legal for volatile loads.
11168   if (LI.isVolatile()) return 0;
11169   
11170   // Do really simple store-to-load forwarding and load CSE, to catch cases
11171   // where there are several consequtive memory accesses to the same location,
11172   // separated by a few arithmetic operations.
11173   BasicBlock::iterator BBI = &LI;
11174   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11175     return ReplaceInstUsesWith(LI, AvailableVal);
11176
11177   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11178     const Value *GEPI0 = GEPI->getOperand(0);
11179     // TODO: Consider a target hook for valid address spaces for this xform.
11180     if (isa<ConstantPointerNull>(GEPI0) &&
11181         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11182       // Insert a new store to null instruction before the load to indicate
11183       // that this code is not reachable.  We do this instead of inserting
11184       // an unreachable instruction directly because we cannot modify the
11185       // CFG.
11186       new StoreInst(UndefValue::get(LI.getType()),
11187                     Constant::getNullValue(Op->getType()), &LI);
11188       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11189     }
11190   } 
11191
11192   if (Constant *C = dyn_cast<Constant>(Op)) {
11193     // load null/undef -> undef
11194     // TODO: Consider a target hook for valid address spaces for this xform.
11195     if (isa<UndefValue>(C) || (C->isNullValue() && 
11196         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11197       // Insert a new store to null instruction before the load to indicate that
11198       // this code is not reachable.  We do this instead of inserting an
11199       // unreachable instruction directly because we cannot modify the CFG.
11200       new StoreInst(UndefValue::get(LI.getType()),
11201                     Constant::getNullValue(Op->getType()), &LI);
11202       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11203     }
11204
11205     // Instcombine load (constant global) into the value loaded.
11206     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11207       if (GV->isConstant() && !GV->isDeclaration())
11208         return ReplaceInstUsesWith(LI, GV->getInitializer());
11209
11210     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11211     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11212       if (CE->getOpcode() == Instruction::GetElementPtr) {
11213         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11214           if (GV->isConstant() && !GV->isDeclaration())
11215             if (Constant *V = 
11216                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
11217               return ReplaceInstUsesWith(LI, V);
11218         if (CE->getOperand(0)->isNullValue()) {
11219           // Insert a new store to null instruction before the load to indicate
11220           // that this code is not reachable.  We do this instead of inserting
11221           // an unreachable instruction directly because we cannot modify the
11222           // CFG.
11223           new StoreInst(UndefValue::get(LI.getType()),
11224                         Constant::getNullValue(Op->getType()), &LI);
11225           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11226         }
11227
11228       } else if (CE->isCast()) {
11229         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11230           return Res;
11231       }
11232     }
11233   }
11234     
11235   // If this load comes from anywhere in a constant global, and if the global
11236   // is all undef or zero, we know what it loads.
11237   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11238     if (GV->isConstant() && GV->hasInitializer()) {
11239       if (GV->getInitializer()->isNullValue())
11240         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11241       else if (isa<UndefValue>(GV->getInitializer()))
11242         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11243     }
11244   }
11245
11246   if (Op->hasOneUse()) {
11247     // Change select and PHI nodes to select values instead of addresses: this
11248     // helps alias analysis out a lot, allows many others simplifications, and
11249     // exposes redundancy in the code.
11250     //
11251     // Note that we cannot do the transformation unless we know that the
11252     // introduced loads cannot trap!  Something like this is valid as long as
11253     // the condition is always false: load (select bool %C, int* null, int* %G),
11254     // but it would not be valid if we transformed it to load from null
11255     // unconditionally.
11256     //
11257     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11258       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11259       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11260           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11261         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11262                                      SI->getOperand(1)->getName()+".val"), LI);
11263         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11264                                      SI->getOperand(2)->getName()+".val"), LI);
11265         return SelectInst::Create(SI->getCondition(), V1, V2);
11266       }
11267
11268       // load (select (cond, null, P)) -> load P
11269       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11270         if (C->isNullValue()) {
11271           LI.setOperand(0, SI->getOperand(2));
11272           return &LI;
11273         }
11274
11275       // load (select (cond, P, null)) -> load P
11276       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11277         if (C->isNullValue()) {
11278           LI.setOperand(0, SI->getOperand(1));
11279           return &LI;
11280         }
11281     }
11282   }
11283   return 0;
11284 }
11285
11286 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11287 /// when possible.  This makes it generally easy to do alias analysis and/or
11288 /// SROA/mem2reg of the memory object.
11289 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11290   User *CI = cast<User>(SI.getOperand(1));
11291   Value *CastOp = CI->getOperand(0);
11292
11293   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11294   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11295   if (SrcTy == 0) return 0;
11296   
11297   const Type *SrcPTy = SrcTy->getElementType();
11298
11299   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11300     return 0;
11301   
11302   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11303   /// to its first element.  This allows us to handle things like:
11304   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11305   /// on 32-bit hosts.
11306   SmallVector<Value*, 4> NewGEPIndices;
11307   
11308   // If the source is an array, the code below will not succeed.  Check to
11309   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11310   // constants.
11311   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11312     // Index through pointer.
11313     Constant *Zero = Constant::getNullValue(Type::Int32Ty);
11314     NewGEPIndices.push_back(Zero);
11315     
11316     while (1) {
11317       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11318         if (!STy->getNumElements()) /* Struct can be empty {} */
11319           break;
11320         NewGEPIndices.push_back(Zero);
11321         SrcPTy = STy->getElementType(0);
11322       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11323         NewGEPIndices.push_back(Zero);
11324         SrcPTy = ATy->getElementType();
11325       } else {
11326         break;
11327       }
11328     }
11329     
11330     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11331   }
11332
11333   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11334     return 0;
11335   
11336   // If the pointers point into different address spaces or if they point to
11337   // values with different sizes, we can't do the transformation.
11338   if (SrcTy->getAddressSpace() != 
11339         cast<PointerType>(CI->getType())->getAddressSpace() ||
11340       IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
11341       IC.getTargetData().getTypeSizeInBits(DestPTy))
11342     return 0;
11343
11344   // Okay, we are casting from one integer or pointer type to another of
11345   // the same size.  Instead of casting the pointer before 
11346   // the store, cast the value to be stored.
11347   Value *NewCast;
11348   Value *SIOp0 = SI.getOperand(0);
11349   Instruction::CastOps opcode = Instruction::BitCast;
11350   const Type* CastSrcTy = SIOp0->getType();
11351   const Type* CastDstTy = SrcPTy;
11352   if (isa<PointerType>(CastDstTy)) {
11353     if (CastSrcTy->isInteger())
11354       opcode = Instruction::IntToPtr;
11355   } else if (isa<IntegerType>(CastDstTy)) {
11356     if (isa<PointerType>(SIOp0->getType()))
11357       opcode = Instruction::PtrToInt;
11358   }
11359   
11360   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11361   // emit a GEP to index into its first field.
11362   if (!NewGEPIndices.empty()) {
11363     if (Constant *C = dyn_cast<Constant>(CastOp))
11364       CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0], 
11365                                               NewGEPIndices.size());
11366     else
11367       CastOp = IC.InsertNewInstBefore(
11368               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11369                                         NewGEPIndices.end()), SI);
11370   }
11371   
11372   if (Constant *C = dyn_cast<Constant>(SIOp0))
11373     NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11374   else
11375     NewCast = IC.InsertNewInstBefore(
11376       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11377       SI);
11378   return new StoreInst(NewCast, CastOp);
11379 }
11380
11381 /// equivalentAddressValues - Test if A and B will obviously have the same
11382 /// value. This includes recognizing that %t0 and %t1 will have the same
11383 /// value in code like this:
11384 ///   %t0 = getelementptr @a, 0, 3
11385 ///   store i32 0, i32* %t0
11386 ///   %t1 = getelementptr @a, 0, 3
11387 ///   %t2 = load i32* %t1
11388 ///
11389 static bool equivalentAddressValues(Value *A, Value *B) {
11390   // Test if the values are trivially equivalent.
11391   if (A == B) return true;
11392   
11393   // Test if the values come form identical arithmetic instructions.
11394   if (isa<BinaryOperator>(A) ||
11395       isa<CastInst>(A) ||
11396       isa<PHINode>(A) ||
11397       isa<GetElementPtrInst>(A))
11398     if (Instruction *BI = dyn_cast<Instruction>(B))
11399       if (cast<Instruction>(A)->isIdenticalTo(BI))
11400         return true;
11401   
11402   // Otherwise they may not be equivalent.
11403   return false;
11404 }
11405
11406 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11407   Value *Val = SI.getOperand(0);
11408   Value *Ptr = SI.getOperand(1);
11409
11410   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11411     EraseInstFromFunction(SI);
11412     ++NumCombined;
11413     return 0;
11414   }
11415   
11416   // If the RHS is an alloca with a single use, zapify the store, making the
11417   // alloca dead.
11418   if (Ptr->hasOneUse() && !SI.isVolatile()) {
11419     if (isa<AllocaInst>(Ptr)) {
11420       EraseInstFromFunction(SI);
11421       ++NumCombined;
11422       return 0;
11423     }
11424     
11425     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
11426       if (isa<AllocaInst>(GEP->getOperand(0)) &&
11427           GEP->getOperand(0)->hasOneUse()) {
11428         EraseInstFromFunction(SI);
11429         ++NumCombined;
11430         return 0;
11431       }
11432   }
11433
11434   // Attempt to improve the alignment.
11435   unsigned KnownAlign =
11436     GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11437   if (KnownAlign >
11438       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11439                                 SI.getAlignment()))
11440     SI.setAlignment(KnownAlign);
11441
11442   // Do really simple DSE, to catch cases where there are several consecutive
11443   // stores to the same location, separated by a few arithmetic operations. This
11444   // situation often occurs with bitfield accesses.
11445   BasicBlock::iterator BBI = &SI;
11446   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11447        --ScanInsts) {
11448     // Don't count debug info directives, lest they affect codegen.
11449     if (isa<DbgInfoIntrinsic>(BBI)) {
11450       ScanInsts++;
11451       --BBI;
11452       continue;
11453     }    
11454     --BBI;
11455     
11456     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11457       // Prev store isn't volatile, and stores to the same location?
11458       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11459                                                           SI.getOperand(1))) {
11460         ++NumDeadStore;
11461         ++BBI;
11462         EraseInstFromFunction(*PrevSI);
11463         continue;
11464       }
11465       break;
11466     }
11467     
11468     // If this is a load, we have to stop.  However, if the loaded value is from
11469     // the pointer we're loading and is producing the pointer we're storing,
11470     // then *this* store is dead (X = load P; store X -> P).
11471     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11472       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11473           !SI.isVolatile()) {
11474         EraseInstFromFunction(SI);
11475         ++NumCombined;
11476         return 0;
11477       }
11478       // Otherwise, this is a load from some other location.  Stores before it
11479       // may not be dead.
11480       break;
11481     }
11482     
11483     // Don't skip over loads or things that can modify memory.
11484     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11485       break;
11486   }
11487   
11488   
11489   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11490
11491   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11492   if (isa<ConstantPointerNull>(Ptr)) {
11493     if (!isa<UndefValue>(Val)) {
11494       SI.setOperand(0, UndefValue::get(Val->getType()));
11495       if (Instruction *U = dyn_cast<Instruction>(Val))
11496         AddToWorkList(U);  // Dropped a use.
11497       ++NumCombined;
11498     }
11499     return 0;  // Do not modify these!
11500   }
11501
11502   // store undef, Ptr -> noop
11503   if (isa<UndefValue>(Val)) {
11504     EraseInstFromFunction(SI);
11505     ++NumCombined;
11506     return 0;
11507   }
11508
11509   // If the pointer destination is a cast, see if we can fold the cast into the
11510   // source instead.
11511   if (isa<CastInst>(Ptr))
11512     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11513       return Res;
11514   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11515     if (CE->isCast())
11516       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11517         return Res;
11518
11519   
11520   // If this store is the last instruction in the basic block, and if the block
11521   // ends with an unconditional branch, try to move it to the successor block.
11522   BBI = &SI; ++BBI;
11523   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11524     if (BI->isUnconditional())
11525       if (SimplifyStoreAtEndOfBlock(SI))
11526         return 0;  // xform done!
11527   
11528   return 0;
11529 }
11530
11531 /// SimplifyStoreAtEndOfBlock - Turn things like:
11532 ///   if () { *P = v1; } else { *P = v2 }
11533 /// into a phi node with a store in the successor.
11534 ///
11535 /// Simplify things like:
11536 ///   *P = v1; if () { *P = v2; }
11537 /// into a phi node with a store in the successor.
11538 ///
11539 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11540   BasicBlock *StoreBB = SI.getParent();
11541   
11542   // Check to see if the successor block has exactly two incoming edges.  If
11543   // so, see if the other predecessor contains a store to the same location.
11544   // if so, insert a PHI node (if needed) and move the stores down.
11545   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11546   
11547   // Determine whether Dest has exactly two predecessors and, if so, compute
11548   // the other predecessor.
11549   pred_iterator PI = pred_begin(DestBB);
11550   BasicBlock *OtherBB = 0;
11551   if (*PI != StoreBB)
11552     OtherBB = *PI;
11553   ++PI;
11554   if (PI == pred_end(DestBB))
11555     return false;
11556   
11557   if (*PI != StoreBB) {
11558     if (OtherBB)
11559       return false;
11560     OtherBB = *PI;
11561   }
11562   if (++PI != pred_end(DestBB))
11563     return false;
11564
11565   // Bail out if all the relevant blocks aren't distinct (this can happen,
11566   // for example, if SI is in an infinite loop)
11567   if (StoreBB == DestBB || OtherBB == DestBB)
11568     return false;
11569
11570   // Verify that the other block ends in a branch and is not otherwise empty.
11571   BasicBlock::iterator BBI = OtherBB->getTerminator();
11572   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11573   if (!OtherBr || BBI == OtherBB->begin())
11574     return false;
11575   
11576   // If the other block ends in an unconditional branch, check for the 'if then
11577   // else' case.  there is an instruction before the branch.
11578   StoreInst *OtherStore = 0;
11579   if (OtherBr->isUnconditional()) {
11580     // If this isn't a store, or isn't a store to the same location, bail out.
11581     --BBI;
11582     OtherStore = dyn_cast<StoreInst>(BBI);
11583     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11584       return false;
11585   } else {
11586     // Otherwise, the other block ended with a conditional branch. If one of the
11587     // destinations is StoreBB, then we have the if/then case.
11588     if (OtherBr->getSuccessor(0) != StoreBB && 
11589         OtherBr->getSuccessor(1) != StoreBB)
11590       return false;
11591     
11592     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11593     // if/then triangle.  See if there is a store to the same ptr as SI that
11594     // lives in OtherBB.
11595     for (;; --BBI) {
11596       // Check to see if we find the matching store.
11597       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11598         if (OtherStore->getOperand(1) != SI.getOperand(1))
11599           return false;
11600         break;
11601       }
11602       // If we find something that may be using or overwriting the stored
11603       // value, or if we run out of instructions, we can't do the xform.
11604       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11605           BBI == OtherBB->begin())
11606         return false;
11607     }
11608     
11609     // In order to eliminate the store in OtherBr, we have to
11610     // make sure nothing reads or overwrites the stored value in
11611     // StoreBB.
11612     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11613       // FIXME: This should really be AA driven.
11614       if (I->mayReadFromMemory() || I->mayWriteToMemory())
11615         return false;
11616     }
11617   }
11618   
11619   // Insert a PHI node now if we need it.
11620   Value *MergedVal = OtherStore->getOperand(0);
11621   if (MergedVal != SI.getOperand(0)) {
11622     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11623     PN->reserveOperandSpace(2);
11624     PN->addIncoming(SI.getOperand(0), SI.getParent());
11625     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11626     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11627   }
11628   
11629   // Advance to a place where it is safe to insert the new store and
11630   // insert it.
11631   BBI = DestBB->getFirstNonPHI();
11632   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11633                                     OtherStore->isVolatile()), *BBI);
11634   
11635   // Nuke the old stores.
11636   EraseInstFromFunction(SI);
11637   EraseInstFromFunction(*OtherStore);
11638   ++NumCombined;
11639   return true;
11640 }
11641
11642
11643 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11644   // Change br (not X), label True, label False to: br X, label False, True
11645   Value *X = 0;
11646   BasicBlock *TrueDest;
11647   BasicBlock *FalseDest;
11648   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11649       !isa<Constant>(X)) {
11650     // Swap Destinations and condition...
11651     BI.setCondition(X);
11652     BI.setSuccessor(0, FalseDest);
11653     BI.setSuccessor(1, TrueDest);
11654     return &BI;
11655   }
11656
11657   // Cannonicalize fcmp_one -> fcmp_oeq
11658   FCmpInst::Predicate FPred; Value *Y;
11659   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
11660                              TrueDest, FalseDest)))
11661     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11662          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11663       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
11664       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
11665       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11666       NewSCC->takeName(I);
11667       // Swap Destinations and condition...
11668       BI.setCondition(NewSCC);
11669       BI.setSuccessor(0, FalseDest);
11670       BI.setSuccessor(1, TrueDest);
11671       RemoveFromWorkList(I);
11672       I->eraseFromParent();
11673       AddToWorkList(NewSCC);
11674       return &BI;
11675     }
11676
11677   // Cannonicalize icmp_ne -> icmp_eq
11678   ICmpInst::Predicate IPred;
11679   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11680                       TrueDest, FalseDest)))
11681     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
11682          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11683          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11684       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
11685       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
11686       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11687       NewSCC->takeName(I);
11688       // Swap Destinations and condition...
11689       BI.setCondition(NewSCC);
11690       BI.setSuccessor(0, FalseDest);
11691       BI.setSuccessor(1, TrueDest);
11692       RemoveFromWorkList(I);
11693       I->eraseFromParent();;
11694       AddToWorkList(NewSCC);
11695       return &BI;
11696     }
11697
11698   return 0;
11699 }
11700
11701 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11702   Value *Cond = SI.getCondition();
11703   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11704     if (I->getOpcode() == Instruction::Add)
11705       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11706         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11707         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11708           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11709                                                 AddRHS));
11710         SI.setOperand(0, I->getOperand(0));
11711         AddToWorkList(I);
11712         return &SI;
11713       }
11714   }
11715   return 0;
11716 }
11717
11718 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
11719   Value *Agg = EV.getAggregateOperand();
11720
11721   if (!EV.hasIndices())
11722     return ReplaceInstUsesWith(EV, Agg);
11723
11724   if (Constant *C = dyn_cast<Constant>(Agg)) {
11725     if (isa<UndefValue>(C))
11726       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11727       
11728     if (isa<ConstantAggregateZero>(C))
11729       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11730
11731     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11732       // Extract the element indexed by the first index out of the constant
11733       Value *V = C->getOperand(*EV.idx_begin());
11734       if (EV.getNumIndices() > 1)
11735         // Extract the remaining indices out of the constant indexed by the
11736         // first index
11737         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11738       else
11739         return ReplaceInstUsesWith(EV, V);
11740     }
11741     return 0; // Can't handle other constants
11742   } 
11743   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11744     // We're extracting from an insertvalue instruction, compare the indices
11745     const unsigned *exti, *exte, *insi, *inse;
11746     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11747          exte = EV.idx_end(), inse = IV->idx_end();
11748          exti != exte && insi != inse;
11749          ++exti, ++insi) {
11750       if (*insi != *exti)
11751         // The insert and extract both reference distinctly different elements.
11752         // This means the extract is not influenced by the insert, and we can
11753         // replace the aggregate operand of the extract with the aggregate
11754         // operand of the insert. i.e., replace
11755         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11756         // %E = extractvalue { i32, { i32 } } %I, 0
11757         // with
11758         // %E = extractvalue { i32, { i32 } } %A, 0
11759         return ExtractValueInst::Create(IV->getAggregateOperand(),
11760                                         EV.idx_begin(), EV.idx_end());
11761     }
11762     if (exti == exte && insi == inse)
11763       // Both iterators are at the end: Index lists are identical. Replace
11764       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11765       // %C = extractvalue { i32, { i32 } } %B, 1, 0
11766       // with "i32 42"
11767       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11768     if (exti == exte) {
11769       // The extract list is a prefix of the insert list. i.e. replace
11770       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11771       // %E = extractvalue { i32, { i32 } } %I, 1
11772       // with
11773       // %X = extractvalue { i32, { i32 } } %A, 1
11774       // %E = insertvalue { i32 } %X, i32 42, 0
11775       // by switching the order of the insert and extract (though the
11776       // insertvalue should be left in, since it may have other uses).
11777       Value *NewEV = InsertNewInstBefore(
11778         ExtractValueInst::Create(IV->getAggregateOperand(),
11779                                  EV.idx_begin(), EV.idx_end()),
11780         EV);
11781       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11782                                      insi, inse);
11783     }
11784     if (insi == inse)
11785       // The insert list is a prefix of the extract list
11786       // We can simply remove the common indices from the extract and make it
11787       // operate on the inserted value instead of the insertvalue result.
11788       // i.e., replace
11789       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11790       // %E = extractvalue { i32, { i32 } } %I, 1, 0
11791       // with
11792       // %E extractvalue { i32 } { i32 42 }, 0
11793       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
11794                                       exti, exte);
11795   }
11796   // Can't simplify extracts from other values. Note that nested extracts are
11797   // already simplified implicitely by the above (extract ( extract (insert) )
11798   // will be translated into extract ( insert ( extract ) ) first and then just
11799   // the value inserted, if appropriate).
11800   return 0;
11801 }
11802
11803 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11804 /// is to leave as a vector operation.
11805 static bool CheapToScalarize(Value *V, bool isConstant) {
11806   if (isa<ConstantAggregateZero>(V)) 
11807     return true;
11808   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
11809     if (isConstant) return true;
11810     // If all elts are the same, we can extract.
11811     Constant *Op0 = C->getOperand(0);
11812     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11813       if (C->getOperand(i) != Op0)
11814         return false;
11815     return true;
11816   }
11817   Instruction *I = dyn_cast<Instruction>(V);
11818   if (!I) return false;
11819   
11820   // Insert element gets simplified to the inserted element or is deleted if
11821   // this is constant idx extract element and its a constant idx insertelt.
11822   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11823       isa<ConstantInt>(I->getOperand(2)))
11824     return true;
11825   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11826     return true;
11827   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11828     if (BO->hasOneUse() &&
11829         (CheapToScalarize(BO->getOperand(0), isConstant) ||
11830          CheapToScalarize(BO->getOperand(1), isConstant)))
11831       return true;
11832   if (CmpInst *CI = dyn_cast<CmpInst>(I))
11833     if (CI->hasOneUse() &&
11834         (CheapToScalarize(CI->getOperand(0), isConstant) ||
11835          CheapToScalarize(CI->getOperand(1), isConstant)))
11836       return true;
11837   
11838   return false;
11839 }
11840
11841 /// Read and decode a shufflevector mask.
11842 ///
11843 /// It turns undef elements into values that are larger than the number of
11844 /// elements in the input.
11845 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11846   unsigned NElts = SVI->getType()->getNumElements();
11847   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11848     return std::vector<unsigned>(NElts, 0);
11849   if (isa<UndefValue>(SVI->getOperand(2)))
11850     return std::vector<unsigned>(NElts, 2*NElts);
11851
11852   std::vector<unsigned> Result;
11853   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
11854   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
11855     if (isa<UndefValue>(*i))
11856       Result.push_back(NElts*2);  // undef -> 8
11857     else
11858       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
11859   return Result;
11860 }
11861
11862 /// FindScalarElement - Given a vector and an element number, see if the scalar
11863 /// value is already around as a register, for example if it were inserted then
11864 /// extracted from the vector.
11865 static Value *FindScalarElement(Value *V, unsigned EltNo) {
11866   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11867   const VectorType *PTy = cast<VectorType>(V->getType());
11868   unsigned Width = PTy->getNumElements();
11869   if (EltNo >= Width)  // Out of range access.
11870     return UndefValue::get(PTy->getElementType());
11871   
11872   if (isa<UndefValue>(V))
11873     return UndefValue::get(PTy->getElementType());
11874   else if (isa<ConstantAggregateZero>(V))
11875     return Constant::getNullValue(PTy->getElementType());
11876   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
11877     return CP->getOperand(EltNo);
11878   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11879     // If this is an insert to a variable element, we don't know what it is.
11880     if (!isa<ConstantInt>(III->getOperand(2))) 
11881       return 0;
11882     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
11883     
11884     // If this is an insert to the element we are looking for, return the
11885     // inserted value.
11886     if (EltNo == IIElt) 
11887       return III->getOperand(1);
11888     
11889     // Otherwise, the insertelement doesn't modify the value, recurse on its
11890     // vector input.
11891     return FindScalarElement(III->getOperand(0), EltNo);
11892   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
11893     unsigned LHSWidth =
11894       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11895     unsigned InEl = getShuffleMask(SVI)[EltNo];
11896     if (InEl < LHSWidth)
11897       return FindScalarElement(SVI->getOperand(0), InEl);
11898     else if (InEl < LHSWidth*2)
11899       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
11900     else
11901       return UndefValue::get(PTy->getElementType());
11902   }
11903   
11904   // Otherwise, we don't know.
11905   return 0;
11906 }
11907
11908 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
11909   // If vector val is undef, replace extract with scalar undef.
11910   if (isa<UndefValue>(EI.getOperand(0)))
11911     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11912
11913   // If vector val is constant 0, replace extract with scalar 0.
11914   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11915     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11916   
11917   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
11918     // If vector val is constant with all elements the same, replace EI with
11919     // that element. When the elements are not identical, we cannot replace yet
11920     // (we do that below, but only when the index is constant).
11921     Constant *op0 = C->getOperand(0);
11922     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11923       if (C->getOperand(i) != op0) {
11924         op0 = 0; 
11925         break;
11926       }
11927     if (op0)
11928       return ReplaceInstUsesWith(EI, op0);
11929   }
11930   
11931   // If extracting a specified index from the vector, see if we can recursively
11932   // find a previously computed scalar that was inserted into the vector.
11933   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11934     unsigned IndexVal = IdxC->getZExtValue();
11935     unsigned VectorWidth = 
11936       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11937       
11938     // If this is extracting an invalid index, turn this into undef, to avoid
11939     // crashing the code below.
11940     if (IndexVal >= VectorWidth)
11941       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11942     
11943     // This instruction only demands the single element from the input vector.
11944     // If the input vector has a single use, simplify it based on this use
11945     // property.
11946     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
11947       APInt UndefElts(VectorWidth, 0);
11948       APInt DemandedMask(VectorWidth, 1 << IndexVal);
11949       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
11950                                                 DemandedMask, UndefElts)) {
11951         EI.setOperand(0, V);
11952         return &EI;
11953       }
11954     }
11955     
11956     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
11957       return ReplaceInstUsesWith(EI, Elt);
11958     
11959     // If the this extractelement is directly using a bitcast from a vector of
11960     // the same number of elements, see if we can find the source element from
11961     // it.  In this case, we will end up needing to bitcast the scalars.
11962     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11963       if (const VectorType *VT = 
11964               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11965         if (VT->getNumElements() == VectorWidth)
11966           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11967             return new BitCastInst(Elt, EI.getType());
11968     }
11969   }
11970   
11971   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
11972     if (I->hasOneUse()) {
11973       // Push extractelement into predecessor operation if legal and
11974       // profitable to do so
11975       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
11976         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11977         if (CheapToScalarize(BO, isConstantElt)) {
11978           ExtractElementInst *newEI0 = 
11979             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11980                                    EI.getName()+".lhs");
11981           ExtractElementInst *newEI1 =
11982             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11983                                    EI.getName()+".rhs");
11984           InsertNewInstBefore(newEI0, EI);
11985           InsertNewInstBefore(newEI1, EI);
11986           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
11987         }
11988       } else if (isa<LoadInst>(I)) {
11989         unsigned AS = 
11990           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
11991         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11992                                          PointerType::get(EI.getType(), AS),EI);
11993         GetElementPtrInst *GEP =
11994           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
11995         InsertNewInstBefore(GEP, EI);
11996         return new LoadInst(GEP);
11997       }
11998     }
11999     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12000       // Extracting the inserted element?
12001       if (IE->getOperand(2) == EI.getOperand(1))
12002         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12003       // If the inserted and extracted elements are constants, they must not
12004       // be the same value, extract from the pre-inserted value instead.
12005       if (isa<Constant>(IE->getOperand(2)) &&
12006           isa<Constant>(EI.getOperand(1))) {
12007         AddUsesToWorkList(EI);
12008         EI.setOperand(0, IE->getOperand(0));
12009         return &EI;
12010       }
12011     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12012       // If this is extracting an element from a shufflevector, figure out where
12013       // it came from and extract from the appropriate input element instead.
12014       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12015         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12016         Value *Src;
12017         unsigned LHSWidth =
12018           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12019
12020         if (SrcIdx < LHSWidth)
12021           Src = SVI->getOperand(0);
12022         else if (SrcIdx < LHSWidth*2) {
12023           SrcIdx -= LHSWidth;
12024           Src = SVI->getOperand(1);
12025         } else {
12026           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12027         }
12028         return new ExtractElementInst(Src, SrcIdx);
12029       }
12030     }
12031   }
12032   return 0;
12033 }
12034
12035 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12036 /// elements from either LHS or RHS, return the shuffle mask and true. 
12037 /// Otherwise, return false.
12038 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12039                                          std::vector<Constant*> &Mask) {
12040   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12041          "Invalid CollectSingleShuffleElements");
12042   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12043
12044   if (isa<UndefValue>(V)) {
12045     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12046     return true;
12047   } else if (V == LHS) {
12048     for (unsigned i = 0; i != NumElts; ++i)
12049       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12050     return true;
12051   } else if (V == RHS) {
12052     for (unsigned i = 0; i != NumElts; ++i)
12053       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
12054     return true;
12055   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12056     // If this is an insert of an extract from some other vector, include it.
12057     Value *VecOp    = IEI->getOperand(0);
12058     Value *ScalarOp = IEI->getOperand(1);
12059     Value *IdxOp    = IEI->getOperand(2);
12060     
12061     if (!isa<ConstantInt>(IdxOp))
12062       return false;
12063     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12064     
12065     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12066       // Okay, we can handle this if the vector we are insertinting into is
12067       // transitively ok.
12068       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12069         // If so, update the mask to reflect the inserted undef.
12070         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
12071         return true;
12072       }      
12073     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12074       if (isa<ConstantInt>(EI->getOperand(1)) &&
12075           EI->getOperand(0)->getType() == V->getType()) {
12076         unsigned ExtractedIdx =
12077           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12078         
12079         // This must be extracting from either LHS or RHS.
12080         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12081           // Okay, we can handle this if the vector we are insertinting into is
12082           // transitively ok.
12083           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12084             // If so, update the mask to reflect the inserted value.
12085             if (EI->getOperand(0) == LHS) {
12086               Mask[InsertedIdx % NumElts] = 
12087                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12088             } else {
12089               assert(EI->getOperand(0) == RHS);
12090               Mask[InsertedIdx % NumElts] = 
12091                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
12092               
12093             }
12094             return true;
12095           }
12096         }
12097       }
12098     }
12099   }
12100   // TODO: Handle shufflevector here!
12101   
12102   return false;
12103 }
12104
12105 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12106 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12107 /// that computes V and the LHS value of the shuffle.
12108 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12109                                      Value *&RHS) {
12110   assert(isa<VectorType>(V->getType()) && 
12111          (RHS == 0 || V->getType() == RHS->getType()) &&
12112          "Invalid shuffle!");
12113   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12114
12115   if (isa<UndefValue>(V)) {
12116     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12117     return V;
12118   } else if (isa<ConstantAggregateZero>(V)) {
12119     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
12120     return V;
12121   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12122     // If this is an insert of an extract from some other vector, include it.
12123     Value *VecOp    = IEI->getOperand(0);
12124     Value *ScalarOp = IEI->getOperand(1);
12125     Value *IdxOp    = IEI->getOperand(2);
12126     
12127     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12128       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12129           EI->getOperand(0)->getType() == V->getType()) {
12130         unsigned ExtractedIdx =
12131           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12132         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12133         
12134         // Either the extracted from or inserted into vector must be RHSVec,
12135         // otherwise we'd end up with a shuffle of three inputs.
12136         if (EI->getOperand(0) == RHS || RHS == 0) {
12137           RHS = EI->getOperand(0);
12138           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
12139           Mask[InsertedIdx % NumElts] = 
12140             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
12141           return V;
12142         }
12143         
12144         if (VecOp == RHS) {
12145           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
12146           // Everything but the extracted element is replaced with the RHS.
12147           for (unsigned i = 0; i != NumElts; ++i) {
12148             if (i != InsertedIdx)
12149               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
12150           }
12151           return V;
12152         }
12153         
12154         // If this insertelement is a chain that comes from exactly these two
12155         // vectors, return the vector and the effective shuffle.
12156         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
12157           return EI->getOperand(0);
12158         
12159       }
12160     }
12161   }
12162   // TODO: Handle shufflevector here!
12163   
12164   // Otherwise, can't do anything fancy.  Return an identity vector.
12165   for (unsigned i = 0; i != NumElts; ++i)
12166     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12167   return V;
12168 }
12169
12170 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12171   Value *VecOp    = IE.getOperand(0);
12172   Value *ScalarOp = IE.getOperand(1);
12173   Value *IdxOp    = IE.getOperand(2);
12174   
12175   // Inserting an undef or into an undefined place, remove this.
12176   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12177     ReplaceInstUsesWith(IE, VecOp);
12178   
12179   // If the inserted element was extracted from some other vector, and if the 
12180   // indexes are constant, try to turn this into a shufflevector operation.
12181   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12182     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12183         EI->getOperand(0)->getType() == IE.getType()) {
12184       unsigned NumVectorElts = IE.getType()->getNumElements();
12185       unsigned ExtractedIdx =
12186         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12187       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12188       
12189       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12190         return ReplaceInstUsesWith(IE, VecOp);
12191       
12192       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12193         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12194       
12195       // If we are extracting a value from a vector, then inserting it right
12196       // back into the same place, just use the input vector.
12197       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12198         return ReplaceInstUsesWith(IE, VecOp);      
12199       
12200       // We could theoretically do this for ANY input.  However, doing so could
12201       // turn chains of insertelement instructions into a chain of shufflevector
12202       // instructions, and right now we do not merge shufflevectors.  As such,
12203       // only do this in a situation where it is clear that there is benefit.
12204       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12205         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12206         // the values of VecOp, except then one read from EIOp0.
12207         // Build a new shuffle mask.
12208         std::vector<Constant*> Mask;
12209         if (isa<UndefValue>(VecOp))
12210           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
12211         else {
12212           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12213           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
12214                                                        NumVectorElts));
12215         } 
12216         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12217         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12218                                      ConstantVector::get(Mask));
12219       }
12220       
12221       // If this insertelement isn't used by some other insertelement, turn it
12222       // (and any insertelements it points to), into one big shuffle.
12223       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12224         std::vector<Constant*> Mask;
12225         Value *RHS = 0;
12226         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12227         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12228         // We now have a shuffle of LHS, RHS, Mask.
12229         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
12230       }
12231     }
12232   }
12233
12234   return 0;
12235 }
12236
12237
12238 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12239   Value *LHS = SVI.getOperand(0);
12240   Value *RHS = SVI.getOperand(1);
12241   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12242
12243   bool MadeChange = false;
12244
12245   // Undefined shuffle mask -> undefined value.
12246   if (isa<UndefValue>(SVI.getOperand(2)))
12247     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12248
12249   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12250
12251   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12252     return 0;
12253
12254   APInt UndefElts(VWidth, 0);
12255   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12256   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12257     LHS = SVI.getOperand(0);
12258     RHS = SVI.getOperand(1);
12259     MadeChange = true;
12260   }
12261   
12262   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12263   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12264   if (LHS == RHS || isa<UndefValue>(LHS)) {
12265     if (isa<UndefValue>(LHS) && LHS == RHS) {
12266       // shuffle(undef,undef,mask) -> undef.
12267       return ReplaceInstUsesWith(SVI, LHS);
12268     }
12269     
12270     // Remap any references to RHS to use LHS.
12271     std::vector<Constant*> Elts;
12272     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12273       if (Mask[i] >= 2*e)
12274         Elts.push_back(UndefValue::get(Type::Int32Ty));
12275       else {
12276         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12277             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12278           Mask[i] = 2*e;     // Turn into undef.
12279           Elts.push_back(UndefValue::get(Type::Int32Ty));
12280         } else {
12281           Mask[i] = Mask[i] % e;  // Force to LHS.
12282           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12283         }
12284       }
12285     }
12286     SVI.setOperand(0, SVI.getOperand(1));
12287     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12288     SVI.setOperand(2, ConstantVector::get(Elts));
12289     LHS = SVI.getOperand(0);
12290     RHS = SVI.getOperand(1);
12291     MadeChange = true;
12292   }
12293   
12294   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12295   bool isLHSID = true, isRHSID = true;
12296     
12297   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12298     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12299     // Is this an identity shuffle of the LHS value?
12300     isLHSID &= (Mask[i] == i);
12301       
12302     // Is this an identity shuffle of the RHS value?
12303     isRHSID &= (Mask[i]-e == i);
12304   }
12305
12306   // Eliminate identity shuffles.
12307   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12308   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12309   
12310   // If the LHS is a shufflevector itself, see if we can combine it with this
12311   // one without producing an unusual shuffle.  Here we are really conservative:
12312   // we are absolutely afraid of producing a shuffle mask not in the input
12313   // program, because the code gen may not be smart enough to turn a merged
12314   // shuffle into two specific shuffles: it may produce worse code.  As such,
12315   // we only merge two shuffles if the result is one of the two input shuffle
12316   // masks.  In this case, merging the shuffles just removes one instruction,
12317   // which we know is safe.  This is good for things like turning:
12318   // (splat(splat)) -> splat.
12319   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12320     if (isa<UndefValue>(RHS)) {
12321       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12322
12323       std::vector<unsigned> NewMask;
12324       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12325         if (Mask[i] >= 2*e)
12326           NewMask.push_back(2*e);
12327         else
12328           NewMask.push_back(LHSMask[Mask[i]]);
12329       
12330       // If the result mask is equal to the src shuffle or this shuffle mask, do
12331       // the replacement.
12332       if (NewMask == LHSMask || NewMask == Mask) {
12333         unsigned LHSInNElts =
12334           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12335         std::vector<Constant*> Elts;
12336         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12337           if (NewMask[i] >= LHSInNElts*2) {
12338             Elts.push_back(UndefValue::get(Type::Int32Ty));
12339           } else {
12340             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
12341           }
12342         }
12343         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12344                                      LHSSVI->getOperand(1),
12345                                      ConstantVector::get(Elts));
12346       }
12347     }
12348   }
12349
12350   return MadeChange ? &SVI : 0;
12351 }
12352
12353
12354
12355
12356 /// TryToSinkInstruction - Try to move the specified instruction from its
12357 /// current block into the beginning of DestBlock, which can only happen if it's
12358 /// safe to move the instruction past all of the instructions between it and the
12359 /// end of its block.
12360 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12361   assert(I->hasOneUse() && "Invariants didn't hold!");
12362
12363   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12364   if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
12365     return false;
12366
12367   // Do not sink alloca instructions out of the entry block.
12368   if (isa<AllocaInst>(I) && I->getParent() ==
12369         &DestBlock->getParent()->getEntryBlock())
12370     return false;
12371
12372   // We can only sink load instructions if there is nothing between the load and
12373   // the end of block that could change the value.
12374   if (I->mayReadFromMemory()) {
12375     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12376          Scan != E; ++Scan)
12377       if (Scan->mayWriteToMemory())
12378         return false;
12379   }
12380
12381   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12382
12383   CopyPrecedingStopPoint(I, InsertPos);
12384   I->moveBefore(InsertPos);
12385   ++NumSunkInst;
12386   return true;
12387 }
12388
12389
12390 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12391 /// all reachable code to the worklist.
12392 ///
12393 /// This has a couple of tricks to make the code faster and more powerful.  In
12394 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12395 /// them to the worklist (this significantly speeds up instcombine on code where
12396 /// many instructions are dead or constant).  Additionally, if we find a branch
12397 /// whose condition is a known constant, we only visit the reachable successors.
12398 ///
12399 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12400                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12401                                        InstCombiner &IC,
12402                                        const TargetData *TD) {
12403   SmallVector<BasicBlock*, 256> Worklist;
12404   Worklist.push_back(BB);
12405
12406   while (!Worklist.empty()) {
12407     BB = Worklist.back();
12408     Worklist.pop_back();
12409     
12410     // We have now visited this block!  If we've already been here, ignore it.
12411     if (!Visited.insert(BB)) continue;
12412
12413     DbgInfoIntrinsic *DBI_Prev = NULL;
12414     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12415       Instruction *Inst = BBI++;
12416       
12417       // DCE instruction if trivially dead.
12418       if (isInstructionTriviallyDead(Inst)) {
12419         ++NumDeadInst;
12420         DOUT << "IC: DCE: " << *Inst;
12421         Inst->eraseFromParent();
12422         continue;
12423       }
12424       
12425       // ConstantProp instruction if trivially constant.
12426       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12427         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12428         Inst->replaceAllUsesWith(C);
12429         ++NumConstProp;
12430         Inst->eraseFromParent();
12431         continue;
12432       }
12433      
12434       // If there are two consecutive llvm.dbg.stoppoint calls then
12435       // it is likely that the optimizer deleted code in between these
12436       // two intrinsics. 
12437       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12438       if (DBI_Next) {
12439         if (DBI_Prev
12440             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12441             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12442           IC.RemoveFromWorkList(DBI_Prev);
12443           DBI_Prev->eraseFromParent();
12444         }
12445         DBI_Prev = DBI_Next;
12446       } else {
12447         DBI_Prev = 0;
12448       }
12449
12450       IC.AddToWorkList(Inst);
12451     }
12452
12453     // Recursively visit successors.  If this is a branch or switch on a
12454     // constant, only visit the reachable successor.
12455     TerminatorInst *TI = BB->getTerminator();
12456     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12457       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12458         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12459         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12460         Worklist.push_back(ReachableBB);
12461         continue;
12462       }
12463     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12464       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12465         // See if this is an explicit destination.
12466         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12467           if (SI->getCaseValue(i) == Cond) {
12468             BasicBlock *ReachableBB = SI->getSuccessor(i);
12469             Worklist.push_back(ReachableBB);
12470             continue;
12471           }
12472         
12473         // Otherwise it is the default destination.
12474         Worklist.push_back(SI->getSuccessor(0));
12475         continue;
12476       }
12477     }
12478     
12479     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12480       Worklist.push_back(TI->getSuccessor(i));
12481   }
12482 }
12483
12484 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12485   bool Changed = false;
12486   TD = &getAnalysis<TargetData>();
12487   
12488   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12489              << F.getNameStr() << "\n");
12490
12491   {
12492     // Do a depth-first traversal of the function, populate the worklist with
12493     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12494     // track of which blocks we visit.
12495     SmallPtrSet<BasicBlock*, 64> Visited;
12496     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12497
12498     // Do a quick scan over the function.  If we find any blocks that are
12499     // unreachable, remove any instructions inside of them.  This prevents
12500     // the instcombine code from having to deal with some bad special cases.
12501     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12502       if (!Visited.count(BB)) {
12503         Instruction *Term = BB->getTerminator();
12504         while (Term != BB->begin()) {   // Remove instrs bottom-up
12505           BasicBlock::iterator I = Term; --I;
12506
12507           DOUT << "IC: DCE: " << *I;
12508           ++NumDeadInst;
12509
12510           if (!I->use_empty())
12511             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12512           I->eraseFromParent();
12513           Changed = true;
12514         }
12515       }
12516   }
12517
12518   while (!Worklist.empty()) {
12519     Instruction *I = RemoveOneFromWorkList();
12520     if (I == 0) continue;  // skip null values.
12521
12522     // Check to see if we can DCE the instruction.
12523     if (isInstructionTriviallyDead(I)) {
12524       // Add operands to the worklist.
12525       if (I->getNumOperands() < 4)
12526         AddUsesToWorkList(*I);
12527       ++NumDeadInst;
12528
12529       DOUT << "IC: DCE: " << *I;
12530
12531       I->eraseFromParent();
12532       RemoveFromWorkList(I);
12533       Changed = true;
12534       continue;
12535     }
12536
12537     // Instruction isn't dead, see if we can constant propagate it.
12538     if (Constant *C = ConstantFoldInstruction(I, TD)) {
12539       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12540
12541       // Add operands to the worklist.
12542       AddUsesToWorkList(*I);
12543       ReplaceInstUsesWith(*I, C);
12544
12545       ++NumConstProp;
12546       I->eraseFromParent();
12547       RemoveFromWorkList(I);
12548       Changed = true;
12549       continue;
12550     }
12551
12552     if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
12553       // See if we can constant fold its operands.
12554       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12555         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
12556           if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
12557             if (NewC != CE) {
12558               i->set(NewC);
12559               Changed = true;
12560             }
12561     }
12562
12563     // See if we can trivially sink this instruction to a successor basic block.
12564     if (I->hasOneUse()) {
12565       BasicBlock *BB = I->getParent();
12566       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12567       if (UserParent != BB) {
12568         bool UserIsSuccessor = false;
12569         // See if the user is one of our successors.
12570         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12571           if (*SI == UserParent) {
12572             UserIsSuccessor = true;
12573             break;
12574           }
12575
12576         // If the user is one of our immediate successors, and if that successor
12577         // only has us as a predecessors (we'd have to split the critical edge
12578         // otherwise), we can keep going.
12579         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12580             next(pred_begin(UserParent)) == pred_end(UserParent))
12581           // Okay, the CFG is simple enough, try to sink this instruction.
12582           Changed |= TryToSinkInstruction(I, UserParent);
12583       }
12584     }
12585
12586     // Now that we have an instruction, try combining it to simplify it...
12587 #ifndef NDEBUG
12588     std::string OrigI;
12589 #endif
12590     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
12591     if (Instruction *Result = visit(*I)) {
12592       ++NumCombined;
12593       // Should we replace the old instruction with a new one?
12594       if (Result != I) {
12595         DOUT << "IC: Old = " << *I
12596              << "    New = " << *Result;
12597
12598         // Everything uses the new instruction now.
12599         I->replaceAllUsesWith(Result);
12600
12601         // Push the new instruction and any users onto the worklist.
12602         AddToWorkList(Result);
12603         AddUsersToWorkList(*Result);
12604
12605         // Move the name to the new instruction first.
12606         Result->takeName(I);
12607
12608         // Insert the new instruction into the basic block...
12609         BasicBlock *InstParent = I->getParent();
12610         BasicBlock::iterator InsertPos = I;
12611
12612         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
12613           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12614             ++InsertPos;
12615
12616         InstParent->getInstList().insert(InsertPos, Result);
12617
12618         // Make sure that we reprocess all operands now that we reduced their
12619         // use counts.
12620         AddUsesToWorkList(*I);
12621
12622         // Instructions can end up on the worklist more than once.  Make sure
12623         // we do not process an instruction that has been deleted.
12624         RemoveFromWorkList(I);
12625
12626         // Erase the old instruction.
12627         InstParent->getInstList().erase(I);
12628       } else {
12629 #ifndef NDEBUG
12630         DOUT << "IC: Mod = " << OrigI
12631              << "    New = " << *I;
12632 #endif
12633
12634         // If the instruction was modified, it's possible that it is now dead.
12635         // if so, remove it.
12636         if (isInstructionTriviallyDead(I)) {
12637           // Make sure we process all operands now that we are reducing their
12638           // use counts.
12639           AddUsesToWorkList(*I);
12640
12641           // Instructions may end up in the worklist more than once.  Erase all
12642           // occurrences of this instruction.
12643           RemoveFromWorkList(I);
12644           I->eraseFromParent();
12645         } else {
12646           AddToWorkList(I);
12647           AddUsersToWorkList(*I);
12648         }
12649       }
12650       Changed = true;
12651     }
12652   }
12653
12654   assert(WorklistMap.empty() && "Worklist empty, but map not?");
12655     
12656   // Do an explicit clear, this shrinks the map if needed.
12657   WorklistMap.clear();
12658   return Changed;
12659 }
12660
12661
12662 bool InstCombiner::runOnFunction(Function &F) {
12663   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12664   
12665   bool EverMadeChange = false;
12666
12667   // Iterate while there is work to do.
12668   unsigned Iteration = 0;
12669   while (DoOneIteration(F, Iteration++))
12670     EverMadeChange = true;
12671   return EverMadeChange;
12672 }
12673
12674 FunctionPass *llvm::createInstructionCombiningPass() {
12675   return new InstCombiner();
12676 }