Move EVER MORE stuff over to LLVMContext.
[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/LLVMContext.h"
40 #include "llvm/Pass.h"
41 #include "llvm/DerivedTypes.h"
42 #include "llvm/GlobalVariable.h"
43 #include "llvm/Analysis/ConstantFolding.h"
44 #include "llvm/Analysis/ValueTracking.h"
45 #include "llvm/Target/TargetData.h"
46 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
47 #include "llvm/Transforms/Utils/Local.h"
48 #include "llvm/Support/CallSite.h"
49 #include "llvm/Support/ConstantRange.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/GetElementPtrTypeIterator.h"
53 #include "llvm/Support/InstVisitor.h"
54 #include "llvm/Support/MathExtras.h"
55 #include "llvm/Support/PatternMatch.h"
56 #include "llvm/Support/Compiler.h"
57 #include "llvm/ADT/DenseMap.h"
58 #include "llvm/ADT/SmallVector.h"
59 #include "llvm/ADT/SmallPtrSet.h"
60 #include "llvm/ADT/Statistic.h"
61 #include "llvm/ADT/STLExtras.h"
62 #include <algorithm>
63 #include <climits>
64 #include <sstream>
65 using namespace llvm;
66 using namespace llvm::PatternMatch;
67
68 STATISTIC(NumCombined , "Number of insts combined");
69 STATISTIC(NumConstProp, "Number of constant folds");
70 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
71 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
72 STATISTIC(NumSunkInst , "Number of instructions sunk");
73
74 namespace {
75   class VISIBILITY_HIDDEN InstCombiner
76     : public FunctionPass,
77       public InstVisitor<InstCombiner, Instruction*> {
78     // Worklist of all of the instructions that need to be simplified.
79     SmallVector<Instruction*, 256> Worklist;
80     DenseMap<Instruction*, unsigned> WorklistMap;
81     TargetData *TD;
82     bool MustPreserveLCSSA;
83   public:
84     static char ID; // Pass identification, replacement for typeid
85     InstCombiner() : FunctionPass(&ID) {}
86
87     LLVMContext *getContext() { return Context; }
88
89     /// AddToWorkList - Add the specified instruction to the worklist if it
90     /// isn't already in it.
91     void AddToWorkList(Instruction *I) {
92       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
93         Worklist.push_back(I);
94     }
95     
96     // RemoveFromWorkList - remove I from the worklist if it exists.
97     void RemoveFromWorkList(Instruction *I) {
98       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
99       if (It == WorklistMap.end()) return; // Not in worklist.
100       
101       // Don't bother moving everything down, just null out the slot.
102       Worklist[It->second] = 0;
103       
104       WorklistMap.erase(It);
105     }
106     
107     Instruction *RemoveOneFromWorkList() {
108       Instruction *I = Worklist.back();
109       Worklist.pop_back();
110       WorklistMap.erase(I);
111       return I;
112     }
113
114     
115     /// AddUsersToWorkList - When an instruction is simplified, add all users of
116     /// the instruction to the work lists because they might get more simplified
117     /// now.
118     ///
119     void AddUsersToWorkList(Value &I) {
120       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
121            UI != UE; ++UI)
122         AddToWorkList(cast<Instruction>(*UI));
123     }
124
125     /// AddUsesToWorkList - When an instruction is simplified, add operands to
126     /// the work lists because they might get more simplified now.
127     ///
128     void AddUsesToWorkList(Instruction &I) {
129       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
130         if (Instruction *Op = dyn_cast<Instruction>(*i))
131           AddToWorkList(Op);
132     }
133     
134     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
135     /// dead.  Add all of its operands to the worklist, turning them into
136     /// undef's to reduce the number of uses of those instructions.
137     ///
138     /// Return the specified operand before it is turned into an undef.
139     ///
140     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
141       Value *R = I.getOperand(op);
142       
143       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
144         if (Instruction *Op = dyn_cast<Instruction>(*i)) {
145           AddToWorkList(Op);
146           // Set the operand to undef to drop the use.
147           *i = Context->getUndef(Op->getType());
148         }
149       
150       return R;
151     }
152
153   public:
154     virtual bool runOnFunction(Function &F);
155     
156     bool DoOneIteration(Function &F, unsigned ItNum);
157
158     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
159       AU.addRequired<TargetData>();
160       AU.addPreservedID(LCSSAID);
161       AU.setPreservesCFG();
162     }
163
164     TargetData &getTargetData() const { return *TD; }
165
166     // Visitation implementation - Implement instruction combining for different
167     // instruction types.  The semantics are as follows:
168     // Return Value:
169     //    null        - No change was made
170     //     I          - Change was made, I is still valid, I may be dead though
171     //   otherwise    - Change was made, replace I with returned instruction
172     //
173     Instruction *visitAdd(BinaryOperator &I);
174     Instruction *visitFAdd(BinaryOperator &I);
175     Instruction *visitSub(BinaryOperator &I);
176     Instruction *visitFSub(BinaryOperator &I);
177     Instruction *visitMul(BinaryOperator &I);
178     Instruction *visitFMul(BinaryOperator &I);
179     Instruction *visitURem(BinaryOperator &I);
180     Instruction *visitSRem(BinaryOperator &I);
181     Instruction *visitFRem(BinaryOperator &I);
182     bool SimplifyDivRemOfSelect(BinaryOperator &I);
183     Instruction *commonRemTransforms(BinaryOperator &I);
184     Instruction *commonIRemTransforms(BinaryOperator &I);
185     Instruction *commonDivTransforms(BinaryOperator &I);
186     Instruction *commonIDivTransforms(BinaryOperator &I);
187     Instruction *visitUDiv(BinaryOperator &I);
188     Instruction *visitSDiv(BinaryOperator &I);
189     Instruction *visitFDiv(BinaryOperator &I);
190     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
191     Instruction *visitAnd(BinaryOperator &I);
192     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
193     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
194                                      Value *A, Value *B, Value *C);
195     Instruction *visitOr (BinaryOperator &I);
196     Instruction *visitXor(BinaryOperator &I);
197     Instruction *visitShl(BinaryOperator &I);
198     Instruction *visitAShr(BinaryOperator &I);
199     Instruction *visitLShr(BinaryOperator &I);
200     Instruction *commonShiftTransforms(BinaryOperator &I);
201     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
202                                       Constant *RHSC);
203     Instruction *visitFCmpInst(FCmpInst &I);
204     Instruction *visitICmpInst(ICmpInst &I);
205     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
206     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
207                                                 Instruction *LHS,
208                                                 ConstantInt *RHS);
209     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
210                                 ConstantInt *DivRHS);
211
212     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
213                              ICmpInst::Predicate Cond, Instruction &I);
214     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
215                                      BinaryOperator &I);
216     Instruction *commonCastTransforms(CastInst &CI);
217     Instruction *commonIntCastTransforms(CastInst &CI);
218     Instruction *commonPointerCastTransforms(CastInst &CI);
219     Instruction *visitTrunc(TruncInst &CI);
220     Instruction *visitZExt(ZExtInst &CI);
221     Instruction *visitSExt(SExtInst &CI);
222     Instruction *visitFPTrunc(FPTruncInst &CI);
223     Instruction *visitFPExt(CastInst &CI);
224     Instruction *visitFPToUI(FPToUIInst &FI);
225     Instruction *visitFPToSI(FPToSIInst &FI);
226     Instruction *visitUIToFP(CastInst &CI);
227     Instruction *visitSIToFP(CastInst &CI);
228     Instruction *visitPtrToInt(PtrToIntInst &CI);
229     Instruction *visitIntToPtr(IntToPtrInst &CI);
230     Instruction *visitBitCast(BitCastInst &CI);
231     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
232                                 Instruction *FI);
233     Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
234     Instruction *visitSelectInst(SelectInst &SI);
235     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
236     Instruction *visitCallInst(CallInst &CI);
237     Instruction *visitInvokeInst(InvokeInst &II);
238     Instruction *visitPHINode(PHINode &PN);
239     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
240     Instruction *visitAllocationInst(AllocationInst &AI);
241     Instruction *visitFreeInst(FreeInst &FI);
242     Instruction *visitLoadInst(LoadInst &LI);
243     Instruction *visitStoreInst(StoreInst &SI);
244     Instruction *visitBranchInst(BranchInst &BI);
245     Instruction *visitSwitchInst(SwitchInst &SI);
246     Instruction *visitInsertElementInst(InsertElementInst &IE);
247     Instruction *visitExtractElementInst(ExtractElementInst &EI);
248     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
249     Instruction *visitExtractValueInst(ExtractValueInst &EV);
250
251     // visitInstruction - Specify what to return for unhandled instructions...
252     Instruction *visitInstruction(Instruction &I) { return 0; }
253
254   private:
255     Instruction *visitCallSite(CallSite CS);
256     bool transformConstExprCastCall(CallSite CS);
257     Instruction *transformCallThroughTrampoline(CallSite CS);
258     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
259                                    bool DoXform = true);
260     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
261     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
262
263
264   public:
265     // InsertNewInstBefore - insert an instruction New before instruction Old
266     // in the program.  Add the new instruction to the worklist.
267     //
268     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
269       assert(New && New->getParent() == 0 &&
270              "New instruction already inserted into a basic block!");
271       BasicBlock *BB = Old.getParent();
272       BB->getInstList().insert(&Old, New);  // Insert inst
273       AddToWorkList(New);
274       return New;
275     }
276
277     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
278     /// This also adds the cast to the worklist.  Finally, this returns the
279     /// cast.
280     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
281                             Instruction &Pos) {
282       if (V->getType() == Ty) return V;
283
284       if (Constant *CV = dyn_cast<Constant>(V))
285         return Context->getConstantExprCast(opc, CV, Ty);
286       
287       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
288       AddToWorkList(C);
289       return C;
290     }
291         
292     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
293       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
294     }
295
296
297     // ReplaceInstUsesWith - This method is to be used when an instruction is
298     // found to be dead, replacable with another preexisting expression.  Here
299     // we add all uses of I to the worklist, replace all uses of I with the new
300     // value, then return I, so that the inst combiner will know that I was
301     // modified.
302     //
303     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
304       AddUsersToWorkList(I);         // Add all modified instrs to worklist
305       if (&I != V) {
306         I.replaceAllUsesWith(V);
307         return &I;
308       } else {
309         // If we are replacing the instruction with itself, this must be in a
310         // segment of unreachable code, so just clobber the instruction.
311         I.replaceAllUsesWith(Context->getUndef(I.getType()));
312         return &I;
313       }
314     }
315
316     // EraseInstFromFunction - When dealing with an instruction that has side
317     // effects or produces a void value, we can't rely on DCE to delete the
318     // instruction.  Instead, visit methods should return the value returned by
319     // this function.
320     Instruction *EraseInstFromFunction(Instruction &I) {
321       assert(I.use_empty() && "Cannot erase instruction that is used!");
322       AddUsesToWorkList(I);
323       RemoveFromWorkList(&I);
324       I.eraseFromParent();
325       return 0;  // Don't do anything with FI
326     }
327         
328     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
329                            APInt &KnownOne, unsigned Depth = 0) const {
330       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
331     }
332     
333     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
334                            unsigned Depth = 0) const {
335       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
336     }
337     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
338       return llvm::ComputeNumSignBits(Op, TD, Depth);
339     }
340
341   private:
342
343     /// SimplifyCommutative - This performs a few simplifications for 
344     /// commutative operators.
345     bool SimplifyCommutative(BinaryOperator &I);
346
347     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
348     /// most-complex to least-complex order.
349     bool SimplifyCompare(CmpInst &I);
350
351     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
352     /// based on the demanded bits.
353     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
354                                    APInt& KnownZero, APInt& KnownOne,
355                                    unsigned Depth);
356     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
357                               APInt& KnownZero, APInt& KnownOne,
358                               unsigned Depth=0);
359         
360     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
361     /// SimplifyDemandedBits knows about.  See if the instruction has any
362     /// properties that allow us to simplify its operands.
363     bool SimplifyDemandedInstructionBits(Instruction &Inst);
364         
365     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
366                                       APInt& UndefElts, unsigned Depth = 0);
367       
368     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
369     // PHI node as operand #0, see if we can fold the instruction into the PHI
370     // (which is only possible if all operands to the PHI are constants).
371     Instruction *FoldOpIntoPhi(Instruction &I);
372
373     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
374     // operator and they all are only used by the PHI, PHI together their
375     // inputs, and do the operation once, to the result of the PHI.
376     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
377     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
378     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
379
380     
381     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
382                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
383     
384     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
385                               bool isSub, Instruction &I);
386     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
387                                  bool isSigned, bool Inside, Instruction &IB);
388     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
389     Instruction *MatchBSwap(BinaryOperator &I);
390     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
391     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
392     Instruction *SimplifyMemSet(MemSetInst *MI);
393
394
395     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
396
397     bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
398                                     unsigned CastOpc, int &NumCastsRemoved);
399     unsigned GetOrEnforceKnownAlignment(Value *V,
400                                         unsigned PrefAlign = 0);
401
402   };
403 }
404
405 char InstCombiner::ID = 0;
406 static RegisterPass<InstCombiner>
407 X("instcombine", "Combine redundant instructions");
408
409 // getComplexity:  Assign a complexity or rank value to LLVM Values...
410 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
411 static unsigned getComplexity(LLVMContext *Context, Value *V) {
412   if (isa<Instruction>(V)) {
413     if (BinaryOperator::isNeg(V) ||
414         BinaryOperator::isFNeg(V) ||
415         BinaryOperator::isNot(V))
416       return 3;
417     return 4;
418   }
419   if (isa<Argument>(V)) return 3;
420   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
421 }
422
423 // isOnlyUse - Return true if this instruction will be deleted if we stop using
424 // it.
425 static bool isOnlyUse(Value *V) {
426   return V->hasOneUse() || isa<Constant>(V);
427 }
428
429 // getPromotedType - Return the specified type promoted as it would be to pass
430 // though a va_arg area...
431 static const Type *getPromotedType(const Type *Ty) {
432   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
433     if (ITy->getBitWidth() < 32)
434       return Type::Int32Ty;
435   }
436   return Ty;
437 }
438
439 /// getBitCastOperand - If the specified operand is a CastInst, a constant
440 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
441 /// operand value, otherwise return null.
442 static Value *getBitCastOperand(Value *V) {
443   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
444     // BitCastInst?
445     return I->getOperand(0);
446   else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
447     // GetElementPtrInst?
448     if (GEP->hasAllZeroIndices())
449       return GEP->getOperand(0);
450   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
451     if (CE->getOpcode() == Instruction::BitCast)
452       // BitCast ConstantExp?
453       return CE->getOperand(0);
454     else if (CE->getOpcode() == Instruction::GetElementPtr) {
455       // GetElementPtr ConstantExp?
456       for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
457            I != E; ++I) {
458         ConstantInt *CI = dyn_cast<ConstantInt>(I);
459         if (!CI || !CI->isZero())
460           // Any non-zero indices? Not cast-like.
461           return 0;
462       }
463       // All-zero indices? This is just like casting.
464       return CE->getOperand(0);
465     }
466   }
467   return 0;
468 }
469
470 /// This function is a wrapper around CastInst::isEliminableCastPair. It
471 /// simply extracts arguments and returns what that function returns.
472 static Instruction::CastOps 
473 isEliminableCastPair(
474   const CastInst *CI, ///< The first cast instruction
475   unsigned opcode,       ///< The opcode of the second cast instruction
476   const Type *DstTy,     ///< The target type for the second cast instruction
477   TargetData *TD         ///< The target data for pointer size
478 ) {
479   
480   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
481   const Type *MidTy = CI->getType();                  // B from above
482
483   // Get the opcodes of the two Cast instructions
484   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
485   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
486
487   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
488                                                 DstTy, TD->getIntPtrType());
489   
490   // We don't want to form an inttoptr or ptrtoint that converts to an integer
491   // type that differs from the pointer size.
492   if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
493       (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
494     Res = 0;
495   
496   return Instruction::CastOps(Res);
497 }
498
499 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
500 /// in any code being generated.  It does not require codegen if V is simple
501 /// enough or if the cast can be folded into other casts.
502 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
503                               const Type *Ty, TargetData *TD) {
504   if (V->getType() == Ty || isa<Constant>(V)) return false;
505   
506   // If this is another cast that can be eliminated, it isn't codegen either.
507   if (const CastInst *CI = dyn_cast<CastInst>(V))
508     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
509       return false;
510   return true;
511 }
512
513 // SimplifyCommutative - This performs a few simplifications for commutative
514 // operators:
515 //
516 //  1. Order operands such that they are listed from right (least complex) to
517 //     left (most complex).  This puts constants before unary operators before
518 //     binary operators.
519 //
520 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
521 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
522 //
523 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
524   bool Changed = false;
525   if (getComplexity(Context, I.getOperand(0)) < 
526       getComplexity(Context, I.getOperand(1)))
527     Changed = !I.swapOperands();
528
529   if (!I.isAssociative()) return Changed;
530   Instruction::BinaryOps Opcode = I.getOpcode();
531   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
532     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
533       if (isa<Constant>(I.getOperand(1))) {
534         Constant *Folded = Context->getConstantExpr(I.getOpcode(),
535                                              cast<Constant>(I.getOperand(1)),
536                                              cast<Constant>(Op->getOperand(1)));
537         I.setOperand(0, Op->getOperand(0));
538         I.setOperand(1, Folded);
539         return true;
540       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
541         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
542             isOnlyUse(Op) && isOnlyUse(Op1)) {
543           Constant *C1 = cast<Constant>(Op->getOperand(1));
544           Constant *C2 = cast<Constant>(Op1->getOperand(1));
545
546           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
547           Constant *Folded = Context->getConstantExpr(I.getOpcode(), C1, C2);
548           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
549                                                     Op1->getOperand(0),
550                                                     Op1->getName(), &I);
551           AddToWorkList(New);
552           I.setOperand(0, New);
553           I.setOperand(1, Folded);
554           return true;
555         }
556     }
557   return Changed;
558 }
559
560 /// SimplifyCompare - For a CmpInst this function just orders the operands
561 /// so that theyare listed from right (least complex) to left (most complex).
562 /// This puts constants before unary operators before binary operators.
563 bool InstCombiner::SimplifyCompare(CmpInst &I) {
564   if (getComplexity(Context, I.getOperand(0)) >=
565       getComplexity(Context, I.getOperand(1)))
566     return false;
567   I.swapOperands();
568   // Compare instructions are not associative so there's nothing else we can do.
569   return true;
570 }
571
572 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
573 // if the LHS is a constant zero (which is the 'negate' form).
574 //
575 static inline Value *dyn_castNegVal(Value *V, LLVMContext *Context) {
576   if (BinaryOperator::isNeg(V))
577     return BinaryOperator::getNegArgument(V);
578
579   // Constants can be considered to be negated values if they can be folded.
580   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
581     return Context->getConstantExprNeg(C);
582
583   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
584     if (C->getType()->getElementType()->isInteger())
585       return Context->getConstantExprNeg(C);
586
587   return 0;
588 }
589
590 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
591 // instruction if the LHS is a constant negative zero (which is the 'negate'
592 // form).
593 //
594 static inline Value *dyn_castFNegVal(Value *V, LLVMContext *Context) {
595   if (BinaryOperator::isFNeg(V))
596     return BinaryOperator::getFNegArgument(V);
597
598   // Constants can be considered to be negated values if they can be folded.
599   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
600     return Context->getConstantExprFNeg(C);
601
602   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
603     if (C->getType()->getElementType()->isFloatingPoint())
604       return Context->getConstantExprFNeg(C);
605
606   return 0;
607 }
608
609 static inline Value *dyn_castNotVal(Value *V, LLVMContext *Context) {
610   if (BinaryOperator::isNot(V))
611     return BinaryOperator::getNotArgument(V);
612
613   // Constants can be considered to be not'ed values...
614   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
615     return Context->getConstantInt(~C->getValue());
616   return 0;
617 }
618
619 // dyn_castFoldableMul - If this value is a multiply that can be folded into
620 // other computations (because it has a constant operand), return the
621 // non-constant operand of the multiply, and set CST to point to the multiplier.
622 // Otherwise, return null.
623 //
624 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST,
625                                          LLVMContext *Context) {
626   if (V->hasOneUse() && V->getType()->isInteger())
627     if (Instruction *I = dyn_cast<Instruction>(V)) {
628       if (I->getOpcode() == Instruction::Mul)
629         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
630           return I->getOperand(0);
631       if (I->getOpcode() == Instruction::Shl)
632         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
633           // The multiplier is really 1 << CST.
634           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
635           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
636           CST = Context->getConstantInt(APInt(BitWidth, 1).shl(CSTVal));
637           return I->getOperand(0);
638         }
639     }
640   return 0;
641 }
642
643 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
644 /// expression, return it.
645 static User *dyn_castGetElementPtr(Value *V) {
646   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
647   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
648     if (CE->getOpcode() == Instruction::GetElementPtr)
649       return cast<User>(V);
650   return false;
651 }
652
653 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
654 /// opcode value. Otherwise return UserOp1.
655 static unsigned getOpcode(const Value *V) {
656   if (const Instruction *I = dyn_cast<Instruction>(V))
657     return I->getOpcode();
658   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
659     return CE->getOpcode();
660   // Use UserOp1 to mean there's no opcode.
661   return Instruction::UserOp1;
662 }
663
664 /// AddOne - Add one to a ConstantInt
665 static Constant *AddOne(Constant *C, LLVMContext *Context) {
666   return Context->getConstantExprAdd(C, 
667     Context->getConstantInt(C->getType(), 1));
668 }
669 /// SubOne - Subtract one from a ConstantInt
670 static Constant *SubOne(ConstantInt *C, LLVMContext *Context) {
671   return Context->getConstantExprSub(C, 
672     Context->getConstantInt(C->getType(), 1));
673 }
674 /// MultiplyOverflows - True if the multiply can not be expressed in an int
675 /// this size.
676 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign,
677                               LLVMContext *Context) {
678   uint32_t W = C1->getBitWidth();
679   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
680   if (sign) {
681     LHSExt.sext(W * 2);
682     RHSExt.sext(W * 2);
683   } else {
684     LHSExt.zext(W * 2);
685     RHSExt.zext(W * 2);
686   }
687
688   APInt MulExt = LHSExt * RHSExt;
689
690   if (sign) {
691     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
692     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
693     return MulExt.slt(Min) || MulExt.sgt(Max);
694   } else 
695     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
696 }
697
698
699 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
700 /// specified instruction is a constant integer.  If so, check to see if there
701 /// are any bits set in the constant that are not demanded.  If so, shrink the
702 /// constant and return true.
703 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
704                                    APInt Demanded, LLVMContext *Context) {
705   assert(I && "No instruction?");
706   assert(OpNo < I->getNumOperands() && "Operand index too large");
707
708   // If the operand is not a constant integer, nothing to do.
709   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
710   if (!OpC) return false;
711
712   // If there are no bits set that aren't demanded, nothing to do.
713   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
714   if ((~Demanded & OpC->getValue()) == 0)
715     return false;
716
717   // This instruction is producing bits that are not demanded. Shrink the RHS.
718   Demanded &= OpC->getValue();
719   I->setOperand(OpNo, Context->getConstantInt(Demanded));
720   return true;
721 }
722
723 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
724 // 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 ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
728                                                    const APInt& KnownOne,
729                                                    APInt& Min, APInt& Max) {
730   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
731          KnownZero.getBitWidth() == Min.getBitWidth() &&
732          KnownZero.getBitWidth() == Max.getBitWidth() &&
733          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
734   APInt UnknownBits = ~(KnownZero|KnownOne);
735
736   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
737   // bit if it is unknown.
738   Min = KnownOne;
739   Max = KnownOne|UnknownBits;
740   
741   if (UnknownBits.isNegative()) { // Sign bit is unknown
742     Min.set(Min.getBitWidth()-1);
743     Max.clear(Max.getBitWidth()-1);
744   }
745 }
746
747 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
748 // a set of known zero and one bits, compute the maximum and minimum values that
749 // could have the specified known zero and known one bits, returning them in
750 // min/max.
751 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
752                                                      const APInt &KnownOne,
753                                                      APInt &Min, APInt &Max) {
754   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
755          KnownZero.getBitWidth() == Min.getBitWidth() &&
756          KnownZero.getBitWidth() == Max.getBitWidth() &&
757          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
758   APInt UnknownBits = ~(KnownZero|KnownOne);
759   
760   // The minimum value is when the unknown bits are all zeros.
761   Min = KnownOne;
762   // The maximum value is when the unknown bits are all ones.
763   Max = KnownOne|UnknownBits;
764 }
765
766 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
767 /// SimplifyDemandedBits knows about.  See if the instruction has any
768 /// properties that allow us to simplify its operands.
769 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
770   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
771   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
772   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
773   
774   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
775                                      KnownZero, KnownOne, 0);
776   if (V == 0) return false;
777   if (V == &Inst) return true;
778   ReplaceInstUsesWith(Inst, V);
779   return true;
780 }
781
782 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
783 /// specified instruction operand if possible, updating it in place.  It returns
784 /// true if it made any change and false otherwise.
785 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
786                                         APInt &KnownZero, APInt &KnownOne,
787                                         unsigned Depth) {
788   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
789                                           KnownZero, KnownOne, Depth);
790   if (NewVal == 0) return false;
791   U.set(NewVal);
792   return true;
793 }
794
795
796 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
797 /// value based on the demanded bits.  When this function is called, it is known
798 /// that only the bits set in DemandedMask of the result of V are ever used
799 /// downstream. Consequently, depending on the mask and V, it may be possible
800 /// to replace V with a constant or one of its operands. In such cases, this
801 /// function does the replacement and returns true. In all other cases, it
802 /// returns false after analyzing the expression and setting KnownOne and known
803 /// to be one in the expression.  KnownZero contains all the bits that are known
804 /// to be zero in the expression. These are provided to potentially allow the
805 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
806 /// the expression. KnownOne and KnownZero always follow the invariant that 
807 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
808 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
809 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
810 /// and KnownOne must all be the same.
811 ///
812 /// This returns null if it did not change anything and it permits no
813 /// simplification.  This returns V itself if it did some simplification of V's
814 /// operands based on the information about what bits are demanded. This returns
815 /// some other non-null value if it found out that V is equal to another value
816 /// in the context where the specified bits are demanded, but not for all users.
817 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
818                                              APInt &KnownZero, APInt &KnownOne,
819                                              unsigned Depth) {
820   assert(V != 0 && "Null pointer of Value???");
821   assert(Depth <= 6 && "Limit Search Depth");
822   uint32_t BitWidth = DemandedMask.getBitWidth();
823   const Type *VTy = V->getType();
824   assert((TD || !isa<PointerType>(VTy)) &&
825          "SimplifyDemandedBits needs to know bit widths!");
826   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
827          (!VTy->isIntOrIntVector() ||
828           VTy->getScalarSizeInBits() == BitWidth) &&
829          KnownZero.getBitWidth() == BitWidth &&
830          KnownOne.getBitWidth() == BitWidth &&
831          "Value *V, DemandedMask, KnownZero and KnownOne "
832          "must have same BitWidth");
833   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
834     // We know all of the bits for a constant!
835     KnownOne = CI->getValue() & DemandedMask;
836     KnownZero = ~KnownOne & DemandedMask;
837     return 0;
838   }
839   if (isa<ConstantPointerNull>(V)) {
840     // We know all of the bits for a constant!
841     KnownOne.clear();
842     KnownZero = DemandedMask;
843     return 0;
844   }
845
846   KnownZero.clear();
847   KnownOne.clear();
848   if (DemandedMask == 0) {   // Not demanding any bits from V.
849     if (isa<UndefValue>(V))
850       return 0;
851     return Context->getUndef(VTy);
852   }
853   
854   if (Depth == 6)        // Limit search depth.
855     return 0;
856   
857   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
858   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
859
860   Instruction *I = dyn_cast<Instruction>(V);
861   if (!I) {
862     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
863     return 0;        // Only analyze instructions.
864   }
865
866   // If there are multiple uses of this value and we aren't at the root, then
867   // we can't do any simplifications of the operands, because DemandedMask
868   // only reflects the bits demanded by *one* of the users.
869   if (Depth != 0 && !I->hasOneUse()) {
870     // Despite the fact that we can't simplify this instruction in all User's
871     // context, we can at least compute the knownzero/knownone bits, and we can
872     // do simplifications that apply to *just* the one user if we know that
873     // this instruction has a simpler value in that context.
874     if (I->getOpcode() == Instruction::And) {
875       // If either the LHS or the RHS are Zero, the result is zero.
876       ComputeMaskedBits(I->getOperand(1), DemandedMask,
877                         RHSKnownZero, RHSKnownOne, Depth+1);
878       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
879                         LHSKnownZero, LHSKnownOne, Depth+1);
880       
881       // If all of the demanded bits are known 1 on one side, return the other.
882       // These bits cannot contribute to the result of the 'and' in this
883       // context.
884       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
885           (DemandedMask & ~LHSKnownZero))
886         return I->getOperand(0);
887       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
888           (DemandedMask & ~RHSKnownZero))
889         return I->getOperand(1);
890       
891       // If all of the demanded bits in the inputs are known zeros, return zero.
892       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
893         return Context->getNullValue(VTy);
894       
895     } else if (I->getOpcode() == Instruction::Or) {
896       // We can simplify (X|Y) -> X or Y in the user's context if we know that
897       // only bits from X or Y are demanded.
898       
899       // If either the LHS or the RHS are One, the result is One.
900       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
901                         RHSKnownZero, RHSKnownOne, Depth+1);
902       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
903                         LHSKnownZero, LHSKnownOne, Depth+1);
904       
905       // If all of the demanded bits are known zero on one side, return the
906       // other.  These bits cannot contribute to the result of the 'or' in this
907       // context.
908       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
909           (DemandedMask & ~LHSKnownOne))
910         return I->getOperand(0);
911       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
912           (DemandedMask & ~RHSKnownOne))
913         return I->getOperand(1);
914       
915       // If all of the potentially set bits on one side are known to be set on
916       // the other side, just use the 'other' side.
917       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
918           (DemandedMask & (~RHSKnownZero)))
919         return I->getOperand(0);
920       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
921           (DemandedMask & (~LHSKnownZero)))
922         return I->getOperand(1);
923     }
924     
925     // Compute the KnownZero/KnownOne bits to simplify things downstream.
926     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
927     return 0;
928   }
929   
930   // If this is the root being simplified, allow it to have multiple uses,
931   // just set the DemandedMask to all bits so that we can try to simplify the
932   // operands.  This allows visitTruncInst (for example) to simplify the
933   // operand of a trunc without duplicating all the logic below.
934   if (Depth == 0 && !V->hasOneUse())
935     DemandedMask = APInt::getAllOnesValue(BitWidth);
936   
937   switch (I->getOpcode()) {
938   default:
939     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
940     break;
941   case Instruction::And:
942     // If either the LHS or the RHS are Zero, the result is zero.
943     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
944                              RHSKnownZero, RHSKnownOne, Depth+1) ||
945         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
946                              LHSKnownZero, LHSKnownOne, Depth+1))
947       return I;
948     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
949     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
950
951     // If all of the demanded bits are known 1 on one side, return the other.
952     // These bits cannot contribute to the result of the 'and'.
953     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
954         (DemandedMask & ~LHSKnownZero))
955       return I->getOperand(0);
956     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
957         (DemandedMask & ~RHSKnownZero))
958       return I->getOperand(1);
959     
960     // If all of the demanded bits in the inputs are known zeros, return zero.
961     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
962       return Context->getNullValue(VTy);
963       
964     // If the RHS is a constant, see if we can simplify it.
965     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero, Context))
966       return I;
967       
968     // Output known-1 bits are only known if set in both the LHS & RHS.
969     RHSKnownOne &= LHSKnownOne;
970     // Output known-0 are known to be clear if zero in either the LHS | RHS.
971     RHSKnownZero |= LHSKnownZero;
972     break;
973   case Instruction::Or:
974     // If either the LHS or the RHS are One, the result is One.
975     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
976                              RHSKnownZero, RHSKnownOne, Depth+1) ||
977         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
978                              LHSKnownZero, LHSKnownOne, Depth+1))
979       return I;
980     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
981     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
982     
983     // If all of the demanded bits are known zero on one side, return the other.
984     // These bits cannot contribute to the result of the 'or'.
985     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
986         (DemandedMask & ~LHSKnownOne))
987       return I->getOperand(0);
988     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
989         (DemandedMask & ~RHSKnownOne))
990       return I->getOperand(1);
991
992     // If all of the potentially set bits on one side are known to be set on
993     // the other side, just use the 'other' side.
994     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
995         (DemandedMask & (~RHSKnownZero)))
996       return I->getOperand(0);
997     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
998         (DemandedMask & (~LHSKnownZero)))
999       return I->getOperand(1);
1000         
1001     // If the RHS is a constant, see if we can simplify it.
1002     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
1003       return I;
1004           
1005     // Output known-0 bits are only known if clear in both the LHS & RHS.
1006     RHSKnownZero &= LHSKnownZero;
1007     // Output known-1 are known to be set if set in either the LHS | RHS.
1008     RHSKnownOne |= LHSKnownOne;
1009     break;
1010   case Instruction::Xor: {
1011     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1012                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1013         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1014                              LHSKnownZero, LHSKnownOne, Depth+1))
1015       return I;
1016     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1017     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1018     
1019     // If all of the demanded bits are known zero on one side, return the other.
1020     // These bits cannot contribute to the result of the 'xor'.
1021     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1022       return I->getOperand(0);
1023     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1024       return I->getOperand(1);
1025     
1026     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1027     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1028                          (RHSKnownOne & LHSKnownOne);
1029     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1030     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1031                         (RHSKnownOne & LHSKnownZero);
1032     
1033     // If all of the demanded bits are known to be zero on one side or the
1034     // other, turn this into an *inclusive* or.
1035     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1036     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1037       Instruction *Or =
1038         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1039                                  I->getName());
1040       return InsertNewInstBefore(Or, *I);
1041     }
1042     
1043     // If all of the demanded bits on one side are known, and all of the set
1044     // bits on that side are also known to be set on the other side, turn this
1045     // into an AND, as we know the bits will be cleared.
1046     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1047     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1048       // all known
1049       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1050         Constant *AndC = Context->getConstantInt(~RHSKnownOne & DemandedMask);
1051         Instruction *And = 
1052           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1053         return InsertNewInstBefore(And, *I);
1054       }
1055     }
1056     
1057     // If the RHS is a constant, see if we can simplify it.
1058     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1059     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
1060       return I;
1061     
1062     RHSKnownZero = KnownZeroOut;
1063     RHSKnownOne  = KnownOneOut;
1064     break;
1065   }
1066   case Instruction::Select:
1067     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1068                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1069         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1070                              LHSKnownZero, LHSKnownOne, Depth+1))
1071       return I;
1072     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1073     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1074     
1075     // If the operands are constants, see if we can simplify them.
1076     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context) ||
1077         ShrinkDemandedConstant(I, 2, DemandedMask, Context))
1078       return I;
1079     
1080     // Only known if known in both the LHS and RHS.
1081     RHSKnownOne &= LHSKnownOne;
1082     RHSKnownZero &= LHSKnownZero;
1083     break;
1084   case Instruction::Trunc: {
1085     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1086     DemandedMask.zext(truncBf);
1087     RHSKnownZero.zext(truncBf);
1088     RHSKnownOne.zext(truncBf);
1089     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1090                              RHSKnownZero, RHSKnownOne, Depth+1))
1091       return I;
1092     DemandedMask.trunc(BitWidth);
1093     RHSKnownZero.trunc(BitWidth);
1094     RHSKnownOne.trunc(BitWidth);
1095     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1096     break;
1097   }
1098   case Instruction::BitCast:
1099     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1100       return false;  // vector->int or fp->int?
1101
1102     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1103       if (const VectorType *SrcVTy =
1104             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1105         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1106           // Don't touch a bitcast between vectors of different element counts.
1107           return false;
1108       } else
1109         // Don't touch a scalar-to-vector bitcast.
1110         return false;
1111     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1112       // Don't touch a vector-to-scalar bitcast.
1113       return false;
1114
1115     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1116                              RHSKnownZero, RHSKnownOne, Depth+1))
1117       return I;
1118     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1119     break;
1120   case Instruction::ZExt: {
1121     // Compute the bits in the result that are not present in the input.
1122     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1123     
1124     DemandedMask.trunc(SrcBitWidth);
1125     RHSKnownZero.trunc(SrcBitWidth);
1126     RHSKnownOne.trunc(SrcBitWidth);
1127     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1128                              RHSKnownZero, RHSKnownOne, Depth+1))
1129       return I;
1130     DemandedMask.zext(BitWidth);
1131     RHSKnownZero.zext(BitWidth);
1132     RHSKnownOne.zext(BitWidth);
1133     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1134     // The top bits are known to be zero.
1135     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1136     break;
1137   }
1138   case Instruction::SExt: {
1139     // Compute the bits in the result that are not present in the input.
1140     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1141     
1142     APInt InputDemandedBits = DemandedMask & 
1143                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1144
1145     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1146     // If any of the sign extended bits are demanded, we know that the sign
1147     // bit is demanded.
1148     if ((NewBits & DemandedMask) != 0)
1149       InputDemandedBits.set(SrcBitWidth-1);
1150       
1151     InputDemandedBits.trunc(SrcBitWidth);
1152     RHSKnownZero.trunc(SrcBitWidth);
1153     RHSKnownOne.trunc(SrcBitWidth);
1154     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1155                              RHSKnownZero, RHSKnownOne, Depth+1))
1156       return I;
1157     InputDemandedBits.zext(BitWidth);
1158     RHSKnownZero.zext(BitWidth);
1159     RHSKnownOne.zext(BitWidth);
1160     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1161       
1162     // If the sign bit of the input is known set or clear, then we know the
1163     // top bits of the result.
1164
1165     // If the input sign bit is known zero, or if the NewBits are not demanded
1166     // convert this into a zero extension.
1167     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1168       // Convert to ZExt cast
1169       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1170       return InsertNewInstBefore(NewCast, *I);
1171     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1172       RHSKnownOne |= NewBits;
1173     }
1174     break;
1175   }
1176   case Instruction::Add: {
1177     // Figure out what the input bits are.  If the top bits of the and result
1178     // are not demanded, then the add doesn't demand them from its input
1179     // either.
1180     unsigned NLZ = DemandedMask.countLeadingZeros();
1181       
1182     // If there is a constant on the RHS, there are a variety of xformations
1183     // we can do.
1184     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1185       // If null, this should be simplified elsewhere.  Some of the xforms here
1186       // won't work if the RHS is zero.
1187       if (RHS->isZero())
1188         break;
1189       
1190       // If the top bit of the output is demanded, demand everything from the
1191       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1192       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1193
1194       // Find information about known zero/one bits in the input.
1195       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1196                                LHSKnownZero, LHSKnownOne, Depth+1))
1197         return I;
1198
1199       // If the RHS of the add has bits set that can't affect the input, reduce
1200       // the constant.
1201       if (ShrinkDemandedConstant(I, 1, InDemandedBits, Context))
1202         return I;
1203       
1204       // Avoid excess work.
1205       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1206         break;
1207       
1208       // Turn it into OR if input bits are zero.
1209       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1210         Instruction *Or =
1211           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1212                                    I->getName());
1213         return InsertNewInstBefore(Or, *I);
1214       }
1215       
1216       // We can say something about the output known-zero and known-one bits,
1217       // depending on potential carries from the input constant and the
1218       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1219       // bits set and the RHS constant is 0x01001, then we know we have a known
1220       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1221       
1222       // To compute this, we first compute the potential carry bits.  These are
1223       // the bits which may be modified.  I'm not aware of a better way to do
1224       // this scan.
1225       const APInt &RHSVal = RHS->getValue();
1226       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1227       
1228       // Now that we know which bits have carries, compute the known-1/0 sets.
1229       
1230       // Bits are known one if they are known zero in one operand and one in the
1231       // other, and there is no input carry.
1232       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1233                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1234       
1235       // Bits are known zero if they are known zero in both operands and there
1236       // is no input carry.
1237       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1238     } else {
1239       // If the high-bits of this ADD are not demanded, then it does not demand
1240       // the high bits of its LHS or RHS.
1241       if (DemandedMask[BitWidth-1] == 0) {
1242         // Right fill the mask of bits for this ADD to demand the most
1243         // significant bit and all those below it.
1244         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1245         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1246                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1247             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1248                                  LHSKnownZero, LHSKnownOne, Depth+1))
1249           return I;
1250       }
1251     }
1252     break;
1253   }
1254   case Instruction::Sub:
1255     // If the high-bits of this SUB are not demanded, then it does not demand
1256     // the high bits of its LHS or RHS.
1257     if (DemandedMask[BitWidth-1] == 0) {
1258       // Right fill the mask of bits for this SUB to demand the most
1259       // significant bit and all those below it.
1260       uint32_t NLZ = DemandedMask.countLeadingZeros();
1261       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1262       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1263                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1264           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1265                                LHSKnownZero, LHSKnownOne, Depth+1))
1266         return I;
1267     }
1268     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1269     // the known zeros and ones.
1270     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1271     break;
1272   case Instruction::Shl:
1273     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1274       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1275       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1276       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1277                                RHSKnownZero, RHSKnownOne, Depth+1))
1278         return I;
1279       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1280       RHSKnownZero <<= ShiftAmt;
1281       RHSKnownOne  <<= ShiftAmt;
1282       // low bits known zero.
1283       if (ShiftAmt)
1284         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1285     }
1286     break;
1287   case Instruction::LShr:
1288     // For a logical shift right
1289     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1290       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1291       
1292       // Unsigned shift right.
1293       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1294       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1295                                RHSKnownZero, RHSKnownOne, Depth+1))
1296         return I;
1297       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1298       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1299       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1300       if (ShiftAmt) {
1301         // Compute the new bits that are at the top now.
1302         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1303         RHSKnownZero |= HighBits;  // high bits known zero.
1304       }
1305     }
1306     break;
1307   case Instruction::AShr:
1308     // If this is an arithmetic shift right and only the low-bit is set, we can
1309     // always convert this into a logical shr, even if the shift amount is
1310     // variable.  The low bit of the shift cannot be an input sign bit unless
1311     // the shift amount is >= the size of the datatype, which is undefined.
1312     if (DemandedMask == 1) {
1313       // Perform the logical shift right.
1314       Instruction *NewVal = BinaryOperator::CreateLShr(
1315                         I->getOperand(0), I->getOperand(1), I->getName());
1316       return InsertNewInstBefore(NewVal, *I);
1317     }    
1318
1319     // If the sign bit is the only bit demanded by this ashr, then there is no
1320     // need to do it, the shift doesn't change the high bit.
1321     if (DemandedMask.isSignBit())
1322       return I->getOperand(0);
1323     
1324     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1325       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1326       
1327       // Signed shift right.
1328       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1329       // If any of the "high bits" are demanded, we should set the sign bit as
1330       // demanded.
1331       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1332         DemandedMaskIn.set(BitWidth-1);
1333       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1334                                RHSKnownZero, RHSKnownOne, Depth+1))
1335         return I;
1336       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1337       // Compute the new bits that are at the top now.
1338       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1339       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1340       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1341         
1342       // Handle the sign bits.
1343       APInt SignBit(APInt::getSignBit(BitWidth));
1344       // Adjust to where it is now in the mask.
1345       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1346         
1347       // If the input sign bit is known to be zero, or if none of the top bits
1348       // are demanded, turn this into an unsigned shift right.
1349       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1350           (HighBits & ~DemandedMask) == HighBits) {
1351         // Perform the logical shift right.
1352         Instruction *NewVal = BinaryOperator::CreateLShr(
1353                           I->getOperand(0), SA, I->getName());
1354         return InsertNewInstBefore(NewVal, *I);
1355       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1356         RHSKnownOne |= HighBits;
1357       }
1358     }
1359     break;
1360   case Instruction::SRem:
1361     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1362       APInt RA = Rem->getValue().abs();
1363       if (RA.isPowerOf2()) {
1364         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1365           return I->getOperand(0);
1366
1367         APInt LowBits = RA - 1;
1368         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1369         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1370                                  LHSKnownZero, LHSKnownOne, Depth+1))
1371           return I;
1372
1373         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1374           LHSKnownZero |= ~LowBits;
1375
1376         KnownZero |= LHSKnownZero & DemandedMask;
1377
1378         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1379       }
1380     }
1381     break;
1382   case Instruction::URem: {
1383     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1384     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1385     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1386                              KnownZero2, KnownOne2, Depth+1) ||
1387         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1388                              KnownZero2, KnownOne2, Depth+1))
1389       return I;
1390
1391     unsigned Leaders = KnownZero2.countLeadingOnes();
1392     Leaders = std::max(Leaders,
1393                        KnownZero2.countLeadingOnes());
1394     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1395     break;
1396   }
1397   case Instruction::Call:
1398     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1399       switch (II->getIntrinsicID()) {
1400       default: break;
1401       case Intrinsic::bswap: {
1402         // If the only bits demanded come from one byte of the bswap result,
1403         // just shift the input byte into position to eliminate the bswap.
1404         unsigned NLZ = DemandedMask.countLeadingZeros();
1405         unsigned NTZ = DemandedMask.countTrailingZeros();
1406           
1407         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1408         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1409         // have 14 leading zeros, round to 8.
1410         NLZ &= ~7;
1411         NTZ &= ~7;
1412         // If we need exactly one byte, we can do this transformation.
1413         if (BitWidth-NLZ-NTZ == 8) {
1414           unsigned ResultBit = NTZ;
1415           unsigned InputBit = BitWidth-NTZ-8;
1416           
1417           // Replace this with either a left or right shift to get the byte into
1418           // the right place.
1419           Instruction *NewVal;
1420           if (InputBit > ResultBit)
1421             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1422                     Context->getConstantInt(I->getType(), InputBit-ResultBit));
1423           else
1424             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1425                     Context->getConstantInt(I->getType(), ResultBit-InputBit));
1426           NewVal->takeName(I);
1427           return InsertNewInstBefore(NewVal, *I);
1428         }
1429           
1430         // TODO: Could compute known zero/one bits based on the input.
1431         break;
1432       }
1433       }
1434     }
1435     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1436     break;
1437   }
1438   
1439   // If the client is only demanding bits that we know, return the known
1440   // constant.
1441   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1442     Constant *C = Context->getConstantInt(RHSKnownOne);
1443     if (isa<PointerType>(V->getType()))
1444       C = Context->getConstantExprIntToPtr(C, V->getType());
1445     return C;
1446   }
1447   return false;
1448 }
1449
1450
1451 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1452 /// any number of elements. DemandedElts contains the set of elements that are
1453 /// actually used by the caller.  This method analyzes which elements of the
1454 /// operand are undef and returns that information in UndefElts.
1455 ///
1456 /// If the information about demanded elements can be used to simplify the
1457 /// operation, the operation is simplified, then the resultant value is
1458 /// returned.  This returns null if no change was made.
1459 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1460                                                 APInt& UndefElts,
1461                                                 unsigned Depth) {
1462   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1463   APInt EltMask(APInt::getAllOnesValue(VWidth));
1464   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1465
1466   if (isa<UndefValue>(V)) {
1467     // If the entire vector is undefined, just return this info.
1468     UndefElts = EltMask;
1469     return 0;
1470   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1471     UndefElts = EltMask;
1472     return Context->getUndef(V->getType());
1473   }
1474
1475   UndefElts = 0;
1476   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1477     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1478     Constant *Undef = Context->getUndef(EltTy);
1479
1480     std::vector<Constant*> Elts;
1481     for (unsigned i = 0; i != VWidth; ++i)
1482       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1483         Elts.push_back(Undef);
1484         UndefElts.set(i);
1485       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1486         Elts.push_back(Undef);
1487         UndefElts.set(i);
1488       } else {                               // Otherwise, defined.
1489         Elts.push_back(CP->getOperand(i));
1490       }
1491
1492     // If we changed the constant, return it.
1493     Constant *NewCP = Context->getConstantVector(Elts);
1494     return NewCP != CP ? NewCP : 0;
1495   } else if (isa<ConstantAggregateZero>(V)) {
1496     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1497     // set to undef.
1498     
1499     // Check if this is identity. If so, return 0 since we are not simplifying
1500     // anything.
1501     if (DemandedElts == ((1ULL << VWidth) -1))
1502       return 0;
1503     
1504     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1505     Constant *Zero = Context->getNullValue(EltTy);
1506     Constant *Undef = Context->getUndef(EltTy);
1507     std::vector<Constant*> Elts;
1508     for (unsigned i = 0; i != VWidth; ++i) {
1509       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1510       Elts.push_back(Elt);
1511     }
1512     UndefElts = DemandedElts ^ EltMask;
1513     return Context->getConstantVector(Elts);
1514   }
1515   
1516   // Limit search depth.
1517   if (Depth == 10)
1518     return 0;
1519
1520   // If multiple users are using the root value, procede with
1521   // simplification conservatively assuming that all elements
1522   // are needed.
1523   if (!V->hasOneUse()) {
1524     // Quit if we find multiple users of a non-root value though.
1525     // They'll be handled when it's their turn to be visited by
1526     // the main instcombine process.
1527     if (Depth != 0)
1528       // TODO: Just compute the UndefElts information recursively.
1529       return 0;
1530
1531     // Conservatively assume that all elements are needed.
1532     DemandedElts = EltMask;
1533   }
1534   
1535   Instruction *I = dyn_cast<Instruction>(V);
1536   if (!I) return 0;        // Only analyze instructions.
1537   
1538   bool MadeChange = false;
1539   APInt UndefElts2(VWidth, 0);
1540   Value *TmpV;
1541   switch (I->getOpcode()) {
1542   default: break;
1543     
1544   case Instruction::InsertElement: {
1545     // If this is a variable index, we don't know which element it overwrites.
1546     // demand exactly the same input as we produce.
1547     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1548     if (Idx == 0) {
1549       // Note that we can't propagate undef elt info, because we don't know
1550       // which elt is getting updated.
1551       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1552                                         UndefElts2, Depth+1);
1553       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1554       break;
1555     }
1556     
1557     // If this is inserting an element that isn't demanded, remove this
1558     // insertelement.
1559     unsigned IdxNo = Idx->getZExtValue();
1560     if (IdxNo >= VWidth || !DemandedElts[IdxNo])
1561       return AddSoonDeadInstToWorklist(*I, 0);
1562     
1563     // Otherwise, the element inserted overwrites whatever was there, so the
1564     // input demanded set is simpler than the output set.
1565     APInt DemandedElts2 = DemandedElts;
1566     DemandedElts2.clear(IdxNo);
1567     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1568                                       UndefElts, Depth+1);
1569     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1570
1571     // The inserted element is defined.
1572     UndefElts.clear(IdxNo);
1573     break;
1574   }
1575   case Instruction::ShuffleVector: {
1576     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1577     uint64_t LHSVWidth =
1578       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1579     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1580     for (unsigned i = 0; i < VWidth; i++) {
1581       if (DemandedElts[i]) {
1582         unsigned MaskVal = Shuffle->getMaskValue(i);
1583         if (MaskVal != -1u) {
1584           assert(MaskVal < LHSVWidth * 2 &&
1585                  "shufflevector mask index out of range!");
1586           if (MaskVal < LHSVWidth)
1587             LeftDemanded.set(MaskVal);
1588           else
1589             RightDemanded.set(MaskVal - LHSVWidth);
1590         }
1591       }
1592     }
1593
1594     APInt UndefElts4(LHSVWidth, 0);
1595     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1596                                       UndefElts4, Depth+1);
1597     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1598
1599     APInt UndefElts3(LHSVWidth, 0);
1600     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1601                                       UndefElts3, Depth+1);
1602     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1603
1604     bool NewUndefElts = false;
1605     for (unsigned i = 0; i < VWidth; i++) {
1606       unsigned MaskVal = Shuffle->getMaskValue(i);
1607       if (MaskVal == -1u) {
1608         UndefElts.set(i);
1609       } else if (MaskVal < LHSVWidth) {
1610         if (UndefElts4[MaskVal]) {
1611           NewUndefElts = true;
1612           UndefElts.set(i);
1613         }
1614       } else {
1615         if (UndefElts3[MaskVal - LHSVWidth]) {
1616           NewUndefElts = true;
1617           UndefElts.set(i);
1618         }
1619       }
1620     }
1621
1622     if (NewUndefElts) {
1623       // Add additional discovered undefs.
1624       std::vector<Constant*> Elts;
1625       for (unsigned i = 0; i < VWidth; ++i) {
1626         if (UndefElts[i])
1627           Elts.push_back(Context->getUndef(Type::Int32Ty));
1628         else
1629           Elts.push_back(Context->getConstantInt(Type::Int32Ty,
1630                                           Shuffle->getMaskValue(i)));
1631       }
1632       I->setOperand(2, Context->getConstantVector(Elts));
1633       MadeChange = true;
1634     }
1635     break;
1636   }
1637   case Instruction::BitCast: {
1638     // Vector->vector casts only.
1639     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1640     if (!VTy) break;
1641     unsigned InVWidth = VTy->getNumElements();
1642     APInt InputDemandedElts(InVWidth, 0);
1643     unsigned Ratio;
1644
1645     if (VWidth == InVWidth) {
1646       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1647       // elements as are demanded of us.
1648       Ratio = 1;
1649       InputDemandedElts = DemandedElts;
1650     } else if (VWidth > InVWidth) {
1651       // Untested so far.
1652       break;
1653       
1654       // If there are more elements in the result than there are in the source,
1655       // then an input element is live if any of the corresponding output
1656       // elements are live.
1657       Ratio = VWidth/InVWidth;
1658       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1659         if (DemandedElts[OutIdx])
1660           InputDemandedElts.set(OutIdx/Ratio);
1661       }
1662     } else {
1663       // Untested so far.
1664       break;
1665       
1666       // If there are more elements in the source than there are in the result,
1667       // then an input element is live if the corresponding output element is
1668       // live.
1669       Ratio = InVWidth/VWidth;
1670       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1671         if (DemandedElts[InIdx/Ratio])
1672           InputDemandedElts.set(InIdx);
1673     }
1674     
1675     // div/rem demand all inputs, because they don't want divide by zero.
1676     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1677                                       UndefElts2, Depth+1);
1678     if (TmpV) {
1679       I->setOperand(0, TmpV);
1680       MadeChange = true;
1681     }
1682     
1683     UndefElts = UndefElts2;
1684     if (VWidth > InVWidth) {
1685       llvm_unreachable("Unimp");
1686       // If there are more elements in the result than there are in the source,
1687       // then an output element is undef if the corresponding input element is
1688       // undef.
1689       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1690         if (UndefElts2[OutIdx/Ratio])
1691           UndefElts.set(OutIdx);
1692     } else if (VWidth < InVWidth) {
1693       llvm_unreachable("Unimp");
1694       // If there are more elements in the source than there are in the result,
1695       // then a result element is undef if all of the corresponding input
1696       // elements are undef.
1697       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1698       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1699         if (!UndefElts2[InIdx])            // Not undef?
1700           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1701     }
1702     break;
1703   }
1704   case Instruction::And:
1705   case Instruction::Or:
1706   case Instruction::Xor:
1707   case Instruction::Add:
1708   case Instruction::Sub:
1709   case Instruction::Mul:
1710     // div/rem demand all inputs, because they don't want divide by zero.
1711     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1712                                       UndefElts, Depth+1);
1713     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1714     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1715                                       UndefElts2, Depth+1);
1716     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1717       
1718     // Output elements are undefined if both are undefined.  Consider things
1719     // like undef&0.  The result is known zero, not undef.
1720     UndefElts &= UndefElts2;
1721     break;
1722     
1723   case Instruction::Call: {
1724     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1725     if (!II) break;
1726     switch (II->getIntrinsicID()) {
1727     default: break;
1728       
1729     // Binary vector operations that work column-wise.  A dest element is a
1730     // function of the corresponding input elements from the two inputs.
1731     case Intrinsic::x86_sse_sub_ss:
1732     case Intrinsic::x86_sse_mul_ss:
1733     case Intrinsic::x86_sse_min_ss:
1734     case Intrinsic::x86_sse_max_ss:
1735     case Intrinsic::x86_sse2_sub_sd:
1736     case Intrinsic::x86_sse2_mul_sd:
1737     case Intrinsic::x86_sse2_min_sd:
1738     case Intrinsic::x86_sse2_max_sd:
1739       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1740                                         UndefElts, Depth+1);
1741       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1742       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1743                                         UndefElts2, Depth+1);
1744       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1745
1746       // If only the low elt is demanded and this is a scalarizable intrinsic,
1747       // scalarize it now.
1748       if (DemandedElts == 1) {
1749         switch (II->getIntrinsicID()) {
1750         default: break;
1751         case Intrinsic::x86_sse_sub_ss:
1752         case Intrinsic::x86_sse_mul_ss:
1753         case Intrinsic::x86_sse2_sub_sd:
1754         case Intrinsic::x86_sse2_mul_sd:
1755           // TODO: Lower MIN/MAX/ABS/etc
1756           Value *LHS = II->getOperand(1);
1757           Value *RHS = II->getOperand(2);
1758           // Extract the element as scalars.
1759           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 
1760             Context->getConstantInt(Type::Int32Ty, 0U, false), "tmp"), *II);
1761           RHS = InsertNewInstBefore(new ExtractElementInst(RHS,
1762             Context->getConstantInt(Type::Int32Ty, 0U, false), "tmp"), *II);
1763           
1764           switch (II->getIntrinsicID()) {
1765           default: llvm_unreachable("Case stmts out of sync!");
1766           case Intrinsic::x86_sse_sub_ss:
1767           case Intrinsic::x86_sse2_sub_sd:
1768             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1769                                                         II->getName()), *II);
1770             break;
1771           case Intrinsic::x86_sse_mul_ss:
1772           case Intrinsic::x86_sse2_mul_sd:
1773             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1774                                                          II->getName()), *II);
1775             break;
1776           }
1777           
1778           Instruction *New =
1779             InsertElementInst::Create(
1780               Context->getUndef(II->getType()), TmpV,
1781               Context->getConstantInt(Type::Int32Ty, 0U, false), II->getName());
1782           InsertNewInstBefore(New, *II);
1783           AddSoonDeadInstToWorklist(*II, 0);
1784           return New;
1785         }            
1786       }
1787         
1788       // Output elements are undefined if both are undefined.  Consider things
1789       // like undef&0.  The result is known zero, not undef.
1790       UndefElts &= UndefElts2;
1791       break;
1792     }
1793     break;
1794   }
1795   }
1796   return MadeChange ? I : 0;
1797 }
1798
1799
1800 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1801 /// function is designed to check a chain of associative operators for a
1802 /// potential to apply a certain optimization.  Since the optimization may be
1803 /// applicable if the expression was reassociated, this checks the chain, then
1804 /// reassociates the expression as necessary to expose the optimization
1805 /// opportunity.  This makes use of a special Functor, which must define
1806 /// 'shouldApply' and 'apply' methods.
1807 ///
1808 template<typename Functor>
1809 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F,
1810                                    LLVMContext *Context) {
1811   unsigned Opcode = Root.getOpcode();
1812   Value *LHS = Root.getOperand(0);
1813
1814   // Quick check, see if the immediate LHS matches...
1815   if (F.shouldApply(LHS))
1816     return F.apply(Root);
1817
1818   // Otherwise, if the LHS is not of the same opcode as the root, return.
1819   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1820   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1821     // Should we apply this transform to the RHS?
1822     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1823
1824     // If not to the RHS, check to see if we should apply to the LHS...
1825     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1826       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1827       ShouldApply = true;
1828     }
1829
1830     // If the functor wants to apply the optimization to the RHS of LHSI,
1831     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1832     if (ShouldApply) {
1833       // Now all of the instructions are in the current basic block, go ahead
1834       // and perform the reassociation.
1835       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1836
1837       // First move the selected RHS to the LHS of the root...
1838       Root.setOperand(0, LHSI->getOperand(1));
1839
1840       // Make what used to be the LHS of the root be the user of the root...
1841       Value *ExtraOperand = TmpLHSI->getOperand(1);
1842       if (&Root == TmpLHSI) {
1843         Root.replaceAllUsesWith(Context->getNullValue(TmpLHSI->getType()));
1844         return 0;
1845       }
1846       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1847       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1848       BasicBlock::iterator ARI = &Root; ++ARI;
1849       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1850       ARI = Root;
1851
1852       // Now propagate the ExtraOperand down the chain of instructions until we
1853       // get to LHSI.
1854       while (TmpLHSI != LHSI) {
1855         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1856         // Move the instruction to immediately before the chain we are
1857         // constructing to avoid breaking dominance properties.
1858         NextLHSI->moveBefore(ARI);
1859         ARI = NextLHSI;
1860
1861         Value *NextOp = NextLHSI->getOperand(1);
1862         NextLHSI->setOperand(1, ExtraOperand);
1863         TmpLHSI = NextLHSI;
1864         ExtraOperand = NextOp;
1865       }
1866
1867       // Now that the instructions are reassociated, have the functor perform
1868       // the transformation...
1869       return F.apply(Root);
1870     }
1871
1872     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1873   }
1874   return 0;
1875 }
1876
1877 namespace {
1878
1879 // AddRHS - Implements: X + X --> X << 1
1880 struct AddRHS {
1881   Value *RHS;
1882   LLVMContext *Context;
1883   AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
1884   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1885   Instruction *apply(BinaryOperator &Add) const {
1886     return BinaryOperator::CreateShl(Add.getOperand(0),
1887                                      Context->getConstantInt(Add.getType(), 1));
1888   }
1889 };
1890
1891 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1892 //                 iff C1&C2 == 0
1893 struct AddMaskingAnd {
1894   Constant *C2;
1895   LLVMContext *Context;
1896   AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
1897   bool shouldApply(Value *LHS) const {
1898     ConstantInt *C1;
1899     return match(LHS, m_And(m_Value(), m_ConstantInt(C1)), *Context) &&
1900            Context->getConstantExprAnd(C1, C2)->isNullValue();
1901   }
1902   Instruction *apply(BinaryOperator &Add) const {
1903     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1904   }
1905 };
1906
1907 }
1908
1909 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1910                                              InstCombiner *IC) {
1911   LLVMContext *Context = IC->getContext();
1912   
1913   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1914     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1915   }
1916
1917   // Figure out if the constant is the left or the right argument.
1918   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1919   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1920
1921   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1922     if (ConstIsRHS)
1923       return Context->getConstantExpr(I.getOpcode(), SOC, ConstOperand);
1924     return Context->getConstantExpr(I.getOpcode(), ConstOperand, SOC);
1925   }
1926
1927   Value *Op0 = SO, *Op1 = ConstOperand;
1928   if (!ConstIsRHS)
1929     std::swap(Op0, Op1);
1930   Instruction *New;
1931   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1932     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1933   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1934     New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1935                           Op0, Op1, SO->getName()+".cmp");
1936   else {
1937     llvm_unreachable("Unknown binary instruction type!");
1938   }
1939   return IC->InsertNewInstBefore(New, I);
1940 }
1941
1942 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1943 // constant as the other operand, try to fold the binary operator into the
1944 // select arguments.  This also works for Cast instructions, which obviously do
1945 // not have a second operand.
1946 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1947                                      InstCombiner *IC) {
1948   // Don't modify shared select instructions
1949   if (!SI->hasOneUse()) return 0;
1950   Value *TV = SI->getOperand(1);
1951   Value *FV = SI->getOperand(2);
1952
1953   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1954     // Bool selects with constant operands can be folded to logical ops.
1955     if (SI->getType() == Type::Int1Ty) return 0;
1956
1957     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1958     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1959
1960     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1961                               SelectFalseVal);
1962   }
1963   return 0;
1964 }
1965
1966
1967 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1968 /// node as operand #0, see if we can fold the instruction into the PHI (which
1969 /// is only possible if all operands to the PHI are constants).
1970 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1971   PHINode *PN = cast<PHINode>(I.getOperand(0));
1972   unsigned NumPHIValues = PN->getNumIncomingValues();
1973   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1974
1975   // Check to see if all of the operands of the PHI are constants.  If there is
1976   // one non-constant value, remember the BB it is.  If there is more than one
1977   // or if *it* is a PHI, bail out.
1978   BasicBlock *NonConstBB = 0;
1979   for (unsigned i = 0; i != NumPHIValues; ++i)
1980     if (!isa<Constant>(PN->getIncomingValue(i))) {
1981       if (NonConstBB) return 0;  // More than one non-const value.
1982       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1983       NonConstBB = PN->getIncomingBlock(i);
1984       
1985       // If the incoming non-constant value is in I's block, we have an infinite
1986       // loop.
1987       if (NonConstBB == I.getParent())
1988         return 0;
1989     }
1990   
1991   // If there is exactly one non-constant value, we can insert a copy of the
1992   // operation in that block.  However, if this is a critical edge, we would be
1993   // inserting the computation one some other paths (e.g. inside a loop).  Only
1994   // do this if the pred block is unconditionally branching into the phi block.
1995   if (NonConstBB) {
1996     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1997     if (!BI || !BI->isUnconditional()) return 0;
1998   }
1999
2000   // Okay, we can do the transformation: create the new PHI node.
2001   PHINode *NewPN = PHINode::Create(I.getType(), "");
2002   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2003   InsertNewInstBefore(NewPN, *PN);
2004   NewPN->takeName(PN);
2005
2006   // Next, add all of the operands to the PHI.
2007   if (I.getNumOperands() == 2) {
2008     Constant *C = cast<Constant>(I.getOperand(1));
2009     for (unsigned i = 0; i != NumPHIValues; ++i) {
2010       Value *InV = 0;
2011       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2012         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2013           InV = Context->getConstantExprCompare(CI->getPredicate(), InC, C);
2014         else
2015           InV = Context->getConstantExpr(I.getOpcode(), InC, C);
2016       } else {
2017         assert(PN->getIncomingBlock(i) == NonConstBB);
2018         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
2019           InV = BinaryOperator::Create(BO->getOpcode(),
2020                                        PN->getIncomingValue(i), C, "phitmp",
2021                                        NonConstBB->getTerminator());
2022         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2023           InV = CmpInst::Create(*Context, CI->getOpcode(), 
2024                                 CI->getPredicate(),
2025                                 PN->getIncomingValue(i), C, "phitmp",
2026                                 NonConstBB->getTerminator());
2027         else
2028           llvm_unreachable("Unknown binop!");
2029         
2030         AddToWorkList(cast<Instruction>(InV));
2031       }
2032       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2033     }
2034   } else { 
2035     CastInst *CI = cast<CastInst>(&I);
2036     const Type *RetTy = CI->getType();
2037     for (unsigned i = 0; i != NumPHIValues; ++i) {
2038       Value *InV;
2039       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2040         InV = Context->getConstantExprCast(CI->getOpcode(), InC, RetTy);
2041       } else {
2042         assert(PN->getIncomingBlock(i) == NonConstBB);
2043         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2044                                I.getType(), "phitmp", 
2045                                NonConstBB->getTerminator());
2046         AddToWorkList(cast<Instruction>(InV));
2047       }
2048       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2049     }
2050   }
2051   return ReplaceInstUsesWith(I, NewPN);
2052 }
2053
2054
2055 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2056 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2057 /// This basically requires proving that the add in the original type would not
2058 /// overflow to change the sign bit or have a carry out.
2059 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2060   // There are different heuristics we can use for this.  Here are some simple
2061   // ones.
2062   
2063   // Add has the property that adding any two 2's complement numbers can only 
2064   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2065   // have at least two sign bits, we know that the addition of the two values will
2066   // sign extend fine.
2067   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2068     return true;
2069   
2070   
2071   // If one of the operands only has one non-zero bit, and if the other operand
2072   // has a known-zero bit in a more significant place than it (not including the
2073   // sign bit) the ripple may go up to and fill the zero, but won't change the
2074   // sign.  For example, (X & ~4) + 1.
2075   
2076   // TODO: Implement.
2077   
2078   return false;
2079 }
2080
2081
2082 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2083   bool Changed = SimplifyCommutative(I);
2084   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2085
2086   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2087     // X + undef -> undef
2088     if (isa<UndefValue>(RHS))
2089       return ReplaceInstUsesWith(I, RHS);
2090
2091     // X + 0 --> X
2092     if (RHSC->isNullValue())
2093       return ReplaceInstUsesWith(I, LHS);
2094
2095     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2096       // X + (signbit) --> X ^ signbit
2097       const APInt& Val = CI->getValue();
2098       uint32_t BitWidth = Val.getBitWidth();
2099       if (Val == APInt::getSignBit(BitWidth))
2100         return BinaryOperator::CreateXor(LHS, RHS);
2101       
2102       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2103       // (X & 254)+1 -> (X&254)|1
2104       if (SimplifyDemandedInstructionBits(I))
2105         return &I;
2106
2107       // zext(bool) + C -> bool ? C + 1 : C
2108       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2109         if (ZI->getSrcTy() == Type::Int1Ty)
2110           return SelectInst::Create(ZI->getOperand(0), AddOne(CI, Context), CI);
2111     }
2112
2113     if (isa<PHINode>(LHS))
2114       if (Instruction *NV = FoldOpIntoPhi(I))
2115         return NV;
2116     
2117     ConstantInt *XorRHS = 0;
2118     Value *XorLHS = 0;
2119     if (isa<ConstantInt>(RHSC) &&
2120         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)), *Context)) {
2121       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2122       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2123       
2124       uint32_t Size = TySizeBits / 2;
2125       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2126       APInt CFF80Val(-C0080Val);
2127       do {
2128         if (TySizeBits > Size) {
2129           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2130           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2131           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2132               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2133             // This is a sign extend if the top bits are known zero.
2134             if (!MaskedValueIsZero(XorLHS, 
2135                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2136               Size = 0;  // Not a sign ext, but can't be any others either.
2137             break;
2138           }
2139         }
2140         Size >>= 1;
2141         C0080Val = APIntOps::lshr(C0080Val, Size);
2142         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2143       } while (Size >= 1);
2144       
2145       // FIXME: This shouldn't be necessary. When the backends can handle types
2146       // with funny bit widths then this switch statement should be removed. It
2147       // is just here to get the size of the "middle" type back up to something
2148       // that the back ends can handle.
2149       const Type *MiddleType = 0;
2150       switch (Size) {
2151         default: break;
2152         case 32: MiddleType = Type::Int32Ty; break;
2153         case 16: MiddleType = Type::Int16Ty; break;
2154         case  8: MiddleType = Type::Int8Ty; break;
2155       }
2156       if (MiddleType) {
2157         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2158         InsertNewInstBefore(NewTrunc, I);
2159         return new SExtInst(NewTrunc, I.getType(), I.getName());
2160       }
2161     }
2162   }
2163
2164   if (I.getType() == Type::Int1Ty)
2165     return BinaryOperator::CreateXor(LHS, RHS);
2166
2167   // X + X --> X << 1
2168   if (I.getType()->isInteger()) {
2169     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2170       return Result;
2171
2172     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2173       if (RHSI->getOpcode() == Instruction::Sub)
2174         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2175           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2176     }
2177     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2178       if (LHSI->getOpcode() == Instruction::Sub)
2179         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2180           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2181     }
2182   }
2183
2184   // -A + B  -->  B - A
2185   // -A + -B  -->  -(A + B)
2186   if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
2187     if (LHS->getType()->isIntOrIntVector()) {
2188       if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
2189         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2190         InsertNewInstBefore(NewAdd, I);
2191         return BinaryOperator::CreateNeg(*Context, NewAdd);
2192       }
2193     }
2194     
2195     return BinaryOperator::CreateSub(RHS, LHSV);
2196   }
2197
2198   // A + -B  -->  A - B
2199   if (!isa<Constant>(RHS))
2200     if (Value *V = dyn_castNegVal(RHS, Context))
2201       return BinaryOperator::CreateSub(LHS, V);
2202
2203
2204   ConstantInt *C2;
2205   if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
2206     if (X == RHS)   // X*C + X --> X * (C+1)
2207       return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
2208
2209     // X*C1 + X*C2 --> X * (C1+C2)
2210     ConstantInt *C1;
2211     if (X == dyn_castFoldableMul(RHS, C1, Context))
2212       return BinaryOperator::CreateMul(X, Context->getConstantExprAdd(C1, C2));
2213   }
2214
2215   // X + X*C --> X * (C+1)
2216   if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2217     return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
2218
2219   // X + ~X --> -1   since   ~X = -X-1
2220   if (dyn_castNotVal(LHS, Context) == RHS ||
2221       dyn_castNotVal(RHS, Context) == LHS)
2222     return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
2223   
2224
2225   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2226   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)), *Context))
2227     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
2228       return R;
2229   
2230   // A+B --> A|B iff A and B have no bits set in common.
2231   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2232     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2233     APInt LHSKnownOne(IT->getBitWidth(), 0);
2234     APInt LHSKnownZero(IT->getBitWidth(), 0);
2235     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2236     if (LHSKnownZero != 0) {
2237       APInt RHSKnownOne(IT->getBitWidth(), 0);
2238       APInt RHSKnownZero(IT->getBitWidth(), 0);
2239       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2240       
2241       // No bits in common -> bitwise or.
2242       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2243         return BinaryOperator::CreateOr(LHS, RHS);
2244     }
2245   }
2246
2247   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2248   if (I.getType()->isIntOrIntVector()) {
2249     Value *W, *X, *Y, *Z;
2250     if (match(LHS, m_Mul(m_Value(W), m_Value(X)), *Context) &&
2251         match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
2252       if (W != Y) {
2253         if (W == Z) {
2254           std::swap(Y, Z);
2255         } else if (Y == X) {
2256           std::swap(W, X);
2257         } else if (X == Z) {
2258           std::swap(Y, Z);
2259           std::swap(W, X);
2260         }
2261       }
2262
2263       if (W == Y) {
2264         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2265                                                             LHS->getName()), I);
2266         return BinaryOperator::CreateMul(W, NewAdd);
2267       }
2268     }
2269   }
2270
2271   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2272     Value *X = 0;
2273     if (match(LHS, m_Not(m_Value(X)), *Context))    // ~X + C --> (C-1) - X
2274       return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
2275
2276     // (X & FF00) + xx00  -> (X+xx00) & FF00
2277     if (LHS->hasOneUse() &&
2278         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
2279       Constant *Anded = Context->getConstantExprAnd(CRHS, C2);
2280       if (Anded == CRHS) {
2281         // See if all bits from the first bit set in the Add RHS up are included
2282         // in the mask.  First, get the rightmost bit.
2283         const APInt& AddRHSV = CRHS->getValue();
2284
2285         // Form a mask of all bits from the lowest bit added through the top.
2286         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2287
2288         // See if the and mask includes all of these bits.
2289         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2290
2291         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2292           // Okay, the xform is safe.  Insert the new add pronto.
2293           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2294                                                             LHS->getName()), I);
2295           return BinaryOperator::CreateAnd(NewAdd, C2);
2296         }
2297       }
2298     }
2299
2300     // Try to fold constant add into select arguments.
2301     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2302       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2303         return R;
2304   }
2305
2306   // add (cast *A to intptrtype) B -> 
2307   //   cast (GEP (cast *A to i8*) B)  -->  intptrtype
2308   {
2309     CastInst *CI = dyn_cast<CastInst>(LHS);
2310     Value *Other = RHS;
2311     if (!CI) {
2312       CI = dyn_cast<CastInst>(RHS);
2313       Other = LHS;
2314     }
2315     if (CI && CI->getType()->isSized() && 
2316         (CI->getType()->getScalarSizeInBits() ==
2317          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2318         && isa<PointerType>(CI->getOperand(0)->getType())) {
2319       unsigned AS =
2320         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2321       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2322                                   Context->getPointerType(Type::Int8Ty, AS), I);
2323       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2324       return new PtrToIntInst(I2, CI->getType());
2325     }
2326   }
2327   
2328   // add (select X 0 (sub n A)) A  -->  select X A n
2329   {
2330     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2331     Value *A = RHS;
2332     if (!SI) {
2333       SI = dyn_cast<SelectInst>(RHS);
2334       A = LHS;
2335     }
2336     if (SI && SI->hasOneUse()) {
2337       Value *TV = SI->getTrueValue();
2338       Value *FV = SI->getFalseValue();
2339       Value *N;
2340
2341       // Can we fold the add into the argument of the select?
2342       // We check both true and false select arguments for a matching subtract.
2343       if (match(FV, m_Zero(), *Context) &&
2344           match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2345         // Fold the add into the true select value.
2346         return SelectInst::Create(SI->getCondition(), N, A);
2347       if (match(TV, m_Zero(), *Context) &&
2348           match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2349         // Fold the add into the false select value.
2350         return SelectInst::Create(SI->getCondition(), A, N);
2351     }
2352   }
2353
2354   // Check for (add (sext x), y), see if we can merge this into an
2355   // integer add followed by a sext.
2356   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2357     // (add (sext x), cst) --> (sext (add x, cst'))
2358     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2359       Constant *CI = 
2360         Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
2361       if (LHSConv->hasOneUse() &&
2362           Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
2363           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2364         // Insert the new, smaller add.
2365         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2366                                                         CI, "addconv");
2367         InsertNewInstBefore(NewAdd, I);
2368         return new SExtInst(NewAdd, I.getType());
2369       }
2370     }
2371     
2372     // (add (sext x), (sext y)) --> (sext (add int x, y))
2373     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2374       // Only do this if x/y have the same type, if at last one of them has a
2375       // single use (so we don't increase the number of sexts), and if the
2376       // integer add will not overflow.
2377       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2378           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2379           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2380                                    RHSConv->getOperand(0))) {
2381         // Insert the new integer add.
2382         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2383                                                         RHSConv->getOperand(0),
2384                                                         "addconv");
2385         InsertNewInstBefore(NewAdd, I);
2386         return new SExtInst(NewAdd, I.getType());
2387       }
2388     }
2389   }
2390
2391   return Changed ? &I : 0;
2392 }
2393
2394 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2395   bool Changed = SimplifyCommutative(I);
2396   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2397
2398   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2399     // X + 0 --> X
2400     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2401       if (CFP->isExactlyValue(Context->getConstantFPNegativeZero
2402                               (I.getType())->getValueAPF()))
2403         return ReplaceInstUsesWith(I, LHS);
2404     }
2405
2406     if (isa<PHINode>(LHS))
2407       if (Instruction *NV = FoldOpIntoPhi(I))
2408         return NV;
2409   }
2410
2411   // -A + B  -->  B - A
2412   // -A + -B  -->  -(A + B)
2413   if (Value *LHSV = dyn_castFNegVal(LHS, Context))
2414     return BinaryOperator::CreateFSub(RHS, LHSV);
2415
2416   // A + -B  -->  A - B
2417   if (!isa<Constant>(RHS))
2418     if (Value *V = dyn_castFNegVal(RHS, Context))
2419       return BinaryOperator::CreateFSub(LHS, V);
2420
2421   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2422   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2423     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2424       return ReplaceInstUsesWith(I, LHS);
2425
2426   // Check for (add double (sitofp x), y), see if we can merge this into an
2427   // integer add followed by a promotion.
2428   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2429     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2430     // ... if the constant fits in the integer value.  This is useful for things
2431     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2432     // requires a constant pool load, and generally allows the add to be better
2433     // instcombined.
2434     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2435       Constant *CI = 
2436       Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
2437       if (LHSConv->hasOneUse() &&
2438           Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
2439           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2440         // Insert the new integer add.
2441         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2442                                                         CI, "addconv");
2443         InsertNewInstBefore(NewAdd, I);
2444         return new SIToFPInst(NewAdd, I.getType());
2445       }
2446     }
2447     
2448     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2449     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2450       // Only do this if x/y have the same type, if at last one of them has a
2451       // single use (so we don't increase the number of int->fp conversions),
2452       // and if the integer add will not overflow.
2453       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2454           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2455           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2456                                    RHSConv->getOperand(0))) {
2457         // Insert the new integer add.
2458         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2459                                                         RHSConv->getOperand(0),
2460                                                         "addconv");
2461         InsertNewInstBefore(NewAdd, I);
2462         return new SIToFPInst(NewAdd, I.getType());
2463       }
2464     }
2465   }
2466   
2467   return Changed ? &I : 0;
2468 }
2469
2470 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2471   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2472
2473   if (Op0 == Op1)                        // sub X, X  -> 0
2474     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2475
2476   // If this is a 'B = x-(-A)', change to B = x+A...
2477   if (Value *V = dyn_castNegVal(Op1, Context))
2478     return BinaryOperator::CreateAdd(Op0, V);
2479
2480   if (isa<UndefValue>(Op0))
2481     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2482   if (isa<UndefValue>(Op1))
2483     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2484
2485   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2486     // Replace (-1 - A) with (~A)...
2487     if (C->isAllOnesValue())
2488       return BinaryOperator::CreateNot(*Context, Op1);
2489
2490     // C - ~X == X + (1+C)
2491     Value *X = 0;
2492     if (match(Op1, m_Not(m_Value(X)), *Context))
2493       return BinaryOperator::CreateAdd(X, AddOne(C, Context));
2494
2495     // -(X >>u 31) -> (X >>s 31)
2496     // -(X >>s 31) -> (X >>u 31)
2497     if (C->isZero()) {
2498       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2499         if (SI->getOpcode() == Instruction::LShr) {
2500           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2501             // Check to see if we are shifting out everything but the sign bit.
2502             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2503                 SI->getType()->getPrimitiveSizeInBits()-1) {
2504               // Ok, the transformation is safe.  Insert AShr.
2505               return BinaryOperator::Create(Instruction::AShr, 
2506                                           SI->getOperand(0), CU, SI->getName());
2507             }
2508           }
2509         }
2510         else if (SI->getOpcode() == Instruction::AShr) {
2511           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2512             // Check to see if we are shifting out everything but the sign bit.
2513             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2514                 SI->getType()->getPrimitiveSizeInBits()-1) {
2515               // Ok, the transformation is safe.  Insert LShr. 
2516               return BinaryOperator::CreateLShr(
2517                                           SI->getOperand(0), CU, SI->getName());
2518             }
2519           }
2520         }
2521       }
2522     }
2523
2524     // Try to fold constant sub into select arguments.
2525     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2526       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2527         return R;
2528
2529     // C - zext(bool) -> bool ? C - 1 : C
2530     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2531       if (ZI->getSrcTy() == Type::Int1Ty)
2532         return SelectInst::Create(ZI->getOperand(0), SubOne(C, Context), C);
2533   }
2534
2535   if (I.getType() == Type::Int1Ty)
2536     return BinaryOperator::CreateXor(Op0, Op1);
2537
2538   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2539     if (Op1I->getOpcode() == Instruction::Add) {
2540       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2541         return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(1),
2542                                          I.getName());
2543       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2544         return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(0), 
2545                                          I.getName());
2546       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2547         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2548           // C1-(X+C2) --> (C1-C2)-X
2549           return BinaryOperator::CreateSub(
2550             Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
2551       }
2552     }
2553
2554     if (Op1I->hasOneUse()) {
2555       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2556       // is not used by anyone else...
2557       //
2558       if (Op1I->getOpcode() == Instruction::Sub) {
2559         // Swap the two operands of the subexpr...
2560         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2561         Op1I->setOperand(0, IIOp1);
2562         Op1I->setOperand(1, IIOp0);
2563
2564         // Create the new top level add instruction...
2565         return BinaryOperator::CreateAdd(Op0, Op1);
2566       }
2567
2568       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2569       //
2570       if (Op1I->getOpcode() == Instruction::And &&
2571           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2572         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2573
2574         Value *NewNot =
2575           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, 
2576                                                         OtherOp, "B.not"), I);
2577         return BinaryOperator::CreateAnd(Op0, NewNot);
2578       }
2579
2580       // 0 - (X sdiv C)  -> (X sdiv -C)
2581       if (Op1I->getOpcode() == Instruction::SDiv)
2582         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2583           if (CSI->isZero())
2584             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2585               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2586                                           Context->getConstantExprNeg(DivRHS));
2587
2588       // X - X*C --> X * (1-C)
2589       ConstantInt *C2 = 0;
2590       if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2591         Constant *CP1 = 
2592           Context->getConstantExprSub(Context->getConstantInt(I.getType(), 1),
2593                                              C2);
2594         return BinaryOperator::CreateMul(Op0, CP1);
2595       }
2596     }
2597   }
2598
2599   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2600     if (Op0I->getOpcode() == Instruction::Add) {
2601       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2602         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2603       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2604         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2605     } else if (Op0I->getOpcode() == Instruction::Sub) {
2606       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2607         return BinaryOperator::CreateNeg(*Context, Op0I->getOperand(1),
2608                                          I.getName());
2609     }
2610   }
2611
2612   ConstantInt *C1;
2613   if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
2614     if (X == Op1)  // X*C - X --> X * (C-1)
2615       return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
2616
2617     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2618     if (X == dyn_castFoldableMul(Op1, C2, Context))
2619       return BinaryOperator::CreateMul(X, Context->getConstantExprSub(C1, C2));
2620   }
2621   return 0;
2622 }
2623
2624 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2625   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2626
2627   // If this is a 'B = x-(-A)', change to B = x+A...
2628   if (Value *V = dyn_castFNegVal(Op1, Context))
2629     return BinaryOperator::CreateFAdd(Op0, V);
2630
2631   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2632     if (Op1I->getOpcode() == Instruction::FAdd) {
2633       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2634         return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(1),
2635                                           I.getName());
2636       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2637         return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(0),
2638                                           I.getName());
2639     }
2640   }
2641
2642   return 0;
2643 }
2644
2645 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2646 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2647 /// TrueIfSigned if the result of the comparison is true when the input value is
2648 /// signed.
2649 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2650                            bool &TrueIfSigned) {
2651   switch (pred) {
2652   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2653     TrueIfSigned = true;
2654     return RHS->isZero();
2655   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2656     TrueIfSigned = true;
2657     return RHS->isAllOnesValue();
2658   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2659     TrueIfSigned = false;
2660     return RHS->isAllOnesValue();
2661   case ICmpInst::ICMP_UGT:
2662     // True if LHS u> RHS and RHS == high-bit-mask - 1
2663     TrueIfSigned = true;
2664     return RHS->getValue() ==
2665       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2666   case ICmpInst::ICMP_UGE: 
2667     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2668     TrueIfSigned = true;
2669     return RHS->getValue().isSignBit();
2670   default:
2671     return false;
2672   }
2673 }
2674
2675 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2676   bool Changed = SimplifyCommutative(I);
2677   Value *Op0 = I.getOperand(0);
2678
2679   // TODO: If Op1 is undef and Op0 is finite, return zero.
2680   if (!I.getType()->isFPOrFPVector() &&
2681       isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2682     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2683
2684   // Simplify mul instructions with a constant RHS...
2685   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2686     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2687
2688       // ((X << C1)*C2) == (X * (C2 << C1))
2689       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2690         if (SI->getOpcode() == Instruction::Shl)
2691           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2692             return BinaryOperator::CreateMul(SI->getOperand(0),
2693                                         Context->getConstantExprShl(CI, ShOp));
2694
2695       if (CI->isZero())
2696         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2697       if (CI->equalsInt(1))                  // X * 1  == X
2698         return ReplaceInstUsesWith(I, Op0);
2699       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2700         return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2701
2702       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2703       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2704         return BinaryOperator::CreateShl(Op0,
2705                  Context->getConstantInt(Op0->getType(), Val.logBase2()));
2706       }
2707     } else if (isa<VectorType>(Op1->getType())) {
2708       if (Op1->isNullValue())
2709         return ReplaceInstUsesWith(I, Op1);
2710
2711       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2712         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2713           return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2714
2715         // As above, vector X*splat(1.0) -> X in all defined cases.
2716         if (Constant *Splat = Op1V->getSplatValue()) {
2717           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2718             if (CI->equalsInt(1))
2719               return ReplaceInstUsesWith(I, Op0);
2720         }
2721       }
2722     }
2723     
2724     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2725       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2726           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2727         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2728         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2729                                                      Op1, "tmp");
2730         InsertNewInstBefore(Add, I);
2731         Value *C1C2 = Context->getConstantExprMul(Op1, 
2732                                            cast<Constant>(Op0I->getOperand(1)));
2733         return BinaryOperator::CreateAdd(Add, C1C2);
2734         
2735       }
2736
2737     // Try to fold constant mul into select arguments.
2738     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2739       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2740         return R;
2741
2742     if (isa<PHINode>(Op0))
2743       if (Instruction *NV = FoldOpIntoPhi(I))
2744         return NV;
2745   }
2746
2747   if (Value *Op0v = dyn_castNegVal(Op0, Context))     // -X * -Y = X*Y
2748     if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
2749       return BinaryOperator::CreateMul(Op0v, Op1v);
2750
2751   // (X / Y) *  Y = X - (X % Y)
2752   // (X / Y) * -Y = (X % Y) - X
2753   {
2754     Value *Op1 = I.getOperand(1);
2755     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2756     if (!BO ||
2757         (BO->getOpcode() != Instruction::UDiv && 
2758          BO->getOpcode() != Instruction::SDiv)) {
2759       Op1 = Op0;
2760       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2761     }
2762     Value *Neg = dyn_castNegVal(Op1, Context);
2763     if (BO && BO->hasOneUse() &&
2764         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2765         (BO->getOpcode() == Instruction::UDiv ||
2766          BO->getOpcode() == Instruction::SDiv)) {
2767       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2768
2769       Instruction *Rem;
2770       if (BO->getOpcode() == Instruction::UDiv)
2771         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2772       else
2773         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2774
2775       InsertNewInstBefore(Rem, I);
2776       Rem->takeName(BO);
2777
2778       if (Op1BO == Op1)
2779         return BinaryOperator::CreateSub(Op0BO, Rem);
2780       else
2781         return BinaryOperator::CreateSub(Rem, Op0BO);
2782     }
2783   }
2784
2785   if (I.getType() == Type::Int1Ty)
2786     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2787
2788   // If one of the operands of the multiply is a cast from a boolean value, then
2789   // we know the bool is either zero or one, so this is a 'masking' multiply.
2790   // See if we can simplify things based on how the boolean was originally
2791   // formed.
2792   CastInst *BoolCast = 0;
2793   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2794     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2795       BoolCast = CI;
2796   if (!BoolCast)
2797     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2798       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2799         BoolCast = CI;
2800   if (BoolCast) {
2801     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2802       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2803       const Type *SCOpTy = SCIOp0->getType();
2804       bool TIS = false;
2805       
2806       // If the icmp is true iff the sign bit of X is set, then convert this
2807       // multiply into a shift/and combination.
2808       if (isa<ConstantInt>(SCIOp1) &&
2809           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2810           TIS) {
2811         // Shift the X value right to turn it into "all signbits".
2812         Constant *Amt = Context->getConstantInt(SCIOp0->getType(),
2813                                           SCOpTy->getPrimitiveSizeInBits()-1);
2814         Value *V =
2815           InsertNewInstBefore(
2816             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2817                                             BoolCast->getOperand(0)->getName()+
2818                                             ".mask"), I);
2819
2820         // If the multiply type is not the same as the source type, sign extend
2821         // or truncate to the multiply type.
2822         if (I.getType() != V->getType()) {
2823           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2824           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2825           Instruction::CastOps opcode = 
2826             (SrcBits == DstBits ? Instruction::BitCast : 
2827              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2828           V = InsertCastBefore(opcode, V, I.getType(), I);
2829         }
2830
2831         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2832         return BinaryOperator::CreateAnd(V, OtherOp);
2833       }
2834     }
2835   }
2836
2837   return Changed ? &I : 0;
2838 }
2839
2840 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2841   bool Changed = SimplifyCommutative(I);
2842   Value *Op0 = I.getOperand(0);
2843
2844   // Simplify mul instructions with a constant RHS...
2845   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2846     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2847       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2848       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2849       if (Op1F->isExactlyValue(1.0))
2850         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2851     } else if (isa<VectorType>(Op1->getType())) {
2852       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2853         // As above, vector X*splat(1.0) -> X in all defined cases.
2854         if (Constant *Splat = Op1V->getSplatValue()) {
2855           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2856             if (F->isExactlyValue(1.0))
2857               return ReplaceInstUsesWith(I, Op0);
2858         }
2859       }
2860     }
2861
2862     // Try to fold constant mul into select arguments.
2863     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2864       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2865         return R;
2866
2867     if (isa<PHINode>(Op0))
2868       if (Instruction *NV = FoldOpIntoPhi(I))
2869         return NV;
2870   }
2871
2872   if (Value *Op0v = dyn_castFNegVal(Op0, Context))     // -X * -Y = X*Y
2873     if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
2874       return BinaryOperator::CreateFMul(Op0v, Op1v);
2875
2876   return Changed ? &I : 0;
2877 }
2878
2879 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2880 /// instruction.
2881 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2882   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2883   
2884   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2885   int NonNullOperand = -1;
2886   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2887     if (ST->isNullValue())
2888       NonNullOperand = 2;
2889   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2890   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2891     if (ST->isNullValue())
2892       NonNullOperand = 1;
2893   
2894   if (NonNullOperand == -1)
2895     return false;
2896   
2897   Value *SelectCond = SI->getOperand(0);
2898   
2899   // Change the div/rem to use 'Y' instead of the select.
2900   I.setOperand(1, SI->getOperand(NonNullOperand));
2901   
2902   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2903   // problem.  However, the select, or the condition of the select may have
2904   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2905   // propagate the known value for the select into other uses of it, and
2906   // propagate a known value of the condition into its other users.
2907   
2908   // If the select and condition only have a single use, don't bother with this,
2909   // early exit.
2910   if (SI->use_empty() && SelectCond->hasOneUse())
2911     return true;
2912   
2913   // Scan the current block backward, looking for other uses of SI.
2914   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2915   
2916   while (BBI != BBFront) {
2917     --BBI;
2918     // If we found a call to a function, we can't assume it will return, so
2919     // information from below it cannot be propagated above it.
2920     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2921       break;
2922     
2923     // Replace uses of the select or its condition with the known values.
2924     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2925          I != E; ++I) {
2926       if (*I == SI) {
2927         *I = SI->getOperand(NonNullOperand);
2928         AddToWorkList(BBI);
2929       } else if (*I == SelectCond) {
2930         *I = NonNullOperand == 1 ? Context->getConstantIntTrue() :
2931                                    Context->getConstantIntFalse();
2932         AddToWorkList(BBI);
2933       }
2934     }
2935     
2936     // If we past the instruction, quit looking for it.
2937     if (&*BBI == SI)
2938       SI = 0;
2939     if (&*BBI == SelectCond)
2940       SelectCond = 0;
2941     
2942     // If we ran out of things to eliminate, break out of the loop.
2943     if (SelectCond == 0 && SI == 0)
2944       break;
2945     
2946   }
2947   return true;
2948 }
2949
2950
2951 /// This function implements the transforms on div instructions that work
2952 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2953 /// used by the visitors to those instructions.
2954 /// @brief Transforms common to all three div instructions
2955 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2956   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2957
2958   // undef / X -> 0        for integer.
2959   // undef / X -> undef    for FP (the undef could be a snan).
2960   if (isa<UndefValue>(Op0)) {
2961     if (Op0->getType()->isFPOrFPVector())
2962       return ReplaceInstUsesWith(I, Op0);
2963     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2964   }
2965
2966   // X / undef -> undef
2967   if (isa<UndefValue>(Op1))
2968     return ReplaceInstUsesWith(I, Op1);
2969
2970   return 0;
2971 }
2972
2973 /// This function implements the transforms common to both integer division
2974 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2975 /// division instructions.
2976 /// @brief Common integer divide transforms
2977 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2978   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2979
2980   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2981   if (Op0 == Op1) {
2982     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2983       Constant *CI = Context->getConstantInt(Ty->getElementType(), 1);
2984       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2985       return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
2986     }
2987
2988     Constant *CI = Context->getConstantInt(I.getType(), 1);
2989     return ReplaceInstUsesWith(I, CI);
2990   }
2991   
2992   if (Instruction *Common = commonDivTransforms(I))
2993     return Common;
2994   
2995   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2996   // This does not apply for fdiv.
2997   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2998     return &I;
2999
3000   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3001     // div X, 1 == X
3002     if (RHS->equalsInt(1))
3003       return ReplaceInstUsesWith(I, Op0);
3004
3005     // (X / C1) / C2  -> X / (C1*C2)
3006     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3007       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3008         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3009           if (MultiplyOverflows(RHS, LHSRHS,
3010                                 I.getOpcode()==Instruction::SDiv, Context))
3011             return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3012           else 
3013             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
3014                                       Context->getConstantExprMul(RHS, LHSRHS));
3015         }
3016
3017     if (!RHS->isZero()) { // avoid X udiv 0
3018       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3019         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3020           return R;
3021       if (isa<PHINode>(Op0))
3022         if (Instruction *NV = FoldOpIntoPhi(I))
3023           return NV;
3024     }
3025   }
3026
3027   // 0 / X == 0, we don't need to preserve faults!
3028   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3029     if (LHS->equalsInt(0))
3030       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3031
3032   // It can't be division by zero, hence it must be division by one.
3033   if (I.getType() == Type::Int1Ty)
3034     return ReplaceInstUsesWith(I, Op0);
3035
3036   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3037     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3038       // div X, 1 == X
3039       if (X->isOne())
3040         return ReplaceInstUsesWith(I, Op0);
3041   }
3042
3043   return 0;
3044 }
3045
3046 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3047   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3048
3049   // Handle the integer div common cases
3050   if (Instruction *Common = commonIDivTransforms(I))
3051     return Common;
3052
3053   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3054     // X udiv C^2 -> X >> C
3055     // Check to see if this is an unsigned division with an exact power of 2,
3056     // if so, convert to a right shift.
3057     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3058       return BinaryOperator::CreateLShr(Op0, 
3059             Context->getConstantInt(Op0->getType(), C->getValue().logBase2()));
3060
3061     // X udiv C, where C >= signbit
3062     if (C->getValue().isNegative()) {
3063       Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3064                                                     ICmpInst::ICMP_ULT, Op0, C),
3065                                       I);
3066       return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3067                                 Context->getConstantInt(I.getType(), 1));
3068     }
3069   }
3070
3071   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3072   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3073     if (RHSI->getOpcode() == Instruction::Shl &&
3074         isa<ConstantInt>(RHSI->getOperand(0))) {
3075       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3076       if (C1.isPowerOf2()) {
3077         Value *N = RHSI->getOperand(1);
3078         const Type *NTy = N->getType();
3079         if (uint32_t C2 = C1.logBase2()) {
3080           Constant *C2V = Context->getConstantInt(NTy, C2);
3081           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3082         }
3083         return BinaryOperator::CreateLShr(Op0, N);
3084       }
3085     }
3086   }
3087   
3088   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3089   // where C1&C2 are powers of two.
3090   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3091     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3092       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3093         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3094         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3095           // Compute the shift amounts
3096           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3097           // Construct the "on true" case of the select
3098           Constant *TC = Context->getConstantInt(Op0->getType(), TSA);
3099           Instruction *TSI = BinaryOperator::CreateLShr(
3100                                                  Op0, TC, SI->getName()+".t");
3101           TSI = InsertNewInstBefore(TSI, I);
3102   
3103           // Construct the "on false" case of the select
3104           Constant *FC = Context->getConstantInt(Op0->getType(), FSA); 
3105           Instruction *FSI = BinaryOperator::CreateLShr(
3106                                                  Op0, FC, SI->getName()+".f");
3107           FSI = InsertNewInstBefore(FSI, I);
3108
3109           // construct the select instruction and return it.
3110           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3111         }
3112       }
3113   return 0;
3114 }
3115
3116 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3117   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3118
3119   // Handle the integer div common cases
3120   if (Instruction *Common = commonIDivTransforms(I))
3121     return Common;
3122
3123   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3124     // sdiv X, -1 == -X
3125     if (RHS->isAllOnesValue())
3126       return BinaryOperator::CreateNeg(*Context, Op0);
3127   }
3128
3129   // If the sign bits of both operands are zero (i.e. we can prove they are
3130   // unsigned inputs), turn this into a udiv.
3131   if (I.getType()->isInteger()) {
3132     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3133     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3134       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3135       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3136     }
3137   }      
3138   
3139   return 0;
3140 }
3141
3142 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3143   return commonDivTransforms(I);
3144 }
3145
3146 /// This function implements the transforms on rem instructions that work
3147 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3148 /// is used by the visitors to those instructions.
3149 /// @brief Transforms common to all three rem instructions
3150 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3151   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3152
3153   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3154     if (I.getType()->isFPOrFPVector())
3155       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3156     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3157   }
3158   if (isa<UndefValue>(Op1))
3159     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3160
3161   // Handle cases involving: rem X, (select Cond, Y, Z)
3162   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3163     return &I;
3164
3165   return 0;
3166 }
3167
3168 /// This function implements the transforms common to both integer remainder
3169 /// instructions (urem and srem). It is called by the visitors to those integer
3170 /// remainder instructions.
3171 /// @brief Common integer remainder transforms
3172 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3173   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3174
3175   if (Instruction *common = commonRemTransforms(I))
3176     return common;
3177
3178   // 0 % X == 0 for integer, we don't need to preserve faults!
3179   if (Constant *LHS = dyn_cast<Constant>(Op0))
3180     if (LHS->isNullValue())
3181       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3182
3183   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3184     // X % 0 == undef, we don't need to preserve faults!
3185     if (RHS->equalsInt(0))
3186       return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
3187     
3188     if (RHS->equalsInt(1))  // X % 1 == 0
3189       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3190
3191     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3192       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3193         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3194           return R;
3195       } else if (isa<PHINode>(Op0I)) {
3196         if (Instruction *NV = FoldOpIntoPhi(I))
3197           return NV;
3198       }
3199
3200       // See if we can fold away this rem instruction.
3201       if (SimplifyDemandedInstructionBits(I))
3202         return &I;
3203     }
3204   }
3205
3206   return 0;
3207 }
3208
3209 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3210   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3211
3212   if (Instruction *common = commonIRemTransforms(I))
3213     return common;
3214   
3215   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3216     // X urem C^2 -> X and C
3217     // Check to see if this is an unsigned remainder with an exact power of 2,
3218     // if so, convert to a bitwise and.
3219     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3220       if (C->getValue().isPowerOf2())
3221         return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
3222   }
3223
3224   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3225     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3226     if (RHSI->getOpcode() == Instruction::Shl &&
3227         isa<ConstantInt>(RHSI->getOperand(0))) {
3228       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3229         Constant *N1 = Context->getAllOnesValue(I.getType());
3230         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3231                                                                    "tmp"), I);
3232         return BinaryOperator::CreateAnd(Op0, Add);
3233       }
3234     }
3235   }
3236
3237   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3238   // where C1&C2 are powers of two.
3239   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3240     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3241       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3242         // STO == 0 and SFO == 0 handled above.
3243         if ((STO->getValue().isPowerOf2()) && 
3244             (SFO->getValue().isPowerOf2())) {
3245           Value *TrueAnd = InsertNewInstBefore(
3246             BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3247                                       SI->getName()+".t"), I);
3248           Value *FalseAnd = InsertNewInstBefore(
3249             BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3250                                       SI->getName()+".f"), I);
3251           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3252         }
3253       }
3254   }
3255   
3256   return 0;
3257 }
3258
3259 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3260   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3261
3262   // Handle the integer rem common cases
3263   if (Instruction *common = commonIRemTransforms(I))
3264     return common;
3265   
3266   if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
3267     if (!isa<Constant>(RHSNeg) ||
3268         (isa<ConstantInt>(RHSNeg) &&
3269          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3270       // X % -Y -> X % Y
3271       AddUsesToWorkList(I);
3272       I.setOperand(1, RHSNeg);
3273       return &I;
3274     }
3275
3276   // If the sign bits of both operands are zero (i.e. we can prove they are
3277   // unsigned inputs), turn this into a urem.
3278   if (I.getType()->isInteger()) {
3279     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3280     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3281       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3282       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3283     }
3284   }
3285
3286   // If it's a constant vector, flip any negative values positive.
3287   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3288     unsigned VWidth = RHSV->getNumOperands();
3289
3290     bool hasNegative = false;
3291     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3292       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3293         if (RHS->getValue().isNegative())
3294           hasNegative = true;
3295
3296     if (hasNegative) {
3297       std::vector<Constant *> Elts(VWidth);
3298       for (unsigned i = 0; i != VWidth; ++i) {
3299         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3300           if (RHS->getValue().isNegative())
3301             Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
3302           else
3303             Elts[i] = RHS;
3304         }
3305       }
3306
3307       Constant *NewRHSV = Context->getConstantVector(Elts);
3308       if (NewRHSV != RHSV) {
3309         AddUsesToWorkList(I);
3310         I.setOperand(1, NewRHSV);
3311         return &I;
3312       }
3313     }
3314   }
3315
3316   return 0;
3317 }
3318
3319 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3320   return commonRemTransforms(I);
3321 }
3322
3323 // isOneBitSet - Return true if there is exactly one bit set in the specified
3324 // constant.
3325 static bool isOneBitSet(const ConstantInt *CI) {
3326   return CI->getValue().isPowerOf2();
3327 }
3328
3329 // isHighOnes - Return true if the constant is of the form 1+0+.
3330 // This is the same as lowones(~X).
3331 static bool isHighOnes(const ConstantInt *CI) {
3332   return (~CI->getValue() + 1).isPowerOf2();
3333 }
3334
3335 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3336 /// are carefully arranged to allow folding of expressions such as:
3337 ///
3338 ///      (A < B) | (A > B) --> (A != B)
3339 ///
3340 /// Note that this is only valid if the first and second predicates have the
3341 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3342 ///
3343 /// Three bits are used to represent the condition, as follows:
3344 ///   0  A > B
3345 ///   1  A == B
3346 ///   2  A < B
3347 ///
3348 /// <=>  Value  Definition
3349 /// 000     0   Always false
3350 /// 001     1   A >  B
3351 /// 010     2   A == B
3352 /// 011     3   A >= B
3353 /// 100     4   A <  B
3354 /// 101     5   A != B
3355 /// 110     6   A <= B
3356 /// 111     7   Always true
3357 ///  
3358 static unsigned getICmpCode(const ICmpInst *ICI) {
3359   switch (ICI->getPredicate()) {
3360     // False -> 0
3361   case ICmpInst::ICMP_UGT: return 1;  // 001
3362   case ICmpInst::ICMP_SGT: return 1;  // 001
3363   case ICmpInst::ICMP_EQ:  return 2;  // 010
3364   case ICmpInst::ICMP_UGE: return 3;  // 011
3365   case ICmpInst::ICMP_SGE: return 3;  // 011
3366   case ICmpInst::ICMP_ULT: return 4;  // 100
3367   case ICmpInst::ICMP_SLT: return 4;  // 100
3368   case ICmpInst::ICMP_NE:  return 5;  // 101
3369   case ICmpInst::ICMP_ULE: return 6;  // 110
3370   case ICmpInst::ICMP_SLE: return 6;  // 110
3371     // True -> 7
3372   default:
3373     llvm_unreachable("Invalid ICmp predicate!");
3374     return 0;
3375   }
3376 }
3377
3378 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3379 /// predicate into a three bit mask. It also returns whether it is an ordered
3380 /// predicate by reference.
3381 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3382   isOrdered = false;
3383   switch (CC) {
3384   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3385   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3386   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3387   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3388   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3389   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3390   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3391   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3392   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3393   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3394   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3395   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3396   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3397   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3398     // True -> 7
3399   default:
3400     // Not expecting FCMP_FALSE and FCMP_TRUE;
3401     llvm_unreachable("Unexpected FCmp predicate!");
3402     return 0;
3403   }
3404 }
3405
3406 /// getICmpValue - This is the complement of getICmpCode, which turns an
3407 /// opcode and two operands into either a constant true or false, or a brand 
3408 /// new ICmp instruction. The sign is passed in to determine which kind
3409 /// of predicate to use in the new icmp instruction.
3410 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3411                            LLVMContext *Context) {
3412   switch (code) {
3413   default: llvm_unreachable("Illegal ICmp code!");
3414   case  0: return Context->getConstantIntFalse();
3415   case  1: 
3416     if (sign)
3417       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
3418     else
3419       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3420   case  2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ,  LHS, RHS);
3421   case  3: 
3422     if (sign)
3423       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
3424     else
3425       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
3426   case  4: 
3427     if (sign)
3428       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
3429     else
3430       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3431   case  5: return new ICmpInst(*Context, ICmpInst::ICMP_NE,  LHS, RHS);
3432   case  6: 
3433     if (sign)
3434       return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
3435     else
3436       return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
3437   case  7: return Context->getConstantIntTrue();
3438   }
3439 }
3440
3441 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3442 /// opcode and two operands into either a FCmp instruction. isordered is passed
3443 /// in to determine which kind of predicate to use in the new fcmp instruction.
3444 static Value *getFCmpValue(bool isordered, unsigned code,
3445                            Value *LHS, Value *RHS, LLVMContext *Context) {
3446   switch (code) {
3447   default: llvm_unreachable("Illegal FCmp code!");
3448   case  0:
3449     if (isordered)
3450       return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
3451     else
3452       return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
3453   case  1: 
3454     if (isordered)
3455       return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
3456     else
3457       return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
3458   case  2: 
3459     if (isordered)
3460       return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
3461     else
3462       return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
3463   case  3: 
3464     if (isordered)
3465       return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
3466     else
3467       return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
3468   case  4: 
3469     if (isordered)
3470       return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
3471     else
3472       return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
3473   case  5: 
3474     if (isordered)
3475       return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
3476     else
3477       return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
3478   case  6: 
3479     if (isordered)
3480       return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
3481     else
3482       return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
3483   case  7: return Context->getConstantIntTrue();
3484   }
3485 }
3486
3487 /// PredicatesFoldable - Return true if both predicates match sign or if at
3488 /// least one of them is an equality comparison (which is signless).
3489 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3490   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3491          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3492          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3493 }
3494
3495 namespace { 
3496 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3497 struct FoldICmpLogical {
3498   InstCombiner &IC;
3499   Value *LHS, *RHS;
3500   ICmpInst::Predicate pred;
3501   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3502     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3503       pred(ICI->getPredicate()) {}
3504   bool shouldApply(Value *V) const {
3505     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3506       if (PredicatesFoldable(pred, ICI->getPredicate()))
3507         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3508                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3509     return false;
3510   }
3511   Instruction *apply(Instruction &Log) const {
3512     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3513     if (ICI->getOperand(0) != LHS) {
3514       assert(ICI->getOperand(1) == LHS);
3515       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3516     }
3517
3518     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3519     unsigned LHSCode = getICmpCode(ICI);
3520     unsigned RHSCode = getICmpCode(RHSICI);
3521     unsigned Code;
3522     switch (Log.getOpcode()) {
3523     case Instruction::And: Code = LHSCode & RHSCode; break;
3524     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3525     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3526     default: llvm_unreachable("Illegal logical opcode!"); return 0;
3527     }
3528
3529     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3530                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3531       
3532     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3533     if (Instruction *I = dyn_cast<Instruction>(RV))
3534       return I;
3535     // Otherwise, it's a constant boolean value...
3536     return IC.ReplaceInstUsesWith(Log, RV);
3537   }
3538 };
3539 } // end anonymous namespace
3540
3541 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3542 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3543 // guaranteed to be a binary operator.
3544 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3545                                     ConstantInt *OpRHS,
3546                                     ConstantInt *AndRHS,
3547                                     BinaryOperator &TheAnd) {
3548   Value *X = Op->getOperand(0);
3549   Constant *Together = 0;
3550   if (!Op->isShift())
3551     Together = Context->getConstantExprAnd(AndRHS, OpRHS);
3552
3553   switch (Op->getOpcode()) {
3554   case Instruction::Xor:
3555     if (Op->hasOneUse()) {
3556       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3557       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3558       InsertNewInstBefore(And, TheAnd);
3559       And->takeName(Op);
3560       return BinaryOperator::CreateXor(And, Together);
3561     }
3562     break;
3563   case Instruction::Or:
3564     if (Together == AndRHS) // (X | C) & C --> C
3565       return ReplaceInstUsesWith(TheAnd, AndRHS);
3566
3567     if (Op->hasOneUse() && Together != OpRHS) {
3568       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3569       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3570       InsertNewInstBefore(Or, TheAnd);
3571       Or->takeName(Op);
3572       return BinaryOperator::CreateAnd(Or, AndRHS);
3573     }
3574     break;
3575   case Instruction::Add:
3576     if (Op->hasOneUse()) {
3577       // Adding a one to a single bit bit-field should be turned into an XOR
3578       // of the bit.  First thing to check is to see if this AND is with a
3579       // single bit constant.
3580       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3581
3582       // If there is only one bit set...
3583       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3584         // Ok, at this point, we know that we are masking the result of the
3585         // ADD down to exactly one bit.  If the constant we are adding has
3586         // no bits set below this bit, then we can eliminate the ADD.
3587         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3588
3589         // Check to see if any bits below the one bit set in AndRHSV are set.
3590         if ((AddRHS & (AndRHSV-1)) == 0) {
3591           // If not, the only thing that can effect the output of the AND is
3592           // the bit specified by AndRHSV.  If that bit is set, the effect of
3593           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3594           // no effect.
3595           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3596             TheAnd.setOperand(0, X);
3597             return &TheAnd;
3598           } else {
3599             // Pull the XOR out of the AND.
3600             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3601             InsertNewInstBefore(NewAnd, TheAnd);
3602             NewAnd->takeName(Op);
3603             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3604           }
3605         }
3606       }
3607     }
3608     break;
3609
3610   case Instruction::Shl: {
3611     // We know that the AND will not produce any of the bits shifted in, so if
3612     // the anded constant includes them, clear them now!
3613     //
3614     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3615     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3616     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3617     ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShlMask);
3618
3619     if (CI->getValue() == ShlMask) { 
3620     // Masking out bits that the shift already masks
3621       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3622     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3623       TheAnd.setOperand(1, CI);
3624       return &TheAnd;
3625     }
3626     break;
3627   }
3628   case Instruction::LShr:
3629   {
3630     // We know that the AND will not produce any of the bits shifted in, so if
3631     // the anded constant includes them, clear them now!  This only applies to
3632     // unsigned shifts, because a signed shr may bring in set bits!
3633     //
3634     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3635     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3636     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3637     ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3638
3639     if (CI->getValue() == ShrMask) {   
3640     // Masking out bits that the shift already masks.
3641       return ReplaceInstUsesWith(TheAnd, Op);
3642     } else if (CI != AndRHS) {
3643       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3644       return &TheAnd;
3645     }
3646     break;
3647   }
3648   case Instruction::AShr:
3649     // Signed shr.
3650     // See if this is shifting in some sign extension, then masking it out
3651     // with an and.
3652     if (Op->hasOneUse()) {
3653       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3654       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3655       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3656       Constant *C = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3657       if (C == AndRHS) {          // Masking out bits shifted in.
3658         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3659         // Make the argument unsigned.
3660         Value *ShVal = Op->getOperand(0);
3661         ShVal = InsertNewInstBefore(
3662             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3663                                    Op->getName()), TheAnd);
3664         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3665       }
3666     }
3667     break;
3668   }
3669   return 0;
3670 }
3671
3672
3673 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3674 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3675 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3676 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3677 /// insert new instructions.
3678 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3679                                            bool isSigned, bool Inside, 
3680                                            Instruction &IB) {
3681   assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ? 
3682             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3683          "Lo is not <= Hi in range emission code!");
3684     
3685   if (Inside) {
3686     if (Lo == Hi)  // Trivially false.
3687       return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
3688
3689     // V >= Min && V < Hi --> V < Hi
3690     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3691       ICmpInst::Predicate pred = (isSigned ? 
3692         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3693       return new ICmpInst(*Context, pred, V, Hi);
3694     }
3695
3696     // Emit V-Lo <u Hi-Lo
3697     Constant *NegLo = Context->getConstantExprNeg(Lo);
3698     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3699     InsertNewInstBefore(Add, IB);
3700     Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
3701     return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
3702   }
3703
3704   if (Lo == Hi)  // Trivially true.
3705     return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
3706
3707   // V < Min || V >= Hi -> V > Hi-1
3708   Hi = SubOne(cast<ConstantInt>(Hi), Context);
3709   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3710     ICmpInst::Predicate pred = (isSigned ? 
3711         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3712     return new ICmpInst(*Context, pred, V, Hi);
3713   }
3714
3715   // Emit V-Lo >u Hi-1-Lo
3716   // Note that Hi has already had one subtracted from it, above.
3717   ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
3718   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3719   InsertNewInstBefore(Add, IB);
3720   Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
3721   return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
3722 }
3723
3724 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3725 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3726 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3727 // not, since all 1s are not contiguous.
3728 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3729   const APInt& V = Val->getValue();
3730   uint32_t BitWidth = Val->getType()->getBitWidth();
3731   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3732
3733   // look for the first zero bit after the run of ones
3734   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3735   // look for the first non-zero bit
3736   ME = V.getActiveBits(); 
3737   return true;
3738 }
3739
3740 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3741 /// where isSub determines whether the operator is a sub.  If we can fold one of
3742 /// the following xforms:
3743 /// 
3744 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3745 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3746 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3747 ///
3748 /// return (A +/- B).
3749 ///
3750 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3751                                         ConstantInt *Mask, bool isSub,
3752                                         Instruction &I) {
3753   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3754   if (!LHSI || LHSI->getNumOperands() != 2 ||
3755       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3756
3757   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3758
3759   switch (LHSI->getOpcode()) {
3760   default: return 0;
3761   case Instruction::And:
3762     if (Context->getConstantExprAnd(N, Mask) == Mask) {
3763       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3764       if ((Mask->getValue().countLeadingZeros() + 
3765            Mask->getValue().countPopulation()) == 
3766           Mask->getValue().getBitWidth())
3767         break;
3768
3769       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3770       // part, we don't need any explicit masks to take them out of A.  If that
3771       // is all N is, ignore it.
3772       uint32_t MB = 0, ME = 0;
3773       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3774         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3775         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3776         if (MaskedValueIsZero(RHS, Mask))
3777           break;
3778       }
3779     }
3780     return 0;
3781   case Instruction::Or:
3782   case Instruction::Xor:
3783     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3784     if ((Mask->getValue().countLeadingZeros() + 
3785          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3786         && Context->getConstantExprAnd(N, Mask)->isNullValue())
3787       break;
3788     return 0;
3789   }
3790   
3791   Instruction *New;
3792   if (isSub)
3793     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3794   else
3795     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3796   return InsertNewInstBefore(New, I);
3797 }
3798
3799 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3800 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3801                                           ICmpInst *LHS, ICmpInst *RHS) {
3802   Value *Val, *Val2;
3803   ConstantInt *LHSCst, *RHSCst;
3804   ICmpInst::Predicate LHSCC, RHSCC;
3805   
3806   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3807   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3808                          m_ConstantInt(LHSCst)), *Context) ||
3809       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3810                          m_ConstantInt(RHSCst)), *Context))
3811     return 0;
3812   
3813   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3814   // where C is a power of 2
3815   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3816       LHSCst->getValue().isPowerOf2()) {
3817     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3818     InsertNewInstBefore(NewOr, I);
3819     return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
3820   }
3821   
3822   // From here on, we only handle:
3823   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3824   if (Val != Val2) return 0;
3825   
3826   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3827   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3828       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3829       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3830       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3831     return 0;
3832   
3833   // We can't fold (ugt x, C) & (sgt x, C2).
3834   if (!PredicatesFoldable(LHSCC, RHSCC))
3835     return 0;
3836     
3837   // Ensure that the larger constant is on the RHS.
3838   bool ShouldSwap;
3839   if (ICmpInst::isSignedPredicate(LHSCC) ||
3840       (ICmpInst::isEquality(LHSCC) && 
3841        ICmpInst::isSignedPredicate(RHSCC)))
3842     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3843   else
3844     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3845     
3846   if (ShouldSwap) {
3847     std::swap(LHS, RHS);
3848     std::swap(LHSCst, RHSCst);
3849     std::swap(LHSCC, RHSCC);
3850   }
3851
3852   // At this point, we know we have have two icmp instructions
3853   // comparing a value against two constants and and'ing the result
3854   // together.  Because of the above check, we know that we only have
3855   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3856   // (from the FoldICmpLogical check above), that the two constants 
3857   // are not equal and that the larger constant is on the RHS
3858   assert(LHSCst != RHSCst && "Compares not folded above?");
3859
3860   switch (LHSCC) {
3861   default: llvm_unreachable("Unknown integer condition code!");
3862   case ICmpInst::ICMP_EQ:
3863     switch (RHSCC) {
3864     default: llvm_unreachable("Unknown integer condition code!");
3865     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3866     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3867     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3868       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3869     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3870     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3871     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3872       return ReplaceInstUsesWith(I, LHS);
3873     }
3874   case ICmpInst::ICMP_NE:
3875     switch (RHSCC) {
3876     default: llvm_unreachable("Unknown integer condition code!");
3877     case ICmpInst::ICMP_ULT:
3878       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
3879         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
3880       break;                        // (X != 13 & X u< 15) -> no change
3881     case ICmpInst::ICMP_SLT:
3882       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
3883         return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
3884       break;                        // (X != 13 & X s< 15) -> no change
3885     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3886     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3887     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3888       return ReplaceInstUsesWith(I, RHS);
3889     case ICmpInst::ICMP_NE:
3890       if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3891         Constant *AddCST = Context->getConstantExprNeg(LHSCst);
3892         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3893                                                      Val->getName()+".off");
3894         InsertNewInstBefore(Add, I);
3895         return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
3896                             Context->getConstantInt(Add->getType(), 1));
3897       }
3898       break;                        // (X != 13 & X != 15) -> no change
3899     }
3900     break;
3901   case ICmpInst::ICMP_ULT:
3902     switch (RHSCC) {
3903     default: llvm_unreachable("Unknown integer condition code!");
3904     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3905     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3906       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3907     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3908       break;
3909     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3910     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3911       return ReplaceInstUsesWith(I, LHS);
3912     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3913       break;
3914     }
3915     break;
3916   case ICmpInst::ICMP_SLT:
3917     switch (RHSCC) {
3918     default: llvm_unreachable("Unknown integer condition code!");
3919     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3920     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3921       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3922     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3923       break;
3924     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3925     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3926       return ReplaceInstUsesWith(I, LHS);
3927     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3928       break;
3929     }
3930     break;
3931   case ICmpInst::ICMP_UGT:
3932     switch (RHSCC) {
3933     default: llvm_unreachable("Unknown integer condition code!");
3934     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3935     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3936       return ReplaceInstUsesWith(I, RHS);
3937     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3938       break;
3939     case ICmpInst::ICMP_NE:
3940       if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
3941         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3942       break;                        // (X u> 13 & X != 15) -> no change
3943     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3944       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3945                              RHSCst, false, true, I);
3946     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3947       break;
3948     }
3949     break;
3950   case ICmpInst::ICMP_SGT:
3951     switch (RHSCC) {
3952     default: llvm_unreachable("Unknown integer condition code!");
3953     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3954     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3955       return ReplaceInstUsesWith(I, RHS);
3956     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3957       break;
3958     case ICmpInst::ICMP_NE:
3959       if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
3960         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3961       break;                        // (X s> 13 & X != 15) -> no change
3962     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3963       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3964                              RHSCst, true, true, I);
3965     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3966       break;
3967     }
3968     break;
3969   }
3970  
3971   return 0;
3972 }
3973
3974
3975 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3976   bool Changed = SimplifyCommutative(I);
3977   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3978
3979   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3980     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3981
3982   // and X, X = X
3983   if (Op0 == Op1)
3984     return ReplaceInstUsesWith(I, Op1);
3985
3986   // See if we can simplify any instructions used by the instruction whose sole 
3987   // purpose is to compute bits we don't care about.
3988   if (SimplifyDemandedInstructionBits(I))
3989     return &I;
3990   if (isa<VectorType>(I.getType())) {
3991     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3992       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3993         return ReplaceInstUsesWith(I, I.getOperand(0));
3994     } else if (isa<ConstantAggregateZero>(Op1)) {
3995       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3996     }
3997   }
3998
3999   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4000     const APInt& AndRHSMask = AndRHS->getValue();
4001     APInt NotAndRHS(~AndRHSMask);
4002
4003     // Optimize a variety of ((val OP C1) & C2) combinations...
4004     if (isa<BinaryOperator>(Op0)) {
4005       Instruction *Op0I = cast<Instruction>(Op0);
4006       Value *Op0LHS = Op0I->getOperand(0);
4007       Value *Op0RHS = Op0I->getOperand(1);
4008       switch (Op0I->getOpcode()) {
4009       case Instruction::Xor:
4010       case Instruction::Or:
4011         // If the mask is only needed on one incoming arm, push it up.
4012         if (Op0I->hasOneUse()) {
4013           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4014             // Not masking anything out for the LHS, move to RHS.
4015             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
4016                                                    Op0RHS->getName()+".masked");
4017             InsertNewInstBefore(NewRHS, I);
4018             return BinaryOperator::Create(
4019                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4020           }
4021           if (!isa<Constant>(Op0RHS) &&
4022               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4023             // Not masking anything out for the RHS, move to LHS.
4024             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
4025                                                    Op0LHS->getName()+".masked");
4026             InsertNewInstBefore(NewLHS, I);
4027             return BinaryOperator::Create(
4028                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4029           }
4030         }
4031
4032         break;
4033       case Instruction::Add:
4034         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4035         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4036         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4037         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4038           return BinaryOperator::CreateAnd(V, AndRHS);
4039         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4040           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4041         break;
4042
4043       case Instruction::Sub:
4044         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4045         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4046         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4047         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4048           return BinaryOperator::CreateAnd(V, AndRHS);
4049
4050         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4051         // has 1's for all bits that the subtraction with A might affect.
4052         if (Op0I->hasOneUse()) {
4053           uint32_t BitWidth = AndRHSMask.getBitWidth();
4054           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4055           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4056
4057           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4058           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4059               MaskedValueIsZero(Op0LHS, Mask)) {
4060             Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
4061             InsertNewInstBefore(NewNeg, I);
4062             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4063           }
4064         }
4065         break;
4066
4067       case Instruction::Shl:
4068       case Instruction::LShr:
4069         // (1 << x) & 1 --> zext(x == 0)
4070         // (1 >> x) & 1 --> zext(x == 0)
4071         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4072           Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4073                                     Op0RHS, Context->getNullValue(I.getType()));
4074           InsertNewInstBefore(NewICmp, I);
4075           return new ZExtInst(NewICmp, I.getType());
4076         }
4077         break;
4078       }
4079
4080       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4081         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4082           return Res;
4083     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4084       // If this is an integer truncation or change from signed-to-unsigned, and
4085       // if the source is an and/or with immediate, transform it.  This
4086       // frequently occurs for bitfield accesses.
4087       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4088         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4089             CastOp->getNumOperands() == 2)
4090           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4091             if (CastOp->getOpcode() == Instruction::And) {
4092               // Change: and (cast (and X, C1) to T), C2
4093               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4094               // This will fold the two constants together, which may allow 
4095               // other simplifications.
4096               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4097                 CastOp->getOperand(0), I.getType(), 
4098                 CastOp->getName()+".shrunk");
4099               NewCast = InsertNewInstBefore(NewCast, I);
4100               // trunc_or_bitcast(C1)&C2
4101               Constant *C3 =
4102                       Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4103               C3 = Context->getConstantExprAnd(C3, AndRHS);
4104               return BinaryOperator::CreateAnd(NewCast, C3);
4105             } else if (CastOp->getOpcode() == Instruction::Or) {
4106               // Change: and (cast (or X, C1) to T), C2
4107               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4108               Constant *C3 =
4109                       Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4110               if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4111                 // trunc(C1)&C2
4112                 return ReplaceInstUsesWith(I, AndRHS);
4113             }
4114           }
4115       }
4116     }
4117
4118     // Try to fold constant and into select arguments.
4119     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4120       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4121         return R;
4122     if (isa<PHINode>(Op0))
4123       if (Instruction *NV = FoldOpIntoPhi(I))
4124         return NV;
4125   }
4126
4127   Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4128   Value *Op1NotVal = dyn_castNotVal(Op1, Context);
4129
4130   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4131     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
4132
4133   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4134   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4135     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4136                                                I.getName()+".demorgan");
4137     InsertNewInstBefore(Or, I);
4138     return BinaryOperator::CreateNot(*Context, Or);
4139   }
4140   
4141   {
4142     Value *A = 0, *B = 0, *C = 0, *D = 0;
4143     if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
4144       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4145         return ReplaceInstUsesWith(I, Op1);
4146     
4147       // (A|B) & ~(A&B) -> A^B
4148       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4149         if ((A == C && B == D) || (A == D && B == C))
4150           return BinaryOperator::CreateXor(A, B);
4151       }
4152     }
4153     
4154     if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
4155       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4156         return ReplaceInstUsesWith(I, Op0);
4157
4158       // ~(A&B) & (A|B) -> A^B
4159       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4160         if ((A == C && B == D) || (A == D && B == C))
4161           return BinaryOperator::CreateXor(A, B);
4162       }
4163     }
4164     
4165     if (Op0->hasOneUse() &&
4166         match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4167       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4168         I.swapOperands();     // Simplify below
4169         std::swap(Op0, Op1);
4170       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4171         cast<BinaryOperator>(Op0)->swapOperands();
4172         I.swapOperands();     // Simplify below
4173         std::swap(Op0, Op1);
4174       }
4175     }
4176
4177     if (Op1->hasOneUse() &&
4178         match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4179       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4180         cast<BinaryOperator>(Op1)->swapOperands();
4181         std::swap(A, B);
4182       }
4183       if (A == Op0) {                                // A&(A^B) -> A & ~B
4184         Instruction *NotB = BinaryOperator::CreateNot(*Context, B, "tmp");
4185         InsertNewInstBefore(NotB, I);
4186         return BinaryOperator::CreateAnd(A, NotB);
4187       }
4188     }
4189
4190     // (A&((~A)|B)) -> A&B
4191     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4192         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
4193       return BinaryOperator::CreateAnd(A, Op1);
4194     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4195         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
4196       return BinaryOperator::CreateAnd(A, Op0);
4197   }
4198   
4199   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4200     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4201     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4202       return R;
4203
4204     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4205       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4206         return Res;
4207   }
4208
4209   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4210   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4211     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4212       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4213         const Type *SrcTy = Op0C->getOperand(0)->getType();
4214         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4215             // Only do this if the casts both really cause code to be generated.
4216             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4217                               I.getType(), TD) &&
4218             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4219                               I.getType(), TD)) {
4220           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4221                                                          Op1C->getOperand(0),
4222                                                          I.getName());
4223           InsertNewInstBefore(NewOp, I);
4224           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4225         }
4226       }
4227     
4228   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4229   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4230     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4231       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4232           SI0->getOperand(1) == SI1->getOperand(1) &&
4233           (SI0->hasOneUse() || SI1->hasOneUse())) {
4234         Instruction *NewOp =
4235           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4236                                                         SI1->getOperand(0),
4237                                                         SI0->getName()), I);
4238         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4239                                       SI1->getOperand(1));
4240       }
4241   }
4242
4243   // If and'ing two fcmp, try combine them into one.
4244   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4245     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4246       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4247           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4248         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4249         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4250           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4251             // If either of the constants are nans, then the whole thing returns
4252             // false.
4253             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4254               return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4255             return new FCmpInst(*Context, FCmpInst::FCMP_ORD, 
4256                                 LHS->getOperand(0), RHS->getOperand(0));
4257           }
4258       } else {
4259         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4260         FCmpInst::Predicate Op0CC, Op1CC;
4261         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4262                   m_Value(Op0RHS)), *Context) &&
4263             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4264                   m_Value(Op1RHS)), *Context)) {
4265           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4266             // Swap RHS operands to match LHS.
4267             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4268             std::swap(Op1LHS, Op1RHS);
4269           }
4270           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4271             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4272             if (Op0CC == Op1CC)
4273               return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4274                                   Op0LHS, Op0RHS);
4275             else if (Op0CC == FCmpInst::FCMP_FALSE ||
4276                      Op1CC == FCmpInst::FCMP_FALSE)
4277               return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4278             else if (Op0CC == FCmpInst::FCMP_TRUE)
4279               return ReplaceInstUsesWith(I, Op1);
4280             else if (Op1CC == FCmpInst::FCMP_TRUE)
4281               return ReplaceInstUsesWith(I, Op0);
4282             bool Op0Ordered;
4283             bool Op1Ordered;
4284             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4285             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4286             if (Op1Pred == 0) {
4287               std::swap(Op0, Op1);
4288               std::swap(Op0Pred, Op1Pred);
4289               std::swap(Op0Ordered, Op1Ordered);
4290             }
4291             if (Op0Pred == 0) {
4292               // uno && ueq -> uno && (uno || eq) -> ueq
4293               // ord && olt -> ord && (ord && lt) -> olt
4294               if (Op0Ordered == Op1Ordered)
4295                 return ReplaceInstUsesWith(I, Op1);
4296               // uno && oeq -> uno && (ord && eq) -> false
4297               // uno && ord -> false
4298               if (!Op0Ordered)
4299                 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4300               // ord && ueq -> ord && (uno || eq) -> oeq
4301               return cast<Instruction>(getFCmpValue(true, Op1Pred,
4302                                                     Op0LHS, Op0RHS, Context));
4303             }
4304           }
4305         }
4306       }
4307     }
4308   }
4309
4310   return Changed ? &I : 0;
4311 }
4312
4313 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4314 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4315 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4316 /// the expression came from the corresponding "byte swapped" byte in some other
4317 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4318 /// we know that the expression deposits the low byte of %X into the high byte
4319 /// of the bswap result and that all other bytes are zero.  This expression is
4320 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4321 /// match.
4322 ///
4323 /// This function returns true if the match was unsuccessful and false if so.
4324 /// On entry to the function the "OverallLeftShift" is a signed integer value
4325 /// indicating the number of bytes that the subexpression is later shifted.  For
4326 /// example, if the expression is later right shifted by 16 bits, the
4327 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4328 /// byte of ByteValues is actually being set.
4329 ///
4330 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4331 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4332 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4333 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4334 /// always in the local (OverallLeftShift) coordinate space.
4335 ///
4336 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4337                               SmallVector<Value*, 8> &ByteValues) {
4338   if (Instruction *I = dyn_cast<Instruction>(V)) {
4339     // If this is an or instruction, it may be an inner node of the bswap.
4340     if (I->getOpcode() == Instruction::Or) {
4341       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4342                                ByteValues) ||
4343              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4344                                ByteValues);
4345     }
4346   
4347     // If this is a logical shift by a constant multiple of 8, recurse with
4348     // OverallLeftShift and ByteMask adjusted.
4349     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4350       unsigned ShAmt = 
4351         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4352       // Ensure the shift amount is defined and of a byte value.
4353       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4354         return true;
4355
4356       unsigned ByteShift = ShAmt >> 3;
4357       if (I->getOpcode() == Instruction::Shl) {
4358         // X << 2 -> collect(X, +2)
4359         OverallLeftShift += ByteShift;
4360         ByteMask >>= ByteShift;
4361       } else {
4362         // X >>u 2 -> collect(X, -2)
4363         OverallLeftShift -= ByteShift;
4364         ByteMask <<= ByteShift;
4365         ByteMask &= (~0U >> (32-ByteValues.size()));
4366       }
4367
4368       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4369       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4370
4371       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4372                                ByteValues);
4373     }
4374
4375     // If this is a logical 'and' with a mask that clears bytes, clear the
4376     // corresponding bytes in ByteMask.
4377     if (I->getOpcode() == Instruction::And &&
4378         isa<ConstantInt>(I->getOperand(1))) {
4379       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4380       unsigned NumBytes = ByteValues.size();
4381       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4382       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4383       
4384       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4385         // If this byte is masked out by a later operation, we don't care what
4386         // the and mask is.
4387         if ((ByteMask & (1 << i)) == 0)
4388           continue;
4389         
4390         // If the AndMask is all zeros for this byte, clear the bit.
4391         APInt MaskB = AndMask & Byte;
4392         if (MaskB == 0) {
4393           ByteMask &= ~(1U << i);
4394           continue;
4395         }
4396         
4397         // If the AndMask is not all ones for this byte, it's not a bytezap.
4398         if (MaskB != Byte)
4399           return true;
4400
4401         // Otherwise, this byte is kept.
4402       }
4403
4404       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4405                                ByteValues);
4406     }
4407   }
4408   
4409   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4410   // the input value to the bswap.  Some observations: 1) if more than one byte
4411   // is demanded from this input, then it could not be successfully assembled
4412   // into a byteswap.  At least one of the two bytes would not be aligned with
4413   // their ultimate destination.
4414   if (!isPowerOf2_32(ByteMask)) return true;
4415   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4416   
4417   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4418   // is demanded, it needs to go into byte 0 of the result.  This means that the
4419   // byte needs to be shifted until it lands in the right byte bucket.  The
4420   // shift amount depends on the position: if the byte is coming from the high
4421   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4422   // low part, it must be shifted left.
4423   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4424   if (InputByteNo < ByteValues.size()/2) {
4425     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4426       return true;
4427   } else {
4428     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4429       return true;
4430   }
4431   
4432   // If the destination byte value is already defined, the values are or'd
4433   // together, which isn't a bswap (unless it's an or of the same bits).
4434   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4435     return true;
4436   ByteValues[DestByteNo] = V;
4437   return false;
4438 }
4439
4440 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4441 /// If so, insert the new bswap intrinsic and return it.
4442 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4443   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4444   if (!ITy || ITy->getBitWidth() % 16 || 
4445       // ByteMask only allows up to 32-byte values.
4446       ITy->getBitWidth() > 32*8) 
4447     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4448   
4449   /// ByteValues - For each byte of the result, we keep track of which value
4450   /// defines each byte.
4451   SmallVector<Value*, 8> ByteValues;
4452   ByteValues.resize(ITy->getBitWidth()/8);
4453     
4454   // Try to find all the pieces corresponding to the bswap.
4455   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4456   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4457     return 0;
4458   
4459   // Check to see if all of the bytes come from the same value.
4460   Value *V = ByteValues[0];
4461   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4462   
4463   // Check to make sure that all of the bytes come from the same value.
4464   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4465     if (ByteValues[i] != V)
4466       return 0;
4467   const Type *Tys[] = { ITy };
4468   Module *M = I.getParent()->getParent()->getParent();
4469   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4470   return CallInst::Create(F, V);
4471 }
4472
4473 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4474 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4475 /// we can simplify this expression to "cond ? C : D or B".
4476 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4477                                          Value *C, Value *D,
4478                                          LLVMContext *Context) {
4479   // If A is not a select of -1/0, this cannot match.
4480   Value *Cond = 0;
4481   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
4482     return 0;
4483
4484   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4485   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4486     return SelectInst::Create(Cond, C, B);
4487   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4488     return SelectInst::Create(Cond, C, B);
4489   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4490   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4491     return SelectInst::Create(Cond, C, D);
4492   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4493     return SelectInst::Create(Cond, C, D);
4494   return 0;
4495 }
4496
4497 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4498 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4499                                          ICmpInst *LHS, ICmpInst *RHS) {
4500   Value *Val, *Val2;
4501   ConstantInt *LHSCst, *RHSCst;
4502   ICmpInst::Predicate LHSCC, RHSCC;
4503   
4504   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4505   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4506              m_ConstantInt(LHSCst)), *Context) ||
4507       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4508              m_ConstantInt(RHSCst)), *Context))
4509     return 0;
4510   
4511   // From here on, we only handle:
4512   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4513   if (Val != Val2) return 0;
4514   
4515   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4516   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4517       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4518       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4519       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4520     return 0;
4521   
4522   // We can't fold (ugt x, C) | (sgt x, C2).
4523   if (!PredicatesFoldable(LHSCC, RHSCC))
4524     return 0;
4525   
4526   // Ensure that the larger constant is on the RHS.
4527   bool ShouldSwap;
4528   if (ICmpInst::isSignedPredicate(LHSCC) ||
4529       (ICmpInst::isEquality(LHSCC) && 
4530        ICmpInst::isSignedPredicate(RHSCC)))
4531     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4532   else
4533     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4534   
4535   if (ShouldSwap) {
4536     std::swap(LHS, RHS);
4537     std::swap(LHSCst, RHSCst);
4538     std::swap(LHSCC, RHSCC);
4539   }
4540   
4541   // At this point, we know we have have two icmp instructions
4542   // comparing a value against two constants and or'ing the result
4543   // together.  Because of the above check, we know that we only have
4544   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4545   // FoldICmpLogical check above), that the two constants are not
4546   // equal.
4547   assert(LHSCst != RHSCst && "Compares not folded above?");
4548
4549   switch (LHSCC) {
4550   default: llvm_unreachable("Unknown integer condition code!");
4551   case ICmpInst::ICMP_EQ:
4552     switch (RHSCC) {
4553     default: llvm_unreachable("Unknown integer condition code!");
4554     case ICmpInst::ICMP_EQ:
4555       if (LHSCst == SubOne(RHSCst, Context)) {
4556         // (X == 13 | X == 14) -> X-13 <u 2
4557         Constant *AddCST = Context->getConstantExprNeg(LHSCst);
4558         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4559                                                      Val->getName()+".off");
4560         InsertNewInstBefore(Add, I);
4561         AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
4562         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
4563       }
4564       break;                         // (X == 13 | X == 15) -> no change
4565     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4566     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4567       break;
4568     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4569     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4570     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4571       return ReplaceInstUsesWith(I, RHS);
4572     }
4573     break;
4574   case ICmpInst::ICMP_NE:
4575     switch (RHSCC) {
4576     default: llvm_unreachable("Unknown integer condition code!");
4577     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4578     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4579     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4580       return ReplaceInstUsesWith(I, LHS);
4581     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4582     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4583     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4584       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4585     }
4586     break;
4587   case ICmpInst::ICMP_ULT:
4588     switch (RHSCC) {
4589     default: llvm_unreachable("Unknown integer condition code!");
4590     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4591       break;
4592     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4593       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4594       // this can cause overflow.
4595       if (RHSCst->isMaxValue(false))
4596         return ReplaceInstUsesWith(I, LHS);
4597       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4598                              false, false, I);
4599     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4600       break;
4601     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4602     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4603       return ReplaceInstUsesWith(I, RHS);
4604     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4605       break;
4606     }
4607     break;
4608   case ICmpInst::ICMP_SLT:
4609     switch (RHSCC) {
4610     default: llvm_unreachable("Unknown integer condition code!");
4611     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4612       break;
4613     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4614       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4615       // this can cause overflow.
4616       if (RHSCst->isMaxValue(true))
4617         return ReplaceInstUsesWith(I, LHS);
4618       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4619                              true, false, I);
4620     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4621       break;
4622     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4623     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4624       return ReplaceInstUsesWith(I, RHS);
4625     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4626       break;
4627     }
4628     break;
4629   case ICmpInst::ICMP_UGT:
4630     switch (RHSCC) {
4631     default: llvm_unreachable("Unknown integer condition code!");
4632     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4633     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4634       return ReplaceInstUsesWith(I, LHS);
4635     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4636       break;
4637     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4638     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4639       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4640     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4641       break;
4642     }
4643     break;
4644   case ICmpInst::ICMP_SGT:
4645     switch (RHSCC) {
4646     default: llvm_unreachable("Unknown integer condition code!");
4647     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4648     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4649       return ReplaceInstUsesWith(I, LHS);
4650     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4651       break;
4652     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4653     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4654       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4655     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4656       break;
4657     }
4658     break;
4659   }
4660   return 0;
4661 }
4662
4663 /// FoldOrWithConstants - This helper function folds:
4664 ///
4665 ///     ((A | B) & C1) | (B & C2)
4666 ///
4667 /// into:
4668 /// 
4669 ///     (A & C1) | B
4670 ///
4671 /// when the XOR of the two constants is "all ones" (-1).
4672 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4673                                                Value *A, Value *B, Value *C) {
4674   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4675   if (!CI1) return 0;
4676
4677   Value *V1 = 0;
4678   ConstantInt *CI2 = 0;
4679   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
4680
4681   APInt Xor = CI1->getValue() ^ CI2->getValue();
4682   if (!Xor.isAllOnesValue()) return 0;
4683
4684   if (V1 == A || V1 == B) {
4685     Instruction *NewOp =
4686       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4687     return BinaryOperator::CreateOr(NewOp, V1);
4688   }
4689
4690   return 0;
4691 }
4692
4693 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4694   bool Changed = SimplifyCommutative(I);
4695   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4696
4697   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4698     return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4699
4700   // or X, X = X
4701   if (Op0 == Op1)
4702     return ReplaceInstUsesWith(I, Op0);
4703
4704   // See if we can simplify any instructions used by the instruction whose sole 
4705   // purpose is to compute bits we don't care about.
4706   if (SimplifyDemandedInstructionBits(I))
4707     return &I;
4708   if (isa<VectorType>(I.getType())) {
4709     if (isa<ConstantAggregateZero>(Op1)) {
4710       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4711     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4712       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4713         return ReplaceInstUsesWith(I, I.getOperand(1));
4714     }
4715   }
4716
4717   // or X, -1 == -1
4718   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4719     ConstantInt *C1 = 0; Value *X = 0;
4720     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4721     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) && 
4722         isOnlyUse(Op0)) {
4723       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4724       InsertNewInstBefore(Or, I);
4725       Or->takeName(Op0);
4726       return BinaryOperator::CreateAnd(Or, 
4727                Context->getConstantInt(RHS->getValue() | C1->getValue()));
4728     }
4729
4730     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4731     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) && 
4732         isOnlyUse(Op0)) {
4733       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4734       InsertNewInstBefore(Or, I);
4735       Or->takeName(Op0);
4736       return BinaryOperator::CreateXor(Or,
4737                  Context->getConstantInt(C1->getValue() & ~RHS->getValue()));
4738     }
4739
4740     // Try to fold constant and into select arguments.
4741     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4742       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4743         return R;
4744     if (isa<PHINode>(Op0))
4745       if (Instruction *NV = FoldOpIntoPhi(I))
4746         return NV;
4747   }
4748
4749   Value *A = 0, *B = 0;
4750   ConstantInt *C1 = 0, *C2 = 0;
4751
4752   if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
4753     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4754       return ReplaceInstUsesWith(I, Op1);
4755   if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
4756     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4757       return ReplaceInstUsesWith(I, Op0);
4758
4759   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4760   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4761   if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4762       match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4763       (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4764        match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
4765     if (Instruction *BSwap = MatchBSwap(I))
4766       return BSwap;
4767   }
4768   
4769   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4770   if (Op0->hasOneUse() &&
4771       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4772       MaskedValueIsZero(Op1, C1->getValue())) {
4773     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4774     InsertNewInstBefore(NOr, I);
4775     NOr->takeName(Op0);
4776     return BinaryOperator::CreateXor(NOr, C1);
4777   }
4778
4779   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4780   if (Op1->hasOneUse() &&
4781       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4782       MaskedValueIsZero(Op0, C1->getValue())) {
4783     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4784     InsertNewInstBefore(NOr, I);
4785     NOr->takeName(Op0);
4786     return BinaryOperator::CreateXor(NOr, C1);
4787   }
4788
4789   // (A & C)|(B & D)
4790   Value *C = 0, *D = 0;
4791   if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4792       match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
4793     Value *V1 = 0, *V2 = 0, *V3 = 0;
4794     C1 = dyn_cast<ConstantInt>(C);
4795     C2 = dyn_cast<ConstantInt>(D);
4796     if (C1 && C2) {  // (A & C1)|(B & C2)
4797       // If we have: ((V + N) & C1) | (V & C2)
4798       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4799       // replace with V+N.
4800       if (C1->getValue() == ~C2->getValue()) {
4801         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4802             match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4803           // Add commutes, try both ways.
4804           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4805             return ReplaceInstUsesWith(I, A);
4806           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4807             return ReplaceInstUsesWith(I, A);
4808         }
4809         // Or commutes, try both ways.
4810         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4811             match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4812           // Add commutes, try both ways.
4813           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4814             return ReplaceInstUsesWith(I, B);
4815           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4816             return ReplaceInstUsesWith(I, B);
4817         }
4818       }
4819       V1 = 0; V2 = 0; V3 = 0;
4820     }
4821     
4822     // Check to see if we have any common things being and'ed.  If so, find the
4823     // terms for V1 & (V2|V3).
4824     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4825       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4826         V1 = A, V2 = C, V3 = D;
4827       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4828         V1 = A, V2 = B, V3 = C;
4829       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4830         V1 = C, V2 = A, V3 = D;
4831       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4832         V1 = C, V2 = A, V3 = B;
4833       
4834       if (V1) {
4835         Value *Or =
4836           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4837         return BinaryOperator::CreateAnd(V1, Or);
4838       }
4839     }
4840
4841     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4842     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4843       return Match;
4844     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4845       return Match;
4846     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4847       return Match;
4848     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4849       return Match;
4850
4851     // ((A&~B)|(~A&B)) -> A^B
4852     if ((match(C, m_Not(m_Specific(D)), *Context) &&
4853          match(B, m_Not(m_Specific(A)), *Context)))
4854       return BinaryOperator::CreateXor(A, D);
4855     // ((~B&A)|(~A&B)) -> A^B
4856     if ((match(A, m_Not(m_Specific(D)), *Context) &&
4857          match(B, m_Not(m_Specific(C)), *Context)))
4858       return BinaryOperator::CreateXor(C, D);
4859     // ((A&~B)|(B&~A)) -> A^B
4860     if ((match(C, m_Not(m_Specific(B)), *Context) &&
4861          match(D, m_Not(m_Specific(A)), *Context)))
4862       return BinaryOperator::CreateXor(A, B);
4863     // ((~B&A)|(B&~A)) -> A^B
4864     if ((match(A, m_Not(m_Specific(B)), *Context) &&
4865          match(D, m_Not(m_Specific(C)), *Context)))
4866       return BinaryOperator::CreateXor(C, B);
4867   }
4868   
4869   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4870   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4871     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4872       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4873           SI0->getOperand(1) == SI1->getOperand(1) &&
4874           (SI0->hasOneUse() || SI1->hasOneUse())) {
4875         Instruction *NewOp =
4876         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4877                                                      SI1->getOperand(0),
4878                                                      SI0->getName()), I);
4879         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4880                                       SI1->getOperand(1));
4881       }
4882   }
4883
4884   // ((A|B)&1)|(B&-2) -> (A&1) | B
4885   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4886       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4887     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4888     if (Ret) return Ret;
4889   }
4890   // (B&-2)|((A|B)&1) -> (A&1) | B
4891   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4892       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4893     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4894     if (Ret) return Ret;
4895   }
4896
4897   if (match(Op0, m_Not(m_Value(A)), *Context)) {   // ~A | Op1
4898     if (A == Op1)   // ~A | A == -1
4899       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4900   } else {
4901     A = 0;
4902   }
4903   // Note, A is still live here!
4904   if (match(Op1, m_Not(m_Value(B)), *Context)) {   // Op0 | ~B
4905     if (Op0 == B)
4906       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4907
4908     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4909     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4910       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4911                                               I.getName()+".demorgan"), I);
4912       return BinaryOperator::CreateNot(*Context, And);
4913     }
4914   }
4915
4916   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4917   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4918     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4919       return R;
4920
4921     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4922       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4923         return Res;
4924   }
4925     
4926   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4927   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4928     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4929       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4930         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4931             !isa<ICmpInst>(Op1C->getOperand(0))) {
4932           const Type *SrcTy = Op0C->getOperand(0)->getType();
4933           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4934               // Only do this if the casts both really cause code to be
4935               // generated.
4936               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4937                                 I.getType(), TD) &&
4938               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4939                                 I.getType(), TD)) {
4940             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4941                                                           Op1C->getOperand(0),
4942                                                           I.getName());
4943             InsertNewInstBefore(NewOp, I);
4944             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4945           }
4946         }
4947       }
4948   }
4949   
4950     
4951   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4952   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4953     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4954       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4955           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4956           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4957         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4958           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4959             // If either of the constants are nans, then the whole thing returns
4960             // true.
4961             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4962               return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4963             
4964             // Otherwise, no need to compare the two constants, compare the
4965             // rest.
4966             return new FCmpInst(*Context, FCmpInst::FCMP_UNO, 
4967                                 LHS->getOperand(0), RHS->getOperand(0));
4968           }
4969       } else {
4970         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4971         FCmpInst::Predicate Op0CC, Op1CC;
4972         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4973                   m_Value(Op0RHS)), *Context) &&
4974             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4975                   m_Value(Op1RHS)), *Context)) {
4976           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4977             // Swap RHS operands to match LHS.
4978             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4979             std::swap(Op1LHS, Op1RHS);
4980           }
4981           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4982             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4983             if (Op0CC == Op1CC)
4984               return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4985                                   Op0LHS, Op0RHS);
4986             else if (Op0CC == FCmpInst::FCMP_TRUE ||
4987                      Op1CC == FCmpInst::FCMP_TRUE)
4988               return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4989             else if (Op0CC == FCmpInst::FCMP_FALSE)
4990               return ReplaceInstUsesWith(I, Op1);
4991             else if (Op1CC == FCmpInst::FCMP_FALSE)
4992               return ReplaceInstUsesWith(I, Op0);
4993             bool Op0Ordered;
4994             bool Op1Ordered;
4995             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4996             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4997             if (Op0Ordered == Op1Ordered) {
4998               // If both are ordered or unordered, return a new fcmp with
4999               // or'ed predicates.
5000               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
5001                                        Op0LHS, Op0RHS, Context);
5002               if (Instruction *I = dyn_cast<Instruction>(RV))
5003                 return I;
5004               // Otherwise, it's a constant boolean value...
5005               return ReplaceInstUsesWith(I, RV);
5006             }
5007           }
5008         }
5009       }
5010     }
5011   }
5012
5013   return Changed ? &I : 0;
5014 }
5015
5016 namespace {
5017
5018 // XorSelf - Implements: X ^ X --> 0
5019 struct XorSelf {
5020   Value *RHS;
5021   XorSelf(Value *rhs) : RHS(rhs) {}
5022   bool shouldApply(Value *LHS) const { return LHS == RHS; }
5023   Instruction *apply(BinaryOperator &Xor) const {
5024     return &Xor;
5025   }
5026 };
5027
5028 }
5029
5030 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5031   bool Changed = SimplifyCommutative(I);
5032   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5033
5034   if (isa<UndefValue>(Op1)) {
5035     if (isa<UndefValue>(Op0))
5036       // Handle undef ^ undef -> 0 special case. This is a common
5037       // idiom (misuse).
5038       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5039     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5040   }
5041
5042   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5043   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
5044     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5045     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5046   }
5047   
5048   // See if we can simplify any instructions used by the instruction whose sole 
5049   // purpose is to compute bits we don't care about.
5050   if (SimplifyDemandedInstructionBits(I))
5051     return &I;
5052   if (isa<VectorType>(I.getType()))
5053     if (isa<ConstantAggregateZero>(Op1))
5054       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5055
5056   // Is this a ~ operation?
5057   if (Value *NotOp = dyn_castNotVal(&I, Context)) {
5058     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5059     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5060     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5061       if (Op0I->getOpcode() == Instruction::And || 
5062           Op0I->getOpcode() == Instruction::Or) {
5063         if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5064         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
5065           Instruction *NotY =
5066             BinaryOperator::CreateNot(*Context, Op0I->getOperand(1),
5067                                       Op0I->getOperand(1)->getName()+".not");
5068           InsertNewInstBefore(NotY, I);
5069           if (Op0I->getOpcode() == Instruction::And)
5070             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5071           else
5072             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5073         }
5074       }
5075     }
5076   }
5077   
5078   
5079   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5080     if (RHS == Context->getConstantIntTrue() && Op0->hasOneUse()) {
5081       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5082       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5083         return new ICmpInst(*Context, ICI->getInversePredicate(),
5084                             ICI->getOperand(0), ICI->getOperand(1));
5085
5086       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5087         return new FCmpInst(*Context, FCI->getInversePredicate(),
5088                             FCI->getOperand(0), FCI->getOperand(1));
5089     }
5090
5091     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5092     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5093       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5094         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5095           Instruction::CastOps Opcode = Op0C->getOpcode();
5096           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5097             if (RHS == Context->getConstantExprCast(Opcode, 
5098                                              Context->getConstantIntTrue(),
5099                                              Op0C->getDestTy())) {
5100               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5101                                      *Context,
5102                                      CI->getOpcode(), CI->getInversePredicate(),
5103                                      CI->getOperand(0), CI->getOperand(1)), I);
5104               NewCI->takeName(CI);
5105               return CastInst::Create(Opcode, NewCI, Op0C->getType());
5106             }
5107           }
5108         }
5109       }
5110     }
5111
5112     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5113       // ~(c-X) == X-c-1 == X+(-c-1)
5114       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5115         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5116           Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5117           Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
5118                                       Context->getConstantInt(I.getType(), 1));
5119           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5120         }
5121           
5122       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5123         if (Op0I->getOpcode() == Instruction::Add) {
5124           // ~(X-c) --> (-c-1)-X
5125           if (RHS->isAllOnesValue()) {
5126             Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
5127             return BinaryOperator::CreateSub(
5128                            Context->getConstantExprSub(NegOp0CI,
5129                                       Context->getConstantInt(I.getType(), 1)),
5130                                       Op0I->getOperand(0));
5131           } else if (RHS->getValue().isSignBit()) {
5132             // (X + C) ^ signbit -> (X + C + signbit)
5133             Constant *C =
5134                    Context->getConstantInt(RHS->getValue() + Op0CI->getValue());
5135             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5136
5137           }
5138         } else if (Op0I->getOpcode() == Instruction::Or) {
5139           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5140           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5141             Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
5142             // Anything in both C1 and C2 is known to be zero, remove it from
5143             // NewRHS.
5144             Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5145             NewRHS = Context->getConstantExprAnd(NewRHS, 
5146                                        Context->getConstantExprNot(CommonBits));
5147             AddToWorkList(Op0I);
5148             I.setOperand(0, Op0I->getOperand(0));
5149             I.setOperand(1, NewRHS);
5150             return &I;
5151           }
5152         }
5153       }
5154     }
5155
5156     // Try to fold constant and into select arguments.
5157     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5158       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5159         return R;
5160     if (isa<PHINode>(Op0))
5161       if (Instruction *NV = FoldOpIntoPhi(I))
5162         return NV;
5163   }
5164
5165   if (Value *X = dyn_castNotVal(Op0, Context))   // ~A ^ A == -1
5166     if (X == Op1)
5167       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5168
5169   if (Value *X = dyn_castNotVal(Op1, Context))   // A ^ ~A == -1
5170     if (X == Op0)
5171       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5172
5173   
5174   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5175   if (Op1I) {
5176     Value *A, *B;
5177     if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
5178       if (A == Op0) {              // B^(B|A) == (A|B)^B
5179         Op1I->swapOperands();
5180         I.swapOperands();
5181         std::swap(Op0, Op1);
5182       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5183         I.swapOperands();     // Simplified below.
5184         std::swap(Op0, Op1);
5185       }
5186     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
5187       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5188     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
5189       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5190     } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) && 
5191                Op1I->hasOneUse()){
5192       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5193         Op1I->swapOperands();
5194         std::swap(A, B);
5195       }
5196       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5197         I.swapOperands();     // Simplified below.
5198         std::swap(Op0, Op1);
5199       }
5200     }
5201   }
5202   
5203   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5204   if (Op0I) {
5205     Value *A, *B;
5206     if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5207         Op0I->hasOneUse()) {
5208       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5209         std::swap(A, B);
5210       if (B == Op1) {                                // (A|B)^B == A & ~B
5211         Instruction *NotB =
5212           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, 
5213                                                         Op1, "tmp"), I);
5214         return BinaryOperator::CreateAnd(A, NotB);
5215       }
5216     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
5217       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5218     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
5219       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5220     } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) && 
5221                Op0I->hasOneUse()){
5222       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5223         std::swap(A, B);
5224       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5225           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5226         Instruction *N =
5227           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, A, "tmp"), I);
5228         return BinaryOperator::CreateAnd(N, Op1);
5229       }
5230     }
5231   }
5232   
5233   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5234   if (Op0I && Op1I && Op0I->isShift() && 
5235       Op0I->getOpcode() == Op1I->getOpcode() && 
5236       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5237       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5238     Instruction *NewOp =
5239       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5240                                                     Op1I->getOperand(0),
5241                                                     Op0I->getName()), I);
5242     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5243                                   Op1I->getOperand(1));
5244   }
5245     
5246   if (Op0I && Op1I) {
5247     Value *A, *B, *C, *D;
5248     // (A & B)^(A | B) -> A ^ B
5249     if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5250         match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
5251       if ((A == C && B == D) || (A == D && B == C)) 
5252         return BinaryOperator::CreateXor(A, B);
5253     }
5254     // (A | B)^(A & B) -> A ^ B
5255     if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5256         match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5257       if ((A == C && B == D) || (A == D && B == C)) 
5258         return BinaryOperator::CreateXor(A, B);
5259     }
5260     
5261     // (A & B)^(C & D)
5262     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5263         match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5264         match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5265       // (X & Y)^(X & Y) -> (Y^Z) & X
5266       Value *X = 0, *Y = 0, *Z = 0;
5267       if (A == C)
5268         X = A, Y = B, Z = D;
5269       else if (A == D)
5270         X = A, Y = B, Z = C;
5271       else if (B == C)
5272         X = B, Y = A, Z = D;
5273       else if (B == D)
5274         X = B, Y = A, Z = C;
5275       
5276       if (X) {
5277         Instruction *NewOp =
5278         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5279         return BinaryOperator::CreateAnd(NewOp, X);
5280       }
5281     }
5282   }
5283     
5284   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5285   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5286     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
5287       return R;
5288
5289   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5290   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5291     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5292       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5293         const Type *SrcTy = Op0C->getOperand(0)->getType();
5294         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5295             // Only do this if the casts both really cause code to be generated.
5296             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5297                               I.getType(), TD) &&
5298             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5299                               I.getType(), TD)) {
5300           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5301                                                          Op1C->getOperand(0),
5302                                                          I.getName());
5303           InsertNewInstBefore(NewOp, I);
5304           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5305         }
5306       }
5307   }
5308
5309   return Changed ? &I : 0;
5310 }
5311
5312 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5313                                    LLVMContext *Context) {
5314   return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
5315 }
5316
5317 static bool HasAddOverflow(ConstantInt *Result,
5318                            ConstantInt *In1, ConstantInt *In2,
5319                            bool IsSigned) {
5320   if (IsSigned)
5321     if (In2->getValue().isNegative())
5322       return Result->getValue().sgt(In1->getValue());
5323     else
5324       return Result->getValue().slt(In1->getValue());
5325   else
5326     return Result->getValue().ult(In1->getValue());
5327 }
5328
5329 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5330 /// overflowed for this type.
5331 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5332                             Constant *In2, LLVMContext *Context,
5333                             bool IsSigned = false) {
5334   Result = Context->getConstantExprAdd(In1, In2);
5335
5336   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5337     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5338       Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5339       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5340                          ExtractElement(In1, Idx, Context),
5341                          ExtractElement(In2, Idx, Context),
5342                          IsSigned))
5343         return true;
5344     }
5345     return false;
5346   }
5347
5348   return HasAddOverflow(cast<ConstantInt>(Result),
5349                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5350                         IsSigned);
5351 }
5352
5353 static bool HasSubOverflow(ConstantInt *Result,
5354                            ConstantInt *In1, ConstantInt *In2,
5355                            bool IsSigned) {
5356   if (IsSigned)
5357     if (In2->getValue().isNegative())
5358       return Result->getValue().slt(In1->getValue());
5359     else
5360       return Result->getValue().sgt(In1->getValue());
5361   else
5362     return Result->getValue().ugt(In1->getValue());
5363 }
5364
5365 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5366 /// overflowed for this type.
5367 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5368                             Constant *In2, LLVMContext *Context,
5369                             bool IsSigned = false) {
5370   Result = Context->getConstantExprSub(In1, In2);
5371
5372   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5373     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5374       Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5375       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5376                          ExtractElement(In1, Idx, Context),
5377                          ExtractElement(In2, Idx, Context),
5378                          IsSigned))
5379         return true;
5380     }
5381     return false;
5382   }
5383
5384   return HasSubOverflow(cast<ConstantInt>(Result),
5385                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5386                         IsSigned);
5387 }
5388
5389 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5390 /// code necessary to compute the offset from the base pointer (without adding
5391 /// in the base pointer).  Return the result as a signed integer of intptr size.
5392 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5393   TargetData &TD = IC.getTargetData();
5394   gep_type_iterator GTI = gep_type_begin(GEP);
5395   const Type *IntPtrTy = TD.getIntPtrType();
5396   LLVMContext *Context = IC.getContext();
5397   Value *Result = Context->getNullValue(IntPtrTy);
5398
5399   // Build a mask for high order bits.
5400   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5401   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5402
5403   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5404        ++i, ++GTI) {
5405     Value *Op = *i;
5406     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5407     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5408       if (OpC->isZero()) continue;
5409       
5410       // Handle a struct index, which adds its field offset to the pointer.
5411       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5412         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5413         
5414         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5415           Result = 
5416              Context->getConstantInt(RC->getValue() + APInt(IntPtrWidth, Size));
5417         else
5418           Result = IC.InsertNewInstBefore(
5419                    BinaryOperator::CreateAdd(Result,
5420                                         Context->getConstantInt(IntPtrTy, Size),
5421                                              GEP->getName()+".offs"), I);
5422         continue;
5423       }
5424       
5425       Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5426       Constant *OC =
5427               Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5428       Scale = Context->getConstantExprMul(OC, Scale);
5429       if (Constant *RC = dyn_cast<Constant>(Result))
5430         Result = Context->getConstantExprAdd(RC, Scale);
5431       else {
5432         // Emit an add instruction.
5433         Result = IC.InsertNewInstBefore(
5434            BinaryOperator::CreateAdd(Result, Scale,
5435                                      GEP->getName()+".offs"), I);
5436       }
5437       continue;
5438     }
5439     // Convert to correct type.
5440     if (Op->getType() != IntPtrTy) {
5441       if (Constant *OpC = dyn_cast<Constant>(Op))
5442         Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
5443       else
5444         Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5445                                                                 true,
5446                                                       Op->getName()+".c"), I);
5447     }
5448     if (Size != 1) {
5449       Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5450       if (Constant *OpC = dyn_cast<Constant>(Op))
5451         Op = Context->getConstantExprMul(OpC, Scale);
5452       else    // We'll let instcombine(mul) convert this to a shl if possible.
5453         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5454                                                   GEP->getName()+".idx"), I);
5455     }
5456
5457     // Emit an add instruction.
5458     if (isa<Constant>(Op) && isa<Constant>(Result))
5459       Result = Context->getConstantExprAdd(cast<Constant>(Op),
5460                                     cast<Constant>(Result));
5461     else
5462       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5463                                                   GEP->getName()+".offs"), I);
5464   }
5465   return Result;
5466 }
5467
5468
5469 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5470 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
5471 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
5472 /// complex, and scales are involved.  The above expression would also be legal
5473 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
5474 /// later form is less amenable to optimization though, and we are allowed to
5475 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5476 ///
5477 /// If we can't emit an optimized form for this expression, this returns null.
5478 /// 
5479 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5480                                           InstCombiner &IC) {
5481   TargetData &TD = IC.getTargetData();
5482   gep_type_iterator GTI = gep_type_begin(GEP);
5483
5484   // Check to see if this gep only has a single variable index.  If so, and if
5485   // any constant indices are a multiple of its scale, then we can compute this
5486   // in terms of the scale of the variable index.  For example, if the GEP
5487   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5488   // because the expression will cross zero at the same point.
5489   unsigned i, e = GEP->getNumOperands();
5490   int64_t Offset = 0;
5491   for (i = 1; i != e; ++i, ++GTI) {
5492     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5493       // Compute the aggregate offset of constant indices.
5494       if (CI->isZero()) continue;
5495
5496       // Handle a struct index, which adds its field offset to the pointer.
5497       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5498         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5499       } else {
5500         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5501         Offset += Size*CI->getSExtValue();
5502       }
5503     } else {
5504       // Found our variable index.
5505       break;
5506     }
5507   }
5508   
5509   // If there are no variable indices, we must have a constant offset, just
5510   // evaluate it the general way.
5511   if (i == e) return 0;
5512   
5513   Value *VariableIdx = GEP->getOperand(i);
5514   // Determine the scale factor of the variable element.  For example, this is
5515   // 4 if the variable index is into an array of i32.
5516   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5517   
5518   // Verify that there are no other variable indices.  If so, emit the hard way.
5519   for (++i, ++GTI; i != e; ++i, ++GTI) {
5520     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5521     if (!CI) return 0;
5522    
5523     // Compute the aggregate offset of constant indices.
5524     if (CI->isZero()) continue;
5525     
5526     // Handle a struct index, which adds its field offset to the pointer.
5527     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5528       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5529     } else {
5530       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5531       Offset += Size*CI->getSExtValue();
5532     }
5533   }
5534   
5535   // Okay, we know we have a single variable index, which must be a
5536   // pointer/array/vector index.  If there is no offset, life is simple, return
5537   // the index.
5538   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5539   if (Offset == 0) {
5540     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5541     // we don't need to bother extending: the extension won't affect where the
5542     // computation crosses zero.
5543     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5544       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5545                                   VariableIdx->getNameStart(), &I);
5546     return VariableIdx;
5547   }
5548   
5549   // Otherwise, there is an index.  The computation we will do will be modulo
5550   // the pointer size, so get it.
5551   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5552   
5553   Offset &= PtrSizeMask;
5554   VariableScale &= PtrSizeMask;
5555
5556   // To do this transformation, any constant index must be a multiple of the
5557   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5558   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5559   // multiple of the variable scale.
5560   int64_t NewOffs = Offset / (int64_t)VariableScale;
5561   if (Offset != NewOffs*(int64_t)VariableScale)
5562     return 0;
5563
5564   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5565   const Type *IntPtrTy = TD.getIntPtrType();
5566   if (VariableIdx->getType() != IntPtrTy)
5567     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5568                                               true /*SExt*/, 
5569                                               VariableIdx->getNameStart(), &I);
5570   Constant *OffsetVal = IC.getContext()->getConstantInt(IntPtrTy, NewOffs);
5571   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5572 }
5573
5574
5575 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5576 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5577 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5578                                        ICmpInst::Predicate Cond,
5579                                        Instruction &I) {
5580   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5581
5582   // Look through bitcasts.
5583   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5584     RHS = BCI->getOperand(0);
5585
5586   Value *PtrBase = GEPLHS->getOperand(0);
5587   if (PtrBase == RHS) {
5588     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5589     // This transformation (ignoring the base and scales) is valid because we
5590     // know pointers can't overflow.  See if we can output an optimized form.
5591     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5592     
5593     // If not, synthesize the offset the hard way.
5594     if (Offset == 0)
5595       Offset = EmitGEPOffset(GEPLHS, I, *this);
5596     return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
5597                         Context->getNullValue(Offset->getType()));
5598   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5599     // If the base pointers are different, but the indices are the same, just
5600     // compare the base pointer.
5601     if (PtrBase != GEPRHS->getOperand(0)) {
5602       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5603       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5604                         GEPRHS->getOperand(0)->getType();
5605       if (IndicesTheSame)
5606         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5607           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5608             IndicesTheSame = false;
5609             break;
5610           }
5611
5612       // If all indices are the same, just compare the base pointers.
5613       if (IndicesTheSame)
5614         return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), 
5615                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5616
5617       // Otherwise, the base pointers are different and the indices are
5618       // different, bail out.
5619       return 0;
5620     }
5621
5622     // If one of the GEPs has all zero indices, recurse.
5623     bool AllZeros = true;
5624     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5625       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5626           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5627         AllZeros = false;
5628         break;
5629       }
5630     if (AllZeros)
5631       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5632                           ICmpInst::getSwappedPredicate(Cond), I);
5633
5634     // If the other GEP has all zero indices, recurse.
5635     AllZeros = true;
5636     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5637       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5638           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5639         AllZeros = false;
5640         break;
5641       }
5642     if (AllZeros)
5643       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5644
5645     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5646       // If the GEPs only differ by one index, compare it.
5647       unsigned NumDifferences = 0;  // Keep track of # differences.
5648       unsigned DiffOperand = 0;     // The operand that differs.
5649       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5650         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5651           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5652                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5653             // Irreconcilable differences.
5654             NumDifferences = 2;
5655             break;
5656           } else {
5657             if (NumDifferences++) break;
5658             DiffOperand = i;
5659           }
5660         }
5661
5662       if (NumDifferences == 0)   // SAME GEP?
5663         return ReplaceInstUsesWith(I, // No comparison is needed here.
5664                                    Context->getConstantInt(Type::Int1Ty,
5665                                              ICmpInst::isTrueWhenEqual(Cond)));
5666
5667       else if (NumDifferences == 1) {
5668         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5669         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5670         // Make sure we do a signed comparison here.
5671         return new ICmpInst(*Context,
5672                             ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5673       }
5674     }
5675
5676     // Only lower this if the icmp is the only user of the GEP or if we expect
5677     // the result to fold to a constant!
5678     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5679         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5680       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5681       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5682       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5683       return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
5684     }
5685   }
5686   return 0;
5687 }
5688
5689 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5690 ///
5691 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5692                                                 Instruction *LHSI,
5693                                                 Constant *RHSC) {
5694   if (!isa<ConstantFP>(RHSC)) return 0;
5695   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5696   
5697   // Get the width of the mantissa.  We don't want to hack on conversions that
5698   // might lose information from the integer, e.g. "i64 -> float"
5699   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5700   if (MantissaWidth == -1) return 0;  // Unknown.
5701   
5702   // Check to see that the input is converted from an integer type that is small
5703   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5704   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5705   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5706   
5707   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5708   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5709   if (LHSUnsigned)
5710     ++InputSize;
5711   
5712   // If the conversion would lose info, don't hack on this.
5713   if ((int)InputSize > MantissaWidth)
5714     return 0;
5715   
5716   // Otherwise, we can potentially simplify the comparison.  We know that it
5717   // will always come through as an integer value and we know the constant is
5718   // not a NAN (it would have been previously simplified).
5719   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5720   
5721   ICmpInst::Predicate Pred;
5722   switch (I.getPredicate()) {
5723   default: llvm_unreachable("Unexpected predicate!");
5724   case FCmpInst::FCMP_UEQ:
5725   case FCmpInst::FCMP_OEQ:
5726     Pred = ICmpInst::ICMP_EQ;
5727     break;
5728   case FCmpInst::FCMP_UGT:
5729   case FCmpInst::FCMP_OGT:
5730     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5731     break;
5732   case FCmpInst::FCMP_UGE:
5733   case FCmpInst::FCMP_OGE:
5734     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5735     break;
5736   case FCmpInst::FCMP_ULT:
5737   case FCmpInst::FCMP_OLT:
5738     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5739     break;
5740   case FCmpInst::FCMP_ULE:
5741   case FCmpInst::FCMP_OLE:
5742     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5743     break;
5744   case FCmpInst::FCMP_UNE:
5745   case FCmpInst::FCMP_ONE:
5746     Pred = ICmpInst::ICMP_NE;
5747     break;
5748   case FCmpInst::FCMP_ORD:
5749     return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5750   case FCmpInst::FCMP_UNO:
5751     return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5752   }
5753   
5754   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5755   
5756   // Now we know that the APFloat is a normal number, zero or inf.
5757   
5758   // See if the FP constant is too large for the integer.  For example,
5759   // comparing an i8 to 300.0.
5760   unsigned IntWidth = IntTy->getScalarSizeInBits();
5761   
5762   if (!LHSUnsigned) {
5763     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5764     // and large values.
5765     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5766     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5767                           APFloat::rmNearestTiesToEven);
5768     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5769       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5770           Pred == ICmpInst::ICMP_SLE)
5771         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5772       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5773     }
5774   } else {
5775     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5776     // +INF and large values.
5777     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5778     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5779                           APFloat::rmNearestTiesToEven);
5780     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5781       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5782           Pred == ICmpInst::ICMP_ULE)
5783         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5784       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5785     }
5786   }
5787   
5788   if (!LHSUnsigned) {
5789     // See if the RHS value is < SignedMin.
5790     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5791     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5792                           APFloat::rmNearestTiesToEven);
5793     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5794       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5795           Pred == ICmpInst::ICMP_SGE)
5796         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5797       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5798     }
5799   }
5800
5801   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5802   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5803   // casting the FP value to the integer value and back, checking for equality.
5804   // Don't do this for zero, because -0.0 is not fractional.
5805   Constant *RHSInt = LHSUnsigned
5806     ? Context->getConstantExprFPToUI(RHSC, IntTy)
5807     : Context->getConstantExprFPToSI(RHSC, IntTy);
5808   if (!RHS.isZero()) {
5809     bool Equal = LHSUnsigned
5810       ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5811       : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
5812     if (!Equal) {
5813       // If we had a comparison against a fractional value, we have to adjust
5814       // the compare predicate and sometimes the value.  RHSC is rounded towards
5815       // zero at this point.
5816       switch (Pred) {
5817       default: llvm_unreachable("Unexpected integer comparison!");
5818       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5819         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5820       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5821         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5822       case ICmpInst::ICMP_ULE:
5823         // (float)int <= 4.4   --> int <= 4
5824         // (float)int <= -4.4  --> false
5825         if (RHS.isNegative())
5826           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5827         break;
5828       case ICmpInst::ICMP_SLE:
5829         // (float)int <= 4.4   --> int <= 4
5830         // (float)int <= -4.4  --> int < -4
5831         if (RHS.isNegative())
5832           Pred = ICmpInst::ICMP_SLT;
5833         break;
5834       case ICmpInst::ICMP_ULT:
5835         // (float)int < -4.4   --> false
5836         // (float)int < 4.4    --> int <= 4
5837         if (RHS.isNegative())
5838           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5839         Pred = ICmpInst::ICMP_ULE;
5840         break;
5841       case ICmpInst::ICMP_SLT:
5842         // (float)int < -4.4   --> int < -4
5843         // (float)int < 4.4    --> int <= 4
5844         if (!RHS.isNegative())
5845           Pred = ICmpInst::ICMP_SLE;
5846         break;
5847       case ICmpInst::ICMP_UGT:
5848         // (float)int > 4.4    --> int > 4
5849         // (float)int > -4.4   --> true
5850         if (RHS.isNegative())
5851           return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5852         break;
5853       case ICmpInst::ICMP_SGT:
5854         // (float)int > 4.4    --> int > 4
5855         // (float)int > -4.4   --> int >= -4
5856         if (RHS.isNegative())
5857           Pred = ICmpInst::ICMP_SGE;
5858         break;
5859       case ICmpInst::ICMP_UGE:
5860         // (float)int >= -4.4   --> true
5861         // (float)int >= 4.4    --> int > 4
5862         if (!RHS.isNegative())
5863           return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5864         Pred = ICmpInst::ICMP_UGT;
5865         break;
5866       case ICmpInst::ICMP_SGE:
5867         // (float)int >= -4.4   --> int >= -4
5868         // (float)int >= 4.4    --> int > 4
5869         if (!RHS.isNegative())
5870           Pred = ICmpInst::ICMP_SGT;
5871         break;
5872       }
5873     }
5874   }
5875
5876   // Lower this FP comparison into an appropriate integer version of the
5877   // comparison.
5878   return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
5879 }
5880
5881 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5882   bool Changed = SimplifyCompare(I);
5883   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5884
5885   // Fold trivial predicates.
5886   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5887     return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5888   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5889     return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5890   
5891   // Simplify 'fcmp pred X, X'
5892   if (Op0 == Op1) {
5893     switch (I.getPredicate()) {
5894     default: llvm_unreachable("Unknown predicate!");
5895     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5896     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5897     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5898       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5899     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5900     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5901     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5902       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5903       
5904     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5905     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5906     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5907     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5908       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5909       I.setPredicate(FCmpInst::FCMP_UNO);
5910       I.setOperand(1, Context->getNullValue(Op0->getType()));
5911       return &I;
5912       
5913     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5914     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5915     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5916     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5917       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5918       I.setPredicate(FCmpInst::FCMP_ORD);
5919       I.setOperand(1, Context->getNullValue(Op0->getType()));
5920       return &I;
5921     }
5922   }
5923     
5924   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5925     return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5926
5927   // Handle fcmp with constant RHS
5928   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5929     // If the constant is a nan, see if we can fold the comparison based on it.
5930     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5931       if (CFP->getValueAPF().isNaN()) {
5932         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5933           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5934         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5935                "Comparison must be either ordered or unordered!");
5936         // True if unordered.
5937         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5938       }
5939     }
5940     
5941     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5942       switch (LHSI->getOpcode()) {
5943       case Instruction::PHI:
5944         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5945         // block.  If in the same block, we're encouraging jump threading.  If
5946         // not, we are just pessimizing the code by making an i1 phi.
5947         if (LHSI->getParent() == I.getParent())
5948           if (Instruction *NV = FoldOpIntoPhi(I))
5949             return NV;
5950         break;
5951       case Instruction::SIToFP:
5952       case Instruction::UIToFP:
5953         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5954           return NV;
5955         break;
5956       case Instruction::Select:
5957         // If either operand of the select is a constant, we can fold the
5958         // comparison into the select arms, which will cause one to be
5959         // constant folded and the select turned into a bitwise or.
5960         Value *Op1 = 0, *Op2 = 0;
5961         if (LHSI->hasOneUse()) {
5962           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5963             // Fold the known value into the constant operand.
5964             Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5965             // Insert a new FCmp of the other select operand.
5966             Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5967                                                       LHSI->getOperand(2), RHSC,
5968                                                       I.getName()), I);
5969           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5970             // Fold the known value into the constant operand.
5971             Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5972             // Insert a new FCmp of the other select operand.
5973             Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5974                                                       LHSI->getOperand(1), RHSC,
5975                                                       I.getName()), I);
5976           }
5977         }
5978
5979         if (Op1)
5980           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5981         break;
5982       }
5983   }
5984
5985   return Changed ? &I : 0;
5986 }
5987
5988 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5989   bool Changed = SimplifyCompare(I);
5990   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5991   const Type *Ty = Op0->getType();
5992
5993   // icmp X, X
5994   if (Op0 == Op1)
5995     return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty, 
5996                                                    I.isTrueWhenEqual()));
5997
5998   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5999     return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
6000   
6001   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
6002   // addresses never equal each other!  We already know that Op0 != Op1.
6003   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
6004        isa<ConstantPointerNull>(Op0)) &&
6005       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
6006        isa<ConstantPointerNull>(Op1)))
6007     return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty, 
6008                                                    !I.isTrueWhenEqual()));
6009
6010   // icmp's with boolean values can always be turned into bitwise operations
6011   if (Ty == Type::Int1Ty) {
6012     switch (I.getPredicate()) {
6013     default: llvm_unreachable("Invalid icmp instruction!");
6014     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
6015       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
6016       InsertNewInstBefore(Xor, I);
6017       return BinaryOperator::CreateNot(*Context, Xor);
6018     }
6019     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
6020       return BinaryOperator::CreateXor(Op0, Op1);
6021
6022     case ICmpInst::ICMP_UGT:
6023       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
6024       // FALL THROUGH
6025     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
6026       Instruction *Not = BinaryOperator::CreateNot(*Context,
6027                                                    Op0, I.getName()+"tmp");
6028       InsertNewInstBefore(Not, I);
6029       return BinaryOperator::CreateAnd(Not, Op1);
6030     }
6031     case ICmpInst::ICMP_SGT:
6032       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
6033       // FALL THROUGH
6034     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
6035       Instruction *Not = BinaryOperator::CreateNot(*Context, 
6036                                                    Op1, I.getName()+"tmp");
6037       InsertNewInstBefore(Not, I);
6038       return BinaryOperator::CreateAnd(Not, Op0);
6039     }
6040     case ICmpInst::ICMP_UGE:
6041       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6042       // FALL THROUGH
6043     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6044       Instruction *Not = BinaryOperator::CreateNot(*Context,
6045                                                    Op0, I.getName()+"tmp");
6046       InsertNewInstBefore(Not, I);
6047       return BinaryOperator::CreateOr(Not, Op1);
6048     }
6049     case ICmpInst::ICMP_SGE:
6050       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6051       // FALL THROUGH
6052     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6053       Instruction *Not = BinaryOperator::CreateNot(*Context,
6054                                                    Op1, I.getName()+"tmp");
6055       InsertNewInstBefore(Not, I);
6056       return BinaryOperator::CreateOr(Not, Op0);
6057     }
6058     }
6059   }
6060
6061   unsigned BitWidth = 0;
6062   if (TD)
6063     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6064   else if (Ty->isIntOrIntVector())
6065     BitWidth = Ty->getScalarSizeInBits();
6066
6067   bool isSignBit = false;
6068
6069   // See if we are doing a comparison with a constant.
6070   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6071     Value *A = 0, *B = 0;
6072     
6073     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6074     if (I.isEquality() && CI->isNullValue() &&
6075         match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
6076       // (icmp cond A B) if cond is equality
6077       return new ICmpInst(*Context, I.getPredicate(), A, B);
6078     }
6079     
6080     // If we have an icmp le or icmp ge instruction, turn it into the
6081     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6082     // them being folded in the code below.
6083     switch (I.getPredicate()) {
6084     default: break;
6085     case ICmpInst::ICMP_ULE:
6086       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
6087         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6088       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6089                           AddOne(CI, Context));
6090     case ICmpInst::ICMP_SLE:
6091       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
6092         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6093       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6094                           AddOne(CI, Context));
6095     case ICmpInst::ICMP_UGE:
6096       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
6097         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6098       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6099                           SubOne(CI, Context));
6100     case ICmpInst::ICMP_SGE:
6101       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
6102         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6103       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6104                           SubOne(CI, Context));
6105     }
6106     
6107     // If this comparison is a normal comparison, it demands all
6108     // bits, if it is a sign bit comparison, it only demands the sign bit.
6109     bool UnusedBit;
6110     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6111   }
6112
6113   // See if we can fold the comparison based on range information we can get
6114   // by checking whether bits are known to be zero or one in the input.
6115   if (BitWidth != 0) {
6116     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6117     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6118
6119     if (SimplifyDemandedBits(I.getOperandUse(0),
6120                              isSignBit ? APInt::getSignBit(BitWidth)
6121                                        : APInt::getAllOnesValue(BitWidth),
6122                              Op0KnownZero, Op0KnownOne, 0))
6123       return &I;
6124     if (SimplifyDemandedBits(I.getOperandUse(1),
6125                              APInt::getAllOnesValue(BitWidth),
6126                              Op1KnownZero, Op1KnownOne, 0))
6127       return &I;
6128
6129     // Given the known and unknown bits, compute a range that the LHS could be
6130     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6131     // EQ and NE we use unsigned values.
6132     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6133     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6134     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6135       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6136                                              Op0Min, Op0Max);
6137       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6138                                              Op1Min, Op1Max);
6139     } else {
6140       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6141                                                Op0Min, Op0Max);
6142       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6143                                                Op1Min, Op1Max);
6144     }
6145
6146     // If Min and Max are known to be the same, then SimplifyDemandedBits
6147     // figured out that the LHS is a constant.  Just constant fold this now so
6148     // that code below can assume that Min != Max.
6149     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6150       return new ICmpInst(*Context, I.getPredicate(),
6151                           Context->getConstantInt(Op0Min), Op1);
6152     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6153       return new ICmpInst(*Context, I.getPredicate(), Op0, 
6154                           Context->getConstantInt(Op1Min));
6155
6156     // Based on the range information we know about the LHS, see if we can
6157     // simplify this comparison.  For example, (x&4) < 8  is always true.
6158     switch (I.getPredicate()) {
6159     default: llvm_unreachable("Unknown icmp opcode!");
6160     case ICmpInst::ICMP_EQ:
6161       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6162         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6163       break;
6164     case ICmpInst::ICMP_NE:
6165       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6166         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6167       break;
6168     case ICmpInst::ICMP_ULT:
6169       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6170         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6171       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6172         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6173       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6174         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6175       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6176         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6177           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6178                               SubOne(CI, Context));
6179
6180         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6181         if (CI->isMinValue(true))
6182           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6183                            Context->getAllOnesValue(Op0->getType()));
6184       }
6185       break;
6186     case ICmpInst::ICMP_UGT:
6187       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6188         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6189       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6190         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6191
6192       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6193         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6194       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6195         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6196           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6197                               AddOne(CI, Context));
6198
6199         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6200         if (CI->isMaxValue(true))
6201           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6202                               Context->getNullValue(Op0->getType()));
6203       }
6204       break;
6205     case ICmpInst::ICMP_SLT:
6206       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6207         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6208       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6209         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6210       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6211         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6212       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6213         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6214           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6215                               SubOne(CI, Context));
6216       }
6217       break;
6218     case ICmpInst::ICMP_SGT:
6219       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6220         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6221       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6222         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6223
6224       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6225         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6226       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6227         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6228           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6229                               AddOne(CI, Context));
6230       }
6231       break;
6232     case ICmpInst::ICMP_SGE:
6233       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6234       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6235         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6236       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6237         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6238       break;
6239     case ICmpInst::ICMP_SLE:
6240       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6241       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6242         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6243       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6244         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6245       break;
6246     case ICmpInst::ICMP_UGE:
6247       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6248       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6249         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6250       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6251         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6252       break;
6253     case ICmpInst::ICMP_ULE:
6254       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6255       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6256         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6257       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6258         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6259       break;
6260     }
6261
6262     // Turn a signed comparison into an unsigned one if both operands
6263     // are known to have the same sign.
6264     if (I.isSignedPredicate() &&
6265         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6266          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6267       return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
6268   }
6269
6270   // Test if the ICmpInst instruction is used exclusively by a select as
6271   // part of a minimum or maximum operation. If so, refrain from doing
6272   // any other folding. This helps out other analyses which understand
6273   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6274   // and CodeGen. And in this case, at least one of the comparison
6275   // operands has at least one user besides the compare (the select),
6276   // which would often largely negate the benefit of folding anyway.
6277   if (I.hasOneUse())
6278     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6279       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6280           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6281         return 0;
6282
6283   // See if we are doing a comparison between a constant and an instruction that
6284   // can be folded into the comparison.
6285   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6286     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6287     // instruction, see if that instruction also has constants so that the 
6288     // instruction can be folded into the icmp 
6289     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6290       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6291         return Res;
6292   }
6293
6294   // Handle icmp with constant (but not simple integer constant) RHS
6295   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6296     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6297       switch (LHSI->getOpcode()) {
6298       case Instruction::GetElementPtr:
6299         if (RHSC->isNullValue()) {
6300           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6301           bool isAllZeros = true;
6302           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6303             if (!isa<Constant>(LHSI->getOperand(i)) ||
6304                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6305               isAllZeros = false;
6306               break;
6307             }
6308           if (isAllZeros)
6309             return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
6310                     Context->getNullValue(LHSI->getOperand(0)->getType()));
6311         }
6312         break;
6313
6314       case Instruction::PHI:
6315         // Only fold icmp into the PHI if the phi and fcmp are in the same
6316         // block.  If in the same block, we're encouraging jump threading.  If
6317         // not, we are just pessimizing the code by making an i1 phi.
6318         if (LHSI->getParent() == I.getParent())
6319           if (Instruction *NV = FoldOpIntoPhi(I))
6320             return NV;
6321         break;
6322       case Instruction::Select: {
6323         // If either operand of the select is a constant, we can fold the
6324         // comparison into the select arms, which will cause one to be
6325         // constant folded and the select turned into a bitwise or.
6326         Value *Op1 = 0, *Op2 = 0;
6327         if (LHSI->hasOneUse()) {
6328           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6329             // Fold the known value into the constant operand.
6330             Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6331             // Insert a new ICmp of the other select operand.
6332             Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6333                                                    LHSI->getOperand(2), RHSC,
6334                                                    I.getName()), I);
6335           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6336             // Fold the known value into the constant operand.
6337             Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6338             // Insert a new ICmp of the other select operand.
6339             Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6340                                                    LHSI->getOperand(1), RHSC,
6341                                                    I.getName()), I);
6342           }
6343         }
6344
6345         if (Op1)
6346           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6347         break;
6348       }
6349       case Instruction::Malloc:
6350         // If we have (malloc != null), and if the malloc has a single use, we
6351         // can assume it is successful and remove the malloc.
6352         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6353           AddToWorkList(LHSI);
6354           return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
6355                                                          !I.isTrueWhenEqual()));
6356         }
6357         break;
6358       }
6359   }
6360
6361   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6362   if (User *GEP = dyn_castGetElementPtr(Op0))
6363     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6364       return NI;
6365   if (User *GEP = dyn_castGetElementPtr(Op1))
6366     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6367                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6368       return NI;
6369
6370   // Test to see if the operands of the icmp are casted versions of other
6371   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6372   // now.
6373   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6374     if (isa<PointerType>(Op0->getType()) && 
6375         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6376       // We keep moving the cast from the left operand over to the right
6377       // operand, where it can often be eliminated completely.
6378       Op0 = CI->getOperand(0);
6379
6380       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6381       // so eliminate it as well.
6382       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6383         Op1 = CI2->getOperand(0);
6384
6385       // If Op1 is a constant, we can fold the cast into the constant.
6386       if (Op0->getType() != Op1->getType()) {
6387         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6388           Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
6389         } else {
6390           // Otherwise, cast the RHS right before the icmp
6391           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6392         }
6393       }
6394       return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
6395     }
6396   }
6397   
6398   if (isa<CastInst>(Op0)) {
6399     // Handle the special case of: icmp (cast bool to X), <cst>
6400     // This comes up when you have code like
6401     //   int X = A < B;
6402     //   if (X) ...
6403     // For generality, we handle any zero-extension of any operand comparison
6404     // with a constant or another cast from the same type.
6405     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6406       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6407         return R;
6408   }
6409   
6410   // See if it's the same type of instruction on the left and right.
6411   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6412     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6413       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6414           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6415         switch (Op0I->getOpcode()) {
6416         default: break;
6417         case Instruction::Add:
6418         case Instruction::Sub:
6419         case Instruction::Xor:
6420           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6421             return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
6422                                 Op1I->getOperand(0));
6423           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6424           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6425             if (CI->getValue().isSignBit()) {
6426               ICmpInst::Predicate Pred = I.isSignedPredicate()
6427                                              ? I.getUnsignedPredicate()
6428                                              : I.getSignedPredicate();
6429               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6430                                   Op1I->getOperand(0));
6431             }
6432             
6433             if (CI->getValue().isMaxSignedValue()) {
6434               ICmpInst::Predicate Pred = I.isSignedPredicate()
6435                                              ? I.getUnsignedPredicate()
6436                                              : I.getSignedPredicate();
6437               Pred = I.getSwappedPredicate(Pred);
6438               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6439                                   Op1I->getOperand(0));
6440             }
6441           }
6442           break;
6443         case Instruction::Mul:
6444           if (!I.isEquality())
6445             break;
6446
6447           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6448             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6449             // Mask = -1 >> count-trailing-zeros(Cst).
6450             if (!CI->isZero() && !CI->isOne()) {
6451               const APInt &AP = CI->getValue();
6452               ConstantInt *Mask = Context->getConstantInt(
6453                                       APInt::getLowBitsSet(AP.getBitWidth(),
6454                                                            AP.getBitWidth() -
6455                                                       AP.countTrailingZeros()));
6456               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6457                                                             Mask);
6458               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6459                                                             Mask);
6460               InsertNewInstBefore(And1, I);
6461               InsertNewInstBefore(And2, I);
6462               return new ICmpInst(*Context, I.getPredicate(), And1, And2);
6463             }
6464           }
6465           break;
6466         }
6467       }
6468     }
6469   }
6470   
6471   // ~x < ~y --> y < x
6472   { Value *A, *B;
6473     if (match(Op0, m_Not(m_Value(A)), *Context) &&
6474         match(Op1, m_Not(m_Value(B)), *Context))
6475       return new ICmpInst(*Context, I.getPredicate(), B, A);
6476   }
6477   
6478   if (I.isEquality()) {
6479     Value *A, *B, *C, *D;
6480     
6481     // -x == -y --> x == y
6482     if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6483         match(Op1, m_Neg(m_Value(B)), *Context))
6484       return new ICmpInst(*Context, I.getPredicate(), A, B);
6485     
6486     if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
6487       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6488         Value *OtherVal = A == Op1 ? B : A;
6489         return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6490                             Context->getNullValue(A->getType()));
6491       }
6492
6493       if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
6494         // A^c1 == C^c2 --> A == C^(c1^c2)
6495         ConstantInt *C1, *C2;
6496         if (match(B, m_ConstantInt(C1), *Context) &&
6497             match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
6498           Constant *NC = 
6499                        Context->getConstantInt(C1->getValue() ^ C2->getValue());
6500           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6501           return new ICmpInst(*Context, I.getPredicate(), A,
6502                               InsertNewInstBefore(Xor, I));
6503         }
6504         
6505         // A^B == A^D -> B == D
6506         if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6507         if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6508         if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6509         if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
6510       }
6511     }
6512     
6513     if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
6514         (A == Op0 || B == Op0)) {
6515       // A == (A^B)  ->  B == 0
6516       Value *OtherVal = A == Op0 ? B : A;
6517       return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6518                           Context->getNullValue(A->getType()));
6519     }
6520
6521     // (A-B) == A  ->  B == 0
6522     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
6523       return new ICmpInst(*Context, I.getPredicate(), B, 
6524                           Context->getNullValue(B->getType()));
6525
6526     // A == (A-B)  ->  B == 0
6527     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
6528       return new ICmpInst(*Context, I.getPredicate(), B,
6529                           Context->getNullValue(B->getType()));
6530     
6531     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6532     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6533         match(Op0, m_And(m_Value(A), m_Value(B)), *Context) && 
6534         match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
6535       Value *X = 0, *Y = 0, *Z = 0;
6536       
6537       if (A == C) {
6538         X = B; Y = D; Z = A;
6539       } else if (A == D) {
6540         X = B; Y = C; Z = A;
6541       } else if (B == C) {
6542         X = A; Y = D; Z = B;
6543       } else if (B == D) {
6544         X = A; Y = C; Z = B;
6545       }
6546       
6547       if (X) {   // Build (X^Y) & Z
6548         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6549         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6550         I.setOperand(0, Op1);
6551         I.setOperand(1, Context->getNullValue(Op1->getType()));
6552         return &I;
6553       }
6554     }
6555   }
6556   return Changed ? &I : 0;
6557 }
6558
6559
6560 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6561 /// and CmpRHS are both known to be integer constants.
6562 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6563                                           ConstantInt *DivRHS) {
6564   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6565   const APInt &CmpRHSV = CmpRHS->getValue();
6566   
6567   // FIXME: If the operand types don't match the type of the divide 
6568   // then don't attempt this transform. The code below doesn't have the
6569   // logic to deal with a signed divide and an unsigned compare (and
6570   // vice versa). This is because (x /s C1) <s C2  produces different 
6571   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6572   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6573   // work. :(  The if statement below tests that condition and bails 
6574   // if it finds it. 
6575   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6576   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6577     return 0;
6578   if (DivRHS->isZero())
6579     return 0; // The ProdOV computation fails on divide by zero.
6580   if (DivIsSigned && DivRHS->isAllOnesValue())
6581     return 0; // The overflow computation also screws up here
6582   if (DivRHS->isOne())
6583     return 0; // Not worth bothering, and eliminates some funny cases
6584               // with INT_MIN.
6585
6586   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6587   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6588   // C2 (CI). By solving for X we can turn this into a range check 
6589   // instead of computing a divide. 
6590   Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
6591
6592   // Determine if the product overflows by seeing if the product is
6593   // not equal to the divide. Make sure we do the same kind of divide
6594   // as in the LHS instruction that we're folding. 
6595   bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6596                  Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
6597
6598   // Get the ICmp opcode
6599   ICmpInst::Predicate Pred = ICI.getPredicate();
6600
6601   // Figure out the interval that is being checked.  For example, a comparison
6602   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6603   // Compute this interval based on the constants involved and the signedness of
6604   // the compare/divide.  This computes a half-open interval, keeping track of
6605   // whether either value in the interval overflows.  After analysis each
6606   // overflow variable is set to 0 if it's corresponding bound variable is valid
6607   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6608   int LoOverflow = 0, HiOverflow = 0;
6609   Constant *LoBound = 0, *HiBound = 0;
6610   
6611   if (!DivIsSigned) {  // udiv
6612     // e.g. X/5 op 3  --> [15, 20)
6613     LoBound = Prod;
6614     HiOverflow = LoOverflow = ProdOV;
6615     if (!HiOverflow)
6616       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6617   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6618     if (CmpRHSV == 0) {       // (X / pos) op 0
6619       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6620       LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS, 
6621                                                                     Context)));
6622       HiBound = DivRHS;
6623     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6624       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6625       HiOverflow = LoOverflow = ProdOV;
6626       if (!HiOverflow)
6627         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6628     } else {                       // (X / pos) op neg
6629       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6630       HiBound = AddOne(Prod, Context);
6631       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6632       if (!LoOverflow) {
6633         ConstantInt* DivNeg =
6634                          cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6635         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6636                                      true) ? -1 : 0;
6637        }
6638     }
6639   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6640     if (CmpRHSV == 0) {       // (X / neg) op 0
6641       // e.g. X/-5 op 0  --> [-4, 5)
6642       LoBound = AddOne(DivRHS, Context);
6643       HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6644       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6645         HiOverflow = 1;            // [INTMIN+1, overflow)
6646         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6647       }
6648     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6649       // e.g. X/-5 op 3  --> [-19, -14)
6650       HiBound = AddOne(Prod, Context);
6651       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6652       if (!LoOverflow)
6653         LoOverflow = AddWithOverflow(LoBound, HiBound,
6654                                      DivRHS, Context, true) ? -1 : 0;
6655     } else {                       // (X / neg) op neg
6656       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6657       LoOverflow = HiOverflow = ProdOV;
6658       if (!HiOverflow)
6659         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6660     }
6661     
6662     // Dividing by a negative swaps the condition.  LT <-> GT
6663     Pred = ICmpInst::getSwappedPredicate(Pred);
6664   }
6665
6666   Value *X = DivI->getOperand(0);
6667   switch (Pred) {
6668   default: llvm_unreachable("Unhandled icmp opcode!");
6669   case ICmpInst::ICMP_EQ:
6670     if (LoOverflow && HiOverflow)
6671       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6672     else if (HiOverflow)
6673       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6674                           ICmpInst::ICMP_UGE, X, LoBound);
6675     else if (LoOverflow)
6676       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6677                           ICmpInst::ICMP_ULT, X, HiBound);
6678     else
6679       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6680   case ICmpInst::ICMP_NE:
6681     if (LoOverflow && HiOverflow)
6682       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6683     else if (HiOverflow)
6684       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6685                           ICmpInst::ICMP_ULT, X, LoBound);
6686     else if (LoOverflow)
6687       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6688                           ICmpInst::ICMP_UGE, X, HiBound);
6689     else
6690       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6691   case ICmpInst::ICMP_ULT:
6692   case ICmpInst::ICMP_SLT:
6693     if (LoOverflow == +1)   // Low bound is greater than input range.
6694       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6695     if (LoOverflow == -1)   // Low bound is less than input range.
6696       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6697     return new ICmpInst(*Context, Pred, X, LoBound);
6698   case ICmpInst::ICMP_UGT:
6699   case ICmpInst::ICMP_SGT:
6700     if (HiOverflow == +1)       // High bound greater than input range.
6701       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6702     else if (HiOverflow == -1)  // High bound less than input range.
6703       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6704     if (Pred == ICmpInst::ICMP_UGT)
6705       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
6706     else
6707       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
6708   }
6709 }
6710
6711
6712 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6713 ///
6714 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6715                                                           Instruction *LHSI,
6716                                                           ConstantInt *RHS) {
6717   const APInt &RHSV = RHS->getValue();
6718   
6719   switch (LHSI->getOpcode()) {
6720   case Instruction::Trunc:
6721     if (ICI.isEquality() && LHSI->hasOneUse()) {
6722       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6723       // of the high bits truncated out of x are known.
6724       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6725              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6726       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6727       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6728       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6729       
6730       // If all the high bits are known, we can do this xform.
6731       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6732         // Pull in the high bits from known-ones set.
6733         APInt NewRHS(RHS->getValue());
6734         NewRHS.zext(SrcBits);
6735         NewRHS |= KnownOne;
6736         return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
6737                             Context->getConstantInt(NewRHS));
6738       }
6739     }
6740     break;
6741       
6742   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6743     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6744       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6745       // fold the xor.
6746       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6747           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6748         Value *CompareVal = LHSI->getOperand(0);
6749         
6750         // If the sign bit of the XorCST is not set, there is no change to
6751         // the operation, just stop using the Xor.
6752         if (!XorCST->getValue().isNegative()) {
6753           ICI.setOperand(0, CompareVal);
6754           AddToWorkList(LHSI);
6755           return &ICI;
6756         }
6757         
6758         // Was the old condition true if the operand is positive?
6759         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6760         
6761         // If so, the new one isn't.
6762         isTrueIfPositive ^= true;
6763         
6764         if (isTrueIfPositive)
6765           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
6766                               SubOne(RHS, Context));
6767         else
6768           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
6769                               AddOne(RHS, Context));
6770       }
6771
6772       if (LHSI->hasOneUse()) {
6773         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6774         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6775           const APInt &SignBit = XorCST->getValue();
6776           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6777                                          ? ICI.getUnsignedPredicate()
6778                                          : ICI.getSignedPredicate();
6779           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6780                               Context->getConstantInt(RHSV ^ SignBit));
6781         }
6782
6783         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6784         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6785           const APInt &NotSignBit = XorCST->getValue();
6786           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6787                                          ? ICI.getUnsignedPredicate()
6788                                          : ICI.getSignedPredicate();
6789           Pred = ICI.getSwappedPredicate(Pred);
6790           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6791                               Context->getConstantInt(RHSV ^ NotSignBit));
6792         }
6793       }
6794     }
6795     break;
6796   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6797     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6798         LHSI->getOperand(0)->hasOneUse()) {
6799       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6800       
6801       // If the LHS is an AND of a truncating cast, we can widen the
6802       // and/compare to be the input width without changing the value
6803       // produced, eliminating a cast.
6804       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6805         // We can do this transformation if either the AND constant does not
6806         // have its sign bit set or if it is an equality comparison. 
6807         // Extending a relational comparison when we're checking the sign
6808         // bit would not work.
6809         if (Cast->hasOneUse() &&
6810             (ICI.isEquality() ||
6811              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6812           uint32_t BitWidth = 
6813             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6814           APInt NewCST = AndCST->getValue();
6815           NewCST.zext(BitWidth);
6816           APInt NewCI = RHSV;
6817           NewCI.zext(BitWidth);
6818           Instruction *NewAnd = 
6819             BinaryOperator::CreateAnd(Cast->getOperand(0),
6820                                Context->getConstantInt(NewCST),LHSI->getName());
6821           InsertNewInstBefore(NewAnd, ICI);
6822           return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
6823                               Context->getConstantInt(NewCI));
6824         }
6825       }
6826       
6827       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6828       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6829       // happens a LOT in code produced by the C front-end, for bitfield
6830       // access.
6831       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6832       if (Shift && !Shift->isShift())
6833         Shift = 0;
6834       
6835       ConstantInt *ShAmt;
6836       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6837       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6838       const Type *AndTy = AndCST->getType();          // Type of the and.
6839       
6840       // We can fold this as long as we can't shift unknown bits
6841       // into the mask.  This can only happen with signed shift
6842       // rights, as they sign-extend.
6843       if (ShAmt) {
6844         bool CanFold = Shift->isLogicalShift();
6845         if (!CanFold) {
6846           // To test for the bad case of the signed shr, see if any
6847           // of the bits shifted in could be tested after the mask.
6848           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6849           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6850           
6851           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6852           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6853                AndCST->getValue()) == 0)
6854             CanFold = true;
6855         }
6856         
6857         if (CanFold) {
6858           Constant *NewCst;
6859           if (Shift->getOpcode() == Instruction::Shl)
6860             NewCst = Context->getConstantExprLShr(RHS, ShAmt);
6861           else
6862             NewCst = Context->getConstantExprShl(RHS, ShAmt);
6863           
6864           // Check to see if we are shifting out any of the bits being
6865           // compared.
6866           if (Context->getConstantExpr(Shift->getOpcode(),
6867                                        NewCst, ShAmt) != RHS) {
6868             // If we shifted bits out, the fold is not going to work out.
6869             // As a special case, check to see if this means that the
6870             // result is always true or false now.
6871             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6872               return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6873             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6874               return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6875           } else {
6876             ICI.setOperand(1, NewCst);
6877             Constant *NewAndCST;
6878             if (Shift->getOpcode() == Instruction::Shl)
6879               NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
6880             else
6881               NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
6882             LHSI->setOperand(1, NewAndCST);
6883             LHSI->setOperand(0, Shift->getOperand(0));
6884             AddToWorkList(Shift); // Shift is dead.
6885             AddUsesToWorkList(ICI);
6886             return &ICI;
6887           }
6888         }
6889       }
6890       
6891       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6892       // preferable because it allows the C<<Y expression to be hoisted out
6893       // of a loop if Y is invariant and X is not.
6894       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6895           ICI.isEquality() && !Shift->isArithmeticShift() &&
6896           !isa<Constant>(Shift->getOperand(0))) {
6897         // Compute C << Y.
6898         Value *NS;
6899         if (Shift->getOpcode() == Instruction::LShr) {
6900           NS = BinaryOperator::CreateShl(AndCST, 
6901                                          Shift->getOperand(1), "tmp");
6902         } else {
6903           // Insert a logical shift.
6904           NS = BinaryOperator::CreateLShr(AndCST,
6905                                           Shift->getOperand(1), "tmp");
6906         }
6907         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6908         
6909         // Compute X & (C << Y).
6910         Instruction *NewAnd = 
6911           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6912         InsertNewInstBefore(NewAnd, ICI);
6913         
6914         ICI.setOperand(0, NewAnd);
6915         return &ICI;
6916       }
6917     }
6918     break;
6919     
6920   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6921     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6922     if (!ShAmt) break;
6923     
6924     uint32_t TypeBits = RHSV.getBitWidth();
6925     
6926     // Check that the shift amount is in range.  If not, don't perform
6927     // undefined shifts.  When the shift is visited it will be
6928     // simplified.
6929     if (ShAmt->uge(TypeBits))
6930       break;
6931     
6932     if (ICI.isEquality()) {
6933       // If we are comparing against bits always shifted out, the
6934       // comparison cannot succeed.
6935       Constant *Comp =
6936         Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6937                                                                  ShAmt);
6938       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6939         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6940         Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
6941         return ReplaceInstUsesWith(ICI, Cst);
6942       }
6943       
6944       if (LHSI->hasOneUse()) {
6945         // Otherwise strength reduce the shift into an and.
6946         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6947         Constant *Mask =
6948           Context->getConstantInt(APInt::getLowBitsSet(TypeBits, 
6949                                                        TypeBits-ShAmtVal));
6950         
6951         Instruction *AndI =
6952           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6953                                     Mask, LHSI->getName()+".mask");
6954         Value *And = InsertNewInstBefore(AndI, ICI);
6955         return new ICmpInst(*Context, ICI.getPredicate(), And,
6956                             Context->getConstantInt(RHSV.lshr(ShAmtVal)));
6957       }
6958     }
6959     
6960     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6961     bool TrueIfSigned = false;
6962     if (LHSI->hasOneUse() &&
6963         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6964       // (X << 31) <s 0  --> (X&1) != 0
6965       Constant *Mask = Context->getConstantInt(APInt(TypeBits, 1) <<
6966                                            (TypeBits-ShAmt->getZExtValue()-1));
6967       Instruction *AndI =
6968         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6969                                   Mask, LHSI->getName()+".mask");
6970       Value *And = InsertNewInstBefore(AndI, ICI);
6971       
6972       return new ICmpInst(*Context,
6973                           TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6974                           And, Context->getNullValue(And->getType()));
6975     }
6976     break;
6977   }
6978     
6979   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6980   case Instruction::AShr: {
6981     // Only handle equality comparisons of shift-by-constant.
6982     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6983     if (!ShAmt || !ICI.isEquality()) break;
6984
6985     // Check that the shift amount is in range.  If not, don't perform
6986     // undefined shifts.  When the shift is visited it will be
6987     // simplified.
6988     uint32_t TypeBits = RHSV.getBitWidth();
6989     if (ShAmt->uge(TypeBits))
6990       break;
6991     
6992     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6993       
6994     // If we are comparing against bits always shifted out, the
6995     // comparison cannot succeed.
6996     APInt Comp = RHSV << ShAmtVal;
6997     if (LHSI->getOpcode() == Instruction::LShr)
6998       Comp = Comp.lshr(ShAmtVal);
6999     else
7000       Comp = Comp.ashr(ShAmtVal);
7001     
7002     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7003       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7004       Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
7005       return ReplaceInstUsesWith(ICI, Cst);
7006     }
7007     
7008     // Otherwise, check to see if the bits shifted out are known to be zero.
7009     // If so, we can compare against the unshifted value:
7010     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
7011     if (LHSI->hasOneUse() &&
7012         MaskedValueIsZero(LHSI->getOperand(0), 
7013                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
7014       return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
7015                           Context->getConstantExprShl(RHS, ShAmt));
7016     }
7017       
7018     if (LHSI->hasOneUse()) {
7019       // Otherwise strength reduce the shift into an and.
7020       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
7021       Constant *Mask = Context->getConstantInt(Val);
7022       
7023       Instruction *AndI =
7024         BinaryOperator::CreateAnd(LHSI->getOperand(0),
7025                                   Mask, LHSI->getName()+".mask");
7026       Value *And = InsertNewInstBefore(AndI, ICI);
7027       return new ICmpInst(*Context, ICI.getPredicate(), And,
7028                           Context->getConstantExprShl(RHS, ShAmt));
7029     }
7030     break;
7031   }
7032     
7033   case Instruction::SDiv:
7034   case Instruction::UDiv:
7035     // Fold: icmp pred ([us]div X, C1), C2 -> range test
7036     // Fold this div into the comparison, producing a range check. 
7037     // Determine, based on the divide type, what the range is being 
7038     // checked.  If there is an overflow on the low or high side, remember 
7039     // it, otherwise compute the range [low, hi) bounding the new value.
7040     // See: InsertRangeTest above for the kinds of replacements possible.
7041     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7042       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7043                                           DivRHS))
7044         return R;
7045     break;
7046
7047   case Instruction::Add:
7048     // Fold: icmp pred (add, X, C1), C2
7049
7050     if (!ICI.isEquality()) {
7051       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7052       if (!LHSC) break;
7053       const APInt &LHSV = LHSC->getValue();
7054
7055       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7056                             .subtract(LHSV);
7057
7058       if (ICI.isSignedPredicate()) {
7059         if (CR.getLower().isSignBit()) {
7060           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7061                               Context->getConstantInt(CR.getUpper()));
7062         } else if (CR.getUpper().isSignBit()) {
7063           return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7064                               Context->getConstantInt(CR.getLower()));
7065         }
7066       } else {
7067         if (CR.getLower().isMinValue()) {
7068           return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7069                               Context->getConstantInt(CR.getUpper()));
7070         } else if (CR.getUpper().isMinValue()) {
7071           return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7072                               Context->getConstantInt(CR.getLower()));
7073         }
7074       }
7075     }
7076     break;
7077   }
7078   
7079   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7080   if (ICI.isEquality()) {
7081     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7082     
7083     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7084     // the second operand is a constant, simplify a bit.
7085     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7086       switch (BO->getOpcode()) {
7087       case Instruction::SRem:
7088         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7089         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7090           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7091           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7092             Instruction *NewRem =
7093               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
7094                                          BO->getName());
7095             InsertNewInstBefore(NewRem, ICI);
7096             return new ICmpInst(*Context, ICI.getPredicate(), NewRem, 
7097                                 Context->getNullValue(BO->getType()));
7098           }
7099         }
7100         break;
7101       case Instruction::Add:
7102         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7103         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7104           if (BO->hasOneUse())
7105             return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7106                                 Context->getConstantExprSub(RHS, BOp1C));
7107         } else if (RHSV == 0) {
7108           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7109           // efficiently invertible, or if the add has just this one use.
7110           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7111           
7112           if (Value *NegVal = dyn_castNegVal(BOp1, Context))
7113             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
7114           else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
7115             return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
7116           else if (BO->hasOneUse()) {
7117             Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
7118             InsertNewInstBefore(Neg, ICI);
7119             Neg->takeName(BO);
7120             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
7121           }
7122         }
7123         break;
7124       case Instruction::Xor:
7125         // For the xor case, we can xor two constants together, eliminating
7126         // the explicit xor.
7127         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7128           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0), 
7129                               Context->getConstantExprXor(RHS, BOC));
7130         
7131         // FALLTHROUGH
7132       case Instruction::Sub:
7133         // Replace (([sub|xor] A, B) != 0) with (A != B)
7134         if (RHSV == 0)
7135           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7136                               BO->getOperand(1));
7137         break;
7138         
7139       case Instruction::Or:
7140         // If bits are being or'd in that are not present in the constant we
7141         // are comparing against, then the comparison could never succeed!
7142         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7143           Constant *NotCI = Context->getConstantExprNot(RHS);
7144           if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7145             return ReplaceInstUsesWith(ICI,
7146                                        Context->getConstantInt(Type::Int1Ty, 
7147                                        isICMP_NE));
7148         }
7149         break;
7150         
7151       case Instruction::And:
7152         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7153           // If bits are being compared against that are and'd out, then the
7154           // comparison can never succeed!
7155           if ((RHSV & ~BOC->getValue()) != 0)
7156             return ReplaceInstUsesWith(ICI,
7157                                        Context->getConstantInt(Type::Int1Ty,
7158                                        isICMP_NE));
7159           
7160           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7161           if (RHS == BOC && RHSV.isPowerOf2())
7162             return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
7163                                 ICmpInst::ICMP_NE, LHSI,
7164                                 Context->getNullValue(RHS->getType()));
7165           
7166           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7167           if (BOC->getValue().isSignBit()) {
7168             Value *X = BO->getOperand(0);
7169             Constant *Zero = Context->getNullValue(X->getType());
7170             ICmpInst::Predicate pred = isICMP_NE ? 
7171               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7172             return new ICmpInst(*Context, pred, X, Zero);
7173           }
7174           
7175           // ((X & ~7) == 0) --> X < 8
7176           if (RHSV == 0 && isHighOnes(BOC)) {
7177             Value *X = BO->getOperand(0);
7178             Constant *NegX = Context->getConstantExprNeg(BOC);
7179             ICmpInst::Predicate pred = isICMP_NE ? 
7180               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7181             return new ICmpInst(*Context, pred, X, NegX);
7182           }
7183         }
7184       default: break;
7185       }
7186     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7187       // Handle icmp {eq|ne} <intrinsic>, intcst.
7188       if (II->getIntrinsicID() == Intrinsic::bswap) {
7189         AddToWorkList(II);
7190         ICI.setOperand(0, II->getOperand(1));
7191         ICI.setOperand(1, Context->getConstantInt(RHSV.byteSwap()));
7192         return &ICI;
7193       }
7194     }
7195   }
7196   return 0;
7197 }
7198
7199 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7200 /// We only handle extending casts so far.
7201 ///
7202 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7203   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7204   Value *LHSCIOp        = LHSCI->getOperand(0);
7205   const Type *SrcTy     = LHSCIOp->getType();
7206   const Type *DestTy    = LHSCI->getType();
7207   Value *RHSCIOp;
7208
7209   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7210   // integer type is the same size as the pointer type.
7211   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7212       getTargetData().getPointerSizeInBits() == 
7213          cast<IntegerType>(DestTy)->getBitWidth()) {
7214     Value *RHSOp = 0;
7215     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7216       RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
7217     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7218       RHSOp = RHSC->getOperand(0);
7219       // If the pointer types don't match, insert a bitcast.
7220       if (LHSCIOp->getType() != RHSOp->getType())
7221         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
7222     }
7223
7224     if (RHSOp)
7225       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
7226   }
7227   
7228   // The code below only handles extension cast instructions, so far.
7229   // Enforce this.
7230   if (LHSCI->getOpcode() != Instruction::ZExt &&
7231       LHSCI->getOpcode() != Instruction::SExt)
7232     return 0;
7233
7234   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7235   bool isSignedCmp = ICI.isSignedPredicate();
7236
7237   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7238     // Not an extension from the same type?
7239     RHSCIOp = CI->getOperand(0);
7240     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7241       return 0;
7242     
7243     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7244     // and the other is a zext), then we can't handle this.
7245     if (CI->getOpcode() != LHSCI->getOpcode())
7246       return 0;
7247
7248     // Deal with equality cases early.
7249     if (ICI.isEquality())
7250       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7251
7252     // A signed comparison of sign extended values simplifies into a
7253     // signed comparison.
7254     if (isSignedCmp && isSignedExt)
7255       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7256
7257     // The other three cases all fold into an unsigned comparison.
7258     return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7259   }
7260
7261   // If we aren't dealing with a constant on the RHS, exit early
7262   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7263   if (!CI)
7264     return 0;
7265
7266   // Compute the constant that would happen if we truncated to SrcTy then
7267   // reextended to DestTy.
7268   Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7269   Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7270                                                 Res1, DestTy);
7271
7272   // If the re-extended constant didn't change...
7273   if (Res2 == CI) {
7274     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7275     // For example, we might have:
7276     //    %A = sext i16 %X to i32
7277     //    %B = icmp ugt i32 %A, 1330
7278     // It is incorrect to transform this into 
7279     //    %B = icmp ugt i16 %X, 1330
7280     // because %A may have negative value. 
7281     //
7282     // However, we allow this when the compare is EQ/NE, because they are
7283     // signless.
7284     if (isSignedExt == isSignedCmp || ICI.isEquality())
7285       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
7286     return 0;
7287   }
7288
7289   // The re-extended constant changed so the constant cannot be represented 
7290   // in the shorter type. Consequently, we cannot emit a simple comparison.
7291
7292   // First, handle some easy cases. We know the result cannot be equal at this
7293   // point so handle the ICI.isEquality() cases
7294   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7295     return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
7296   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7297     return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
7298
7299   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7300   // should have been folded away previously and not enter in here.
7301   Value *Result;
7302   if (isSignedCmp) {
7303     // We're performing a signed comparison.
7304     if (cast<ConstantInt>(CI)->getValue().isNegative())
7305       Result = Context->getConstantIntFalse();          // X < (small) --> false
7306     else
7307       Result = Context->getConstantIntTrue();           // X < (large) --> true
7308   } else {
7309     // We're performing an unsigned comparison.
7310     if (isSignedExt) {
7311       // We're performing an unsigned comp with a sign extended value.
7312       // This is true if the input is >= 0. [aka >s -1]
7313       Constant *NegOne = Context->getAllOnesValue(SrcTy);
7314       Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT, 
7315                                    LHSCIOp, NegOne, ICI.getName()), ICI);
7316     } else {
7317       // Unsigned extend & unsigned compare -> always true.
7318       Result = Context->getConstantIntTrue();
7319     }
7320   }
7321
7322   // Finally, return the value computed.
7323   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7324       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7325     return ReplaceInstUsesWith(ICI, Result);
7326
7327   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7328           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7329          "ICmp should be folded!");
7330   if (Constant *CI = dyn_cast<Constant>(Result))
7331     return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
7332   return BinaryOperator::CreateNot(*Context, Result);
7333 }
7334
7335 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7336   return commonShiftTransforms(I);
7337 }
7338
7339 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7340   return commonShiftTransforms(I);
7341 }
7342
7343 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7344   if (Instruction *R = commonShiftTransforms(I))
7345     return R;
7346   
7347   Value *Op0 = I.getOperand(0);
7348   
7349   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7350   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7351     if (CSI->isAllOnesValue())
7352       return ReplaceInstUsesWith(I, CSI);
7353
7354   // See if we can turn a signed shr into an unsigned shr.
7355   if (MaskedValueIsZero(Op0,
7356                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7357     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7358
7359   // Arithmetic shifting an all-sign-bit value is a no-op.
7360   unsigned NumSignBits = ComputeNumSignBits(Op0);
7361   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7362     return ReplaceInstUsesWith(I, Op0);
7363
7364   return 0;
7365 }
7366
7367 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7368   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7369   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7370
7371   // shl X, 0 == X and shr X, 0 == X
7372   // shl 0, X == 0 and shr 0, X == 0
7373   if (Op1 == Context->getNullValue(Op1->getType()) ||
7374       Op0 == Context->getNullValue(Op0->getType()))
7375     return ReplaceInstUsesWith(I, Op0);
7376   
7377   if (isa<UndefValue>(Op0)) {            
7378     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7379       return ReplaceInstUsesWith(I, Op0);
7380     else                                    // undef << X -> 0, undef >>u X -> 0
7381       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7382   }
7383   if (isa<UndefValue>(Op1)) {
7384     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7385       return ReplaceInstUsesWith(I, Op0);          
7386     else                                     // X << undef, X >>u undef -> 0
7387       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7388   }
7389
7390   // See if we can fold away this shift.
7391   if (SimplifyDemandedInstructionBits(I))
7392     return &I;
7393
7394   // Try to fold constant and into select arguments.
7395   if (isa<Constant>(Op0))
7396     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7397       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7398         return R;
7399
7400   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7401     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7402       return Res;
7403   return 0;
7404 }
7405
7406 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7407                                                BinaryOperator &I) {
7408   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7409
7410   // See if we can simplify any instructions used by the instruction whose sole 
7411   // purpose is to compute bits we don't care about.
7412   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7413   
7414   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7415   // a signed shift.
7416   //
7417   if (Op1->uge(TypeBits)) {
7418     if (I.getOpcode() != Instruction::AShr)
7419       return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
7420     else {
7421       I.setOperand(1, Context->getConstantInt(I.getType(), TypeBits-1));
7422       return &I;
7423     }
7424   }
7425   
7426   // ((X*C1) << C2) == (X * (C1 << C2))
7427   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7428     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7429       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7430         return BinaryOperator::CreateMul(BO->getOperand(0),
7431                                         Context->getConstantExprShl(BOOp, Op1));
7432   
7433   // Try to fold constant and into select arguments.
7434   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7435     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7436       return R;
7437   if (isa<PHINode>(Op0))
7438     if (Instruction *NV = FoldOpIntoPhi(I))
7439       return NV;
7440   
7441   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7442   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7443     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7444     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7445     // place.  Don't try to do this transformation in this case.  Also, we
7446     // require that the input operand is a shift-by-constant so that we have
7447     // confidence that the shifts will get folded together.  We could do this
7448     // xform in more cases, but it is unlikely to be profitable.
7449     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7450         isa<ConstantInt>(TrOp->getOperand(1))) {
7451       // Okay, we'll do this xform.  Make the shift of shift.
7452       Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
7453       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7454                                                 I.getName());
7455       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7456
7457       // For logical shifts, the truncation has the effect of making the high
7458       // part of the register be zeros.  Emulate this by inserting an AND to
7459       // clear the top bits as needed.  This 'and' will usually be zapped by
7460       // other xforms later if dead.
7461       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7462       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7463       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7464       
7465       // The mask we constructed says what the trunc would do if occurring
7466       // between the shifts.  We want to know the effect *after* the second
7467       // shift.  We know that it is a logical shift by a constant, so adjust the
7468       // mask as appropriate.
7469       if (I.getOpcode() == Instruction::Shl)
7470         MaskV <<= Op1->getZExtValue();
7471       else {
7472         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7473         MaskV = MaskV.lshr(Op1->getZExtValue());
7474       }
7475
7476       Instruction *And =
7477         BinaryOperator::CreateAnd(NSh, Context->getConstantInt(MaskV), 
7478                                   TI->getName());
7479       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7480
7481       // Return the value truncated to the interesting size.
7482       return new TruncInst(And, I.getType());
7483     }
7484   }
7485   
7486   if (Op0->hasOneUse()) {
7487     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7488       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7489       Value *V1, *V2;
7490       ConstantInt *CC;
7491       switch (Op0BO->getOpcode()) {
7492         default: break;
7493         case Instruction::Add:
7494         case Instruction::And:
7495         case Instruction::Or:
7496         case Instruction::Xor: {
7497           // These operators commute.
7498           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7499           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7500               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7501                     m_Specific(Op1)), *Context)){
7502             Instruction *YS = BinaryOperator::CreateShl(
7503                                             Op0BO->getOperand(0), Op1,
7504                                             Op0BO->getName());
7505             InsertNewInstBefore(YS, I); // (Y << C)
7506             Instruction *X = 
7507               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7508                                      Op0BO->getOperand(1)->getName());
7509             InsertNewInstBefore(X, I);  // (X + (Y << C))
7510             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7511             return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7512                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7513           }
7514           
7515           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7516           Value *Op0BOOp1 = Op0BO->getOperand(1);
7517           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7518               match(Op0BOOp1, 
7519                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7520                           m_ConstantInt(CC)), *Context) &&
7521               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7522             Instruction *YS = BinaryOperator::CreateShl(
7523                                                      Op0BO->getOperand(0), Op1,
7524                                                      Op0BO->getName());
7525             InsertNewInstBefore(YS, I); // (Y << C)
7526             Instruction *XM =
7527               BinaryOperator::CreateAnd(V1,
7528                                         Context->getConstantExprShl(CC, Op1),
7529                                         V1->getName()+".mask");
7530             InsertNewInstBefore(XM, I); // X & (CC << C)
7531             
7532             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7533           }
7534         }
7535           
7536         // FALL THROUGH.
7537         case Instruction::Sub: {
7538           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7539           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7540               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7541                     m_Specific(Op1)), *Context)){
7542             Instruction *YS = BinaryOperator::CreateShl(
7543                                                      Op0BO->getOperand(1), Op1,
7544                                                      Op0BO->getName());
7545             InsertNewInstBefore(YS, I); // (Y << C)
7546             Instruction *X =
7547               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7548                                      Op0BO->getOperand(0)->getName());
7549             InsertNewInstBefore(X, I);  // (X + (Y << C))
7550             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7551             return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7552                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7553           }
7554           
7555           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7556           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7557               match(Op0BO->getOperand(0),
7558                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7559                           m_ConstantInt(CC)), *Context) && V2 == Op1 &&
7560               cast<BinaryOperator>(Op0BO->getOperand(0))
7561                   ->getOperand(0)->hasOneUse()) {
7562             Instruction *YS = BinaryOperator::CreateShl(
7563                                                      Op0BO->getOperand(1), Op1,
7564                                                      Op0BO->getName());
7565             InsertNewInstBefore(YS, I); // (Y << C)
7566             Instruction *XM =
7567               BinaryOperator::CreateAnd(V1, 
7568                                         Context->getConstantExprShl(CC, Op1),
7569                                         V1->getName()+".mask");
7570             InsertNewInstBefore(XM, I); // X & (CC << C)
7571             
7572             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7573           }
7574           
7575           break;
7576         }
7577       }
7578       
7579       
7580       // If the operand is an bitwise operator with a constant RHS, and the
7581       // shift is the only use, we can pull it out of the shift.
7582       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7583         bool isValid = true;     // Valid only for And, Or, Xor
7584         bool highBitSet = false; // Transform if high bit of constant set?
7585         
7586         switch (Op0BO->getOpcode()) {
7587           default: isValid = false; break;   // Do not perform transform!
7588           case Instruction::Add:
7589             isValid = isLeftShift;
7590             break;
7591           case Instruction::Or:
7592           case Instruction::Xor:
7593             highBitSet = false;
7594             break;
7595           case Instruction::And:
7596             highBitSet = true;
7597             break;
7598         }
7599         
7600         // If this is a signed shift right, and the high bit is modified
7601         // by the logical operation, do not perform the transformation.
7602         // The highBitSet boolean indicates the value of the high bit of
7603         // the constant which would cause it to be modified for this
7604         // operation.
7605         //
7606         if (isValid && I.getOpcode() == Instruction::AShr)
7607           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7608         
7609         if (isValid) {
7610           Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
7611           
7612           Instruction *NewShift =
7613             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7614           InsertNewInstBefore(NewShift, I);
7615           NewShift->takeName(Op0BO);
7616           
7617           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7618                                         NewRHS);
7619         }
7620       }
7621     }
7622   }
7623   
7624   // Find out if this is a shift of a shift by a constant.
7625   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7626   if (ShiftOp && !ShiftOp->isShift())
7627     ShiftOp = 0;
7628   
7629   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7630     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7631     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7632     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7633     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7634     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7635     Value *X = ShiftOp->getOperand(0);
7636     
7637     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7638     
7639     const IntegerType *Ty = cast<IntegerType>(I.getType());
7640     
7641     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7642     if (I.getOpcode() == ShiftOp->getOpcode()) {
7643       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7644       // saturates.
7645       if (AmtSum >= TypeBits) {
7646         if (I.getOpcode() != Instruction::AShr)
7647           return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7648         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7649       }
7650       
7651       return BinaryOperator::Create(I.getOpcode(), X,
7652                                     Context->getConstantInt(Ty, AmtSum));
7653     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7654                I.getOpcode() == Instruction::AShr) {
7655       if (AmtSum >= TypeBits)
7656         return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7657       
7658       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7659       return BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, AmtSum));
7660     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7661                I.getOpcode() == Instruction::LShr) {
7662       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7663       if (AmtSum >= TypeBits)
7664         AmtSum = TypeBits-1;
7665       
7666       Instruction *Shift =
7667         BinaryOperator::CreateAShr(X, Context->getConstantInt(Ty, AmtSum));
7668       InsertNewInstBefore(Shift, I);
7669
7670       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7671       return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7672     }
7673     
7674     // Okay, if we get here, one shift must be left, and the other shift must be
7675     // right.  See if the amounts are equal.
7676     if (ShiftAmt1 == ShiftAmt2) {
7677       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7678       if (I.getOpcode() == Instruction::Shl) {
7679         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7680         return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7681       }
7682       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7683       if (I.getOpcode() == Instruction::LShr) {
7684         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7685         return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7686       }
7687       // We can simplify ((X << C) >>s C) into a trunc + sext.
7688       // NOTE: we could do this for any C, but that would make 'unusual' integer
7689       // types.  For now, just stick to ones well-supported by the code
7690       // generators.
7691       const Type *SExtType = 0;
7692       switch (Ty->getBitWidth() - ShiftAmt1) {
7693       case 1  :
7694       case 8  :
7695       case 16 :
7696       case 32 :
7697       case 64 :
7698       case 128:
7699         SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
7700         break;
7701       default: break;
7702       }
7703       if (SExtType) {
7704         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7705         InsertNewInstBefore(NewTrunc, I);
7706         return new SExtInst(NewTrunc, Ty);
7707       }
7708       // Otherwise, we can't handle it yet.
7709     } else if (ShiftAmt1 < ShiftAmt2) {
7710       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7711       
7712       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7713       if (I.getOpcode() == Instruction::Shl) {
7714         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7715                ShiftOp->getOpcode() == Instruction::AShr);
7716         Instruction *Shift =
7717           BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7718         InsertNewInstBefore(Shift, I);
7719         
7720         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7721         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7722       }
7723       
7724       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7725       if (I.getOpcode() == Instruction::LShr) {
7726         assert(ShiftOp->getOpcode() == Instruction::Shl);
7727         Instruction *Shift =
7728           BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, ShiftDiff));
7729         InsertNewInstBefore(Shift, I);
7730         
7731         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7732         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7733       }
7734       
7735       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7736     } else {
7737       assert(ShiftAmt2 < ShiftAmt1);
7738       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7739
7740       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7741       if (I.getOpcode() == Instruction::Shl) {
7742         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7743                ShiftOp->getOpcode() == Instruction::AShr);
7744         Instruction *Shift =
7745           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7746                                  Context->getConstantInt(Ty, ShiftDiff));
7747         InsertNewInstBefore(Shift, I);
7748         
7749         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7750         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7751       }
7752       
7753       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7754       if (I.getOpcode() == Instruction::LShr) {
7755         assert(ShiftOp->getOpcode() == Instruction::Shl);
7756         Instruction *Shift =
7757           BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7758         InsertNewInstBefore(Shift, I);
7759         
7760         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7761         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7762       }
7763       
7764       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7765     }
7766   }
7767   return 0;
7768 }
7769
7770
7771 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7772 /// expression.  If so, decompose it, returning some value X, such that Val is
7773 /// X*Scale+Offset.
7774 ///
7775 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7776                                         int &Offset, LLVMContext *Context) {
7777   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7778   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7779     Offset = CI->getZExtValue();
7780     Scale  = 0;
7781     return Context->getConstantInt(Type::Int32Ty, 0);
7782   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7783     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7784       if (I->getOpcode() == Instruction::Shl) {
7785         // This is a value scaled by '1 << the shift amt'.
7786         Scale = 1U << RHS->getZExtValue();
7787         Offset = 0;
7788         return I->getOperand(0);
7789       } else if (I->getOpcode() == Instruction::Mul) {
7790         // This value is scaled by 'RHS'.
7791         Scale = RHS->getZExtValue();
7792         Offset = 0;
7793         return I->getOperand(0);
7794       } else if (I->getOpcode() == Instruction::Add) {
7795         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7796         // where C1 is divisible by C2.
7797         unsigned SubScale;
7798         Value *SubVal = 
7799           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7800                                     Offset, Context);
7801         Offset += RHS->getZExtValue();
7802         Scale = SubScale;
7803         return SubVal;
7804       }
7805     }
7806   }
7807
7808   // Otherwise, we can't look past this.
7809   Scale = 1;
7810   Offset = 0;
7811   return Val;
7812 }
7813
7814
7815 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7816 /// try to eliminate the cast by moving the type information into the alloc.
7817 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7818                                                    AllocationInst &AI) {
7819   const PointerType *PTy = cast<PointerType>(CI.getType());
7820   
7821   // Remove any uses of AI that are dead.
7822   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7823   
7824   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7825     Instruction *User = cast<Instruction>(*UI++);
7826     if (isInstructionTriviallyDead(User)) {
7827       while (UI != E && *UI == User)
7828         ++UI; // If this instruction uses AI more than once, don't break UI.
7829       
7830       ++NumDeadInst;
7831       DOUT << "IC: DCE: " << *User;
7832       EraseInstFromFunction(*User);
7833     }
7834   }
7835   
7836   // Get the type really allocated and the type casted to.
7837   const Type *AllocElTy = AI.getAllocatedType();
7838   const Type *CastElTy = PTy->getElementType();
7839   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7840
7841   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7842   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7843   if (CastElTyAlign < AllocElTyAlign) return 0;
7844
7845   // If the allocation has multiple uses, only promote it if we are strictly
7846   // increasing the alignment of the resultant allocation.  If we keep it the
7847   // same, we open the door to infinite loops of various kinds.  (A reference
7848   // from a dbg.declare doesn't count as a use for this purpose.)
7849   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7850       CastElTyAlign == AllocElTyAlign) return 0;
7851
7852   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7853   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7854   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7855
7856   // See if we can satisfy the modulus by pulling a scale out of the array
7857   // size argument.
7858   unsigned ArraySizeScale;
7859   int ArrayOffset;
7860   Value *NumElements = // See if the array size is a decomposable linear expr.
7861     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7862                               ArrayOffset, Context);
7863  
7864   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7865   // do the xform.
7866   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7867       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7868
7869   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7870   Value *Amt = 0;
7871   if (Scale == 1) {
7872     Amt = NumElements;
7873   } else {
7874     // If the allocation size is constant, form a constant mul expression
7875     Amt = Context->getConstantInt(Type::Int32Ty, Scale);
7876     if (isa<ConstantInt>(NumElements))
7877       Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
7878                                  cast<ConstantInt>(Amt));
7879     // otherwise multiply the amount and the number of elements
7880     else {
7881       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7882       Amt = InsertNewInstBefore(Tmp, AI);
7883     }
7884   }
7885   
7886   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7887     Value *Off = Context->getConstantInt(Type::Int32Ty, Offset, true);
7888     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7889     Amt = InsertNewInstBefore(Tmp, AI);
7890   }
7891   
7892   AllocationInst *New;
7893   if (isa<MallocInst>(AI))
7894     New = new MallocInst(*Context, CastElTy, Amt, AI.getAlignment());
7895   else
7896     New = new AllocaInst(*Context, CastElTy, Amt, AI.getAlignment());
7897   InsertNewInstBefore(New, AI);
7898   New->takeName(&AI);
7899   
7900   // If the allocation has one real use plus a dbg.declare, just remove the
7901   // declare.
7902   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7903     EraseInstFromFunction(*DI);
7904   }
7905   // If the allocation has multiple real uses, insert a cast and change all
7906   // things that used it to use the new cast.  This will also hack on CI, but it
7907   // will die soon.
7908   else if (!AI.hasOneUse()) {
7909     AddUsesToWorkList(AI);
7910     // New is the allocation instruction, pointer typed. AI is the original
7911     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7912     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7913     InsertNewInstBefore(NewCast, AI);
7914     AI.replaceAllUsesWith(NewCast);
7915   }
7916   return ReplaceInstUsesWith(CI, New);
7917 }
7918
7919 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7920 /// and return it as type Ty without inserting any new casts and without
7921 /// changing the computed value.  This is used by code that tries to decide
7922 /// whether promoting or shrinking integer operations to wider or smaller types
7923 /// will allow us to eliminate a truncate or extend.
7924 ///
7925 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7926 /// extension operation if Ty is larger.
7927 ///
7928 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7929 /// should return true if trunc(V) can be computed by computing V in the smaller
7930 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7931 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7932 /// efficiently truncated.
7933 ///
7934 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7935 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7936 /// the final result.
7937 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7938                                               unsigned CastOpc,
7939                                               int &NumCastsRemoved){
7940   // We can always evaluate constants in another type.
7941   if (isa<Constant>(V))
7942     return true;
7943   
7944   Instruction *I = dyn_cast<Instruction>(V);
7945   if (!I) return false;
7946   
7947   const Type *OrigTy = V->getType();
7948   
7949   // If this is an extension or truncate, we can often eliminate it.
7950   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7951     // If this is a cast from the destination type, we can trivially eliminate
7952     // it, and this will remove a cast overall.
7953     if (I->getOperand(0)->getType() == Ty) {
7954       // If the first operand is itself a cast, and is eliminable, do not count
7955       // this as an eliminable cast.  We would prefer to eliminate those two
7956       // casts first.
7957       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7958         ++NumCastsRemoved;
7959       return true;
7960     }
7961   }
7962
7963   // We can't extend or shrink something that has multiple uses: doing so would
7964   // require duplicating the instruction in general, which isn't profitable.
7965   if (!I->hasOneUse()) return false;
7966
7967   unsigned Opc = I->getOpcode();
7968   switch (Opc) {
7969   case Instruction::Add:
7970   case Instruction::Sub:
7971   case Instruction::Mul:
7972   case Instruction::And:
7973   case Instruction::Or:
7974   case Instruction::Xor:
7975     // These operators can all arbitrarily be extended or truncated.
7976     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7977                                       NumCastsRemoved) &&
7978            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7979                                       NumCastsRemoved);
7980
7981   case Instruction::UDiv:
7982   case Instruction::URem: {
7983     // UDiv and URem can be truncated if all the truncated bits are zero.
7984     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7985     uint32_t BitWidth = Ty->getScalarSizeInBits();
7986     if (BitWidth < OrigBitWidth) {
7987       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7988       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7989           MaskedValueIsZero(I->getOperand(1), Mask)) {
7990         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7991                                           NumCastsRemoved) &&
7992                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7993                                           NumCastsRemoved);
7994       }
7995     }
7996     break;
7997   }
7998   case Instruction::Shl:
7999     // If we are truncating the result of this SHL, and if it's a shift of a
8000     // constant amount, we can always perform a SHL in a smaller type.
8001     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8002       uint32_t BitWidth = Ty->getScalarSizeInBits();
8003       if (BitWidth < OrigTy->getScalarSizeInBits() &&
8004           CI->getLimitedValue(BitWidth) < BitWidth)
8005         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8006                                           NumCastsRemoved);
8007     }
8008     break;
8009   case Instruction::LShr:
8010     // If this is a truncate of a logical shr, we can truncate it to a smaller
8011     // lshr iff we know that the bits we would otherwise be shifting in are
8012     // already zeros.
8013     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8014       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8015       uint32_t BitWidth = Ty->getScalarSizeInBits();
8016       if (BitWidth < OrigBitWidth &&
8017           MaskedValueIsZero(I->getOperand(0),
8018             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8019           CI->getLimitedValue(BitWidth) < BitWidth) {
8020         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8021                                           NumCastsRemoved);
8022       }
8023     }
8024     break;
8025   case Instruction::ZExt:
8026   case Instruction::SExt:
8027   case Instruction::Trunc:
8028     // If this is the same kind of case as our original (e.g. zext+zext), we
8029     // can safely replace it.  Note that replacing it does not reduce the number
8030     // of casts in the input.
8031     if (Opc == CastOpc)
8032       return true;
8033
8034     // sext (zext ty1), ty2 -> zext ty2
8035     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
8036       return true;
8037     break;
8038   case Instruction::Select: {
8039     SelectInst *SI = cast<SelectInst>(I);
8040     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8041                                       NumCastsRemoved) &&
8042            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8043                                       NumCastsRemoved);
8044   }
8045   case Instruction::PHI: {
8046     // We can change a phi if we can change all operands.
8047     PHINode *PN = cast<PHINode>(I);
8048     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8049       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8050                                       NumCastsRemoved))
8051         return false;
8052     return true;
8053   }
8054   default:
8055     // TODO: Can handle more cases here.
8056     break;
8057   }
8058   
8059   return false;
8060 }
8061
8062 /// EvaluateInDifferentType - Given an expression that 
8063 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8064 /// evaluate the expression.
8065 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
8066                                              bool isSigned) {
8067   if (Constant *C = dyn_cast<Constant>(V))
8068     return Context->getConstantExprIntegerCast(C, Ty,
8069                                                isSigned /*Sext or ZExt*/);
8070
8071   // Otherwise, it must be an instruction.
8072   Instruction *I = cast<Instruction>(V);
8073   Instruction *Res = 0;
8074   unsigned Opc = I->getOpcode();
8075   switch (Opc) {
8076   case Instruction::Add:
8077   case Instruction::Sub:
8078   case Instruction::Mul:
8079   case Instruction::And:
8080   case Instruction::Or:
8081   case Instruction::Xor:
8082   case Instruction::AShr:
8083   case Instruction::LShr:
8084   case Instruction::Shl:
8085   case Instruction::UDiv:
8086   case Instruction::URem: {
8087     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8088     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8089     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8090     break;
8091   }    
8092   case Instruction::Trunc:
8093   case Instruction::ZExt:
8094   case Instruction::SExt:
8095     // If the source type of the cast is the type we're trying for then we can
8096     // just return the source.  There's no need to insert it because it is not
8097     // new.
8098     if (I->getOperand(0)->getType() == Ty)
8099       return I->getOperand(0);
8100     
8101     // Otherwise, must be the same type of cast, so just reinsert a new one.
8102     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8103                            Ty);
8104     break;
8105   case Instruction::Select: {
8106     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8107     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8108     Res = SelectInst::Create(I->getOperand(0), True, False);
8109     break;
8110   }
8111   case Instruction::PHI: {
8112     PHINode *OPN = cast<PHINode>(I);
8113     PHINode *NPN = PHINode::Create(Ty);
8114     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8115       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8116       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8117     }
8118     Res = NPN;
8119     break;
8120   }
8121   default: 
8122     // TODO: Can handle more cases here.
8123     llvm_unreachable("Unreachable!");
8124     break;
8125   }
8126   
8127   Res->takeName(I);
8128   return InsertNewInstBefore(Res, *I);
8129 }
8130
8131 /// @brief Implement the transforms common to all CastInst visitors.
8132 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8133   Value *Src = CI.getOperand(0);
8134
8135   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8136   // eliminate it now.
8137   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8138     if (Instruction::CastOps opc = 
8139         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8140       // The first cast (CSrc) is eliminable so we need to fix up or replace
8141       // the second cast (CI). CSrc will then have a good chance of being dead.
8142       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8143     }
8144   }
8145
8146   // If we are casting a select then fold the cast into the select
8147   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8148     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8149       return NV;
8150
8151   // If we are casting a PHI then fold the cast into the PHI
8152   if (isa<PHINode>(Src))
8153     if (Instruction *NV = FoldOpIntoPhi(CI))
8154       return NV;
8155   
8156   return 0;
8157 }
8158
8159 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8160 /// or not there is a sequence of GEP indices into the type that will land us at
8161 /// the specified offset.  If so, fill them into NewIndices and return the
8162 /// resultant element type, otherwise return null.
8163 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8164                                        SmallVectorImpl<Value*> &NewIndices,
8165                                        const TargetData *TD,
8166                                        LLVMContext *Context) {
8167   if (!Ty->isSized()) return 0;
8168   
8169   // Start with the index over the outer type.  Note that the type size
8170   // might be zero (even if the offset isn't zero) if the indexed type
8171   // is something like [0 x {int, int}]
8172   const Type *IntPtrTy = TD->getIntPtrType();
8173   int64_t FirstIdx = 0;
8174   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8175     FirstIdx = Offset/TySize;
8176     Offset -= FirstIdx*TySize;
8177     
8178     // Handle hosts where % returns negative instead of values [0..TySize).
8179     if (Offset < 0) {
8180       --FirstIdx;
8181       Offset += TySize;
8182       assert(Offset >= 0);
8183     }
8184     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8185   }
8186   
8187   NewIndices.push_back(Context->getConstantInt(IntPtrTy, FirstIdx));
8188     
8189   // Index into the types.  If we fail, set OrigBase to null.
8190   while (Offset) {
8191     // Indexing into tail padding between struct/array elements.
8192     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8193       return 0;
8194     
8195     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8196       const StructLayout *SL = TD->getStructLayout(STy);
8197       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8198              "Offset must stay within the indexed type");
8199       
8200       unsigned Elt = SL->getElementContainingOffset(Offset);
8201       NewIndices.push_back(Context->getConstantInt(Type::Int32Ty, Elt));
8202       
8203       Offset -= SL->getElementOffset(Elt);
8204       Ty = STy->getElementType(Elt);
8205     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8206       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8207       assert(EltSize && "Cannot index into a zero-sized array");
8208       NewIndices.push_back(Context->getConstantInt(IntPtrTy,Offset/EltSize));
8209       Offset %= EltSize;
8210       Ty = AT->getElementType();
8211     } else {
8212       // Otherwise, we can't index into the middle of this atomic type, bail.
8213       return 0;
8214     }
8215   }
8216   
8217   return Ty;
8218 }
8219
8220 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8221 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8222   Value *Src = CI.getOperand(0);
8223   
8224   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8225     // If casting the result of a getelementptr instruction with no offset, turn
8226     // this into a cast of the original pointer!
8227     if (GEP->hasAllZeroIndices()) {
8228       // Changing the cast operand is usually not a good idea but it is safe
8229       // here because the pointer operand is being replaced with another 
8230       // pointer operand so the opcode doesn't need to change.
8231       AddToWorkList(GEP);
8232       CI.setOperand(0, GEP->getOperand(0));
8233       return &CI;
8234     }
8235     
8236     // If the GEP has a single use, and the base pointer is a bitcast, and the
8237     // GEP computes a constant offset, see if we can convert these three
8238     // instructions into fewer.  This typically happens with unions and other
8239     // non-type-safe code.
8240     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8241       if (GEP->hasAllConstantIndices()) {
8242         // We are guaranteed to get a constant from EmitGEPOffset.
8243         ConstantInt *OffsetV =
8244                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8245         int64_t Offset = OffsetV->getSExtValue();
8246         
8247         // Get the base pointer input of the bitcast, and the type it points to.
8248         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8249         const Type *GEPIdxTy =
8250           cast<PointerType>(OrigBase->getType())->getElementType();
8251         SmallVector<Value*, 8> NewIndices;
8252         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8253           // If we were able to index down into an element, create the GEP
8254           // and bitcast the result.  This eliminates one bitcast, potentially
8255           // two.
8256           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
8257                                                         NewIndices.begin(),
8258                                                         NewIndices.end(), "");
8259           InsertNewInstBefore(NGEP, CI);
8260           NGEP->takeName(GEP);
8261           
8262           if (isa<BitCastInst>(CI))
8263             return new BitCastInst(NGEP, CI.getType());
8264           assert(isa<PtrToIntInst>(CI));
8265           return new PtrToIntInst(NGEP, CI.getType());
8266         }
8267       }      
8268     }
8269   }
8270     
8271   return commonCastTransforms(CI);
8272 }
8273
8274 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8275 /// type like i42.  We don't want to introduce operations on random non-legal
8276 /// integer types where they don't already exist in the code.  In the future,
8277 /// we should consider making this based off target-data, so that 32-bit targets
8278 /// won't get i64 operations etc.
8279 static bool isSafeIntegerType(const Type *Ty) {
8280   switch (Ty->getPrimitiveSizeInBits()) {
8281   case 8:
8282   case 16:
8283   case 32:
8284   case 64:
8285     return true;
8286   default: 
8287     return false;
8288   }
8289 }
8290
8291 /// commonIntCastTransforms - This function implements the common transforms
8292 /// for trunc, zext, and sext.
8293 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8294   if (Instruction *Result = commonCastTransforms(CI))
8295     return Result;
8296
8297   Value *Src = CI.getOperand(0);
8298   const Type *SrcTy = Src->getType();
8299   const Type *DestTy = CI.getType();
8300   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8301   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8302
8303   // See if we can simplify any instructions used by the LHS whose sole 
8304   // purpose is to compute bits we don't care about.
8305   if (SimplifyDemandedInstructionBits(CI))
8306     return &CI;
8307
8308   // If the source isn't an instruction or has more than one use then we
8309   // can't do anything more. 
8310   Instruction *SrcI = dyn_cast<Instruction>(Src);
8311   if (!SrcI || !Src->hasOneUse())
8312     return 0;
8313
8314   // Attempt to propagate the cast into the instruction for int->int casts.
8315   int NumCastsRemoved = 0;
8316   // Only do this if the dest type is a simple type, don't convert the
8317   // expression tree to something weird like i93 unless the source is also
8318   // strange.
8319   if ((isSafeIntegerType(DestTy->getScalarType()) ||
8320        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8321       CanEvaluateInDifferentType(SrcI, DestTy,
8322                                  CI.getOpcode(), NumCastsRemoved)) {
8323     // If this cast is a truncate, evaluting in a different type always
8324     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8325     // we need to do an AND to maintain the clear top-part of the computation,
8326     // so we require that the input have eliminated at least one cast.  If this
8327     // is a sign extension, we insert two new casts (to do the extension) so we
8328     // require that two casts have been eliminated.
8329     bool DoXForm = false;
8330     bool JustReplace = false;
8331     switch (CI.getOpcode()) {
8332     default:
8333       // All the others use floating point so we shouldn't actually 
8334       // get here because of the check above.
8335       llvm_unreachable("Unknown cast type");
8336     case Instruction::Trunc:
8337       DoXForm = true;
8338       break;
8339     case Instruction::ZExt: {
8340       DoXForm = NumCastsRemoved >= 1;
8341       if (!DoXForm && 0) {
8342         // If it's unnecessary to issue an AND to clear the high bits, it's
8343         // always profitable to do this xform.
8344         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8345         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8346         if (MaskedValueIsZero(TryRes, Mask))
8347           return ReplaceInstUsesWith(CI, TryRes);
8348         
8349         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8350           if (TryI->use_empty())
8351             EraseInstFromFunction(*TryI);
8352       }
8353       break;
8354     }
8355     case Instruction::SExt: {
8356       DoXForm = NumCastsRemoved >= 2;
8357       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8358         // If we do not have to emit the truncate + sext pair, then it's always
8359         // profitable to do this xform.
8360         //
8361         // It's not safe to eliminate the trunc + sext pair if one of the
8362         // eliminated cast is a truncate. e.g.
8363         // t2 = trunc i32 t1 to i16
8364         // t3 = sext i16 t2 to i32
8365         // !=
8366         // i32 t1
8367         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8368         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8369         if (NumSignBits > (DestBitSize - SrcBitSize))
8370           return ReplaceInstUsesWith(CI, TryRes);
8371         
8372         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8373           if (TryI->use_empty())
8374             EraseInstFromFunction(*TryI);
8375       }
8376       break;
8377     }
8378     }
8379     
8380     if (DoXForm) {
8381       DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8382            << " cast: " << CI;
8383       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8384                                            CI.getOpcode() == Instruction::SExt);
8385       if (JustReplace)
8386         // Just replace this cast with the result.
8387         return ReplaceInstUsesWith(CI, Res);
8388
8389       assert(Res->getType() == DestTy);
8390       switch (CI.getOpcode()) {
8391       default: llvm_unreachable("Unknown cast type!");
8392       case Instruction::Trunc:
8393         // Just replace this cast with the result.
8394         return ReplaceInstUsesWith(CI, Res);
8395       case Instruction::ZExt: {
8396         assert(SrcBitSize < DestBitSize && "Not a zext?");
8397
8398         // If the high bits are already zero, just replace this cast with the
8399         // result.
8400         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8401         if (MaskedValueIsZero(Res, Mask))
8402           return ReplaceInstUsesWith(CI, Res);
8403
8404         // We need to emit an AND to clear the high bits.
8405         Constant *C = Context->getConstantInt(APInt::getLowBitsSet(DestBitSize,
8406                                                             SrcBitSize));
8407         return BinaryOperator::CreateAnd(Res, C);
8408       }
8409       case Instruction::SExt: {
8410         // If the high bits are already filled with sign bit, just replace this
8411         // cast with the result.
8412         unsigned NumSignBits = ComputeNumSignBits(Res);
8413         if (NumSignBits > (DestBitSize - SrcBitSize))
8414           return ReplaceInstUsesWith(CI, Res);
8415
8416         // We need to emit a cast to truncate, then a cast to sext.
8417         return CastInst::Create(Instruction::SExt,
8418             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8419                              CI), DestTy);
8420       }
8421       }
8422     }
8423   }
8424   
8425   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8426   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8427
8428   switch (SrcI->getOpcode()) {
8429   case Instruction::Add:
8430   case Instruction::Mul:
8431   case Instruction::And:
8432   case Instruction::Or:
8433   case Instruction::Xor:
8434     // If we are discarding information, rewrite.
8435     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8436       // Don't insert two casts unless at least one can be eliminated.
8437       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8438           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8439         Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8440         Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8441         return BinaryOperator::Create(
8442             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8443       }
8444     }
8445
8446     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8447     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8448         SrcI->getOpcode() == Instruction::Xor &&
8449         Op1 == Context->getConstantIntTrue() &&
8450         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8451       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8452       return BinaryOperator::CreateXor(New,
8453                                       Context->getConstantInt(CI.getType(), 1));
8454     }
8455     break;
8456
8457   case Instruction::Shl: {
8458     // Canonicalize trunc inside shl, if we can.
8459     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8460     if (CI && DestBitSize < SrcBitSize &&
8461         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8462       Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8463       Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8464       return BinaryOperator::CreateShl(Op0c, Op1c);
8465     }
8466     break;
8467   }
8468   }
8469   return 0;
8470 }
8471
8472 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8473   if (Instruction *Result = commonIntCastTransforms(CI))
8474     return Result;
8475   
8476   Value *Src = CI.getOperand(0);
8477   const Type *Ty = CI.getType();
8478   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8479   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8480
8481   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8482   if (DestBitWidth == 1 &&
8483       isa<VectorType>(Ty) == isa<VectorType>(Src->getType())) {
8484     Constant *One = Context->getConstantInt(Src->getType(), 1);
8485     Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8486     Value *Zero = Context->getNullValue(Src->getType());
8487     return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
8488   }
8489
8490   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8491   ConstantInt *ShAmtV = 0;
8492   Value *ShiftOp = 0;
8493   if (Src->hasOneUse() &&
8494       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
8495     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8496     
8497     // Get a mask for the bits shifting in.
8498     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8499     if (MaskedValueIsZero(ShiftOp, Mask)) {
8500       if (ShAmt >= DestBitWidth)        // All zeros.
8501         return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
8502       
8503       // Okay, we can shrink this.  Truncate the input, then return a new
8504       // shift.
8505       Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8506       Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
8507       return BinaryOperator::CreateLShr(V1, V2);
8508     }
8509   }
8510   
8511   return 0;
8512 }
8513
8514 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8515 /// in order to eliminate the icmp.
8516 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8517                                              bool DoXform) {
8518   // If we are just checking for a icmp eq of a single bit and zext'ing it
8519   // to an integer, then shift the bit to the appropriate place and then
8520   // cast to integer to avoid the comparison.
8521   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8522     const APInt &Op1CV = Op1C->getValue();
8523       
8524     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8525     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8526     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8527         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8528       if (!DoXform) return ICI;
8529
8530       Value *In = ICI->getOperand(0);
8531       Value *Sh = Context->getConstantInt(In->getType(),
8532                                    In->getType()->getScalarSizeInBits()-1);
8533       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8534                                                         In->getName()+".lobit"),
8535                                CI);
8536       if (In->getType() != CI.getType())
8537         In = CastInst::CreateIntegerCast(In, CI.getType(),
8538                                          false/*ZExt*/, "tmp", &CI);
8539
8540       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8541         Constant *One = Context->getConstantInt(In->getType(), 1);
8542         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8543                                                          In->getName()+".not"),
8544                                  CI);
8545       }
8546
8547       return ReplaceInstUsesWith(CI, In);
8548     }
8549       
8550       
8551       
8552     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8553     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8554     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8555     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8556     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8557     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8558     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8559     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8560     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8561         // This only works for EQ and NE
8562         ICI->isEquality()) {
8563       // If Op1C some other power of two, convert:
8564       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8565       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8566       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8567       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8568         
8569       APInt KnownZeroMask(~KnownZero);
8570       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8571         if (!DoXform) return ICI;
8572
8573         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8574         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8575           // (X&4) == 2 --> false
8576           // (X&4) != 2 --> true
8577           Constant *Res = Context->getConstantInt(Type::Int1Ty, isNE);
8578           Res = Context->getConstantExprZExt(Res, CI.getType());
8579           return ReplaceInstUsesWith(CI, Res);
8580         }
8581           
8582         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8583         Value *In = ICI->getOperand(0);
8584         if (ShiftAmt) {
8585           // Perform a logical shr by shiftamt.
8586           // Insert the shift to put the result in the low bit.
8587           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8588                               Context->getConstantInt(In->getType(), ShiftAmt),
8589                                                    In->getName()+".lobit"), CI);
8590         }
8591           
8592         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8593           Constant *One = Context->getConstantInt(In->getType(), 1);
8594           In = BinaryOperator::CreateXor(In, One, "tmp");
8595           InsertNewInstBefore(cast<Instruction>(In), CI);
8596         }
8597           
8598         if (CI.getType() == In->getType())
8599           return ReplaceInstUsesWith(CI, In);
8600         else
8601           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8602       }
8603     }
8604   }
8605
8606   return 0;
8607 }
8608
8609 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8610   // If one of the common conversion will work ..
8611   if (Instruction *Result = commonIntCastTransforms(CI))
8612     return Result;
8613
8614   Value *Src = CI.getOperand(0);
8615
8616   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8617   // types and if the sizes are just right we can convert this into a logical
8618   // 'and' which will be much cheaper than the pair of casts.
8619   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8620     // Get the sizes of the types involved.  We know that the intermediate type
8621     // will be smaller than A or C, but don't know the relation between A and C.
8622     Value *A = CSrc->getOperand(0);
8623     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8624     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8625     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8626     // If we're actually extending zero bits, then if
8627     // SrcSize <  DstSize: zext(a & mask)
8628     // SrcSize == DstSize: a & mask
8629     // SrcSize  > DstSize: trunc(a) & mask
8630     if (SrcSize < DstSize) {
8631       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8632       Constant *AndConst = Context->getConstantInt(A->getType(), AndValue);
8633       Instruction *And =
8634         BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8635       InsertNewInstBefore(And, CI);
8636       return new ZExtInst(And, CI.getType());
8637     } else if (SrcSize == DstSize) {
8638       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8639       return BinaryOperator::CreateAnd(A, Context->getConstantInt(A->getType(),
8640                                                            AndValue));
8641     } else if (SrcSize > DstSize) {
8642       Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8643       InsertNewInstBefore(Trunc, CI);
8644       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8645       return BinaryOperator::CreateAnd(Trunc, 
8646                                        Context->getConstantInt(Trunc->getType(),
8647                                                                AndValue));
8648     }
8649   }
8650
8651   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8652     return transformZExtICmp(ICI, CI);
8653
8654   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8655   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8656     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8657     // of the (zext icmp) will be transformed.
8658     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8659     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8660     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8661         (transformZExtICmp(LHS, CI, false) ||
8662          transformZExtICmp(RHS, CI, false))) {
8663       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8664       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8665       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8666     }
8667   }
8668
8669   // zext(trunc(t) & C) -> (t & zext(C)).
8670   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8671     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8672       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8673         Value *TI0 = TI->getOperand(0);
8674         if (TI0->getType() == CI.getType())
8675           return
8676             BinaryOperator::CreateAnd(TI0,
8677                                 Context->getConstantExprZExt(C, CI.getType()));
8678       }
8679
8680   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8681   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8682     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8683       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8684         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8685             And->getOperand(1) == C)
8686           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8687             Value *TI0 = TI->getOperand(0);
8688             if (TI0->getType() == CI.getType()) {
8689               Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
8690               Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8691               InsertNewInstBefore(NewAnd, *And);
8692               return BinaryOperator::CreateXor(NewAnd, ZC);
8693             }
8694           }
8695
8696   return 0;
8697 }
8698
8699 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8700   if (Instruction *I = commonIntCastTransforms(CI))
8701     return I;
8702   
8703   Value *Src = CI.getOperand(0);
8704   
8705   // Canonicalize sign-extend from i1 to a select.
8706   if (Src->getType() == Type::Int1Ty)
8707     return SelectInst::Create(Src,
8708                               Context->getAllOnesValue(CI.getType()),
8709                               Context->getNullValue(CI.getType()));
8710
8711   // See if the value being truncated is already sign extended.  If so, just
8712   // eliminate the trunc/sext pair.
8713   if (getOpcode(Src) == Instruction::Trunc) {
8714     Value *Op = cast<User>(Src)->getOperand(0);
8715     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8716     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8717     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8718     unsigned NumSignBits = ComputeNumSignBits(Op);
8719
8720     if (OpBits == DestBits) {
8721       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8722       // bits, it is already ready.
8723       if (NumSignBits > DestBits-MidBits)
8724         return ReplaceInstUsesWith(CI, Op);
8725     } else if (OpBits < DestBits) {
8726       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8727       // bits, just sext from i32.
8728       if (NumSignBits > OpBits-MidBits)
8729         return new SExtInst(Op, CI.getType(), "tmp");
8730     } else {
8731       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8732       // bits, just truncate to i32.
8733       if (NumSignBits > OpBits-MidBits)
8734         return new TruncInst(Op, CI.getType(), "tmp");
8735     }
8736   }
8737
8738   // If the input is a shl/ashr pair of a same constant, then this is a sign
8739   // extension from a smaller value.  If we could trust arbitrary bitwidth
8740   // integers, we could turn this into a truncate to the smaller bit and then
8741   // use a sext for the whole extension.  Since we don't, look deeper and check
8742   // for a truncate.  If the source and dest are the same type, eliminate the
8743   // trunc and extend and just do shifts.  For example, turn:
8744   //   %a = trunc i32 %i to i8
8745   //   %b = shl i8 %a, 6
8746   //   %c = ashr i8 %b, 6
8747   //   %d = sext i8 %c to i32
8748   // into:
8749   //   %a = shl i32 %i, 30
8750   //   %d = ashr i32 %a, 30
8751   Value *A = 0;
8752   ConstantInt *BA = 0, *CA = 0;
8753   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8754                         m_ConstantInt(CA)), *Context) &&
8755       BA == CA && isa<TruncInst>(A)) {
8756     Value *I = cast<TruncInst>(A)->getOperand(0);
8757     if (I->getType() == CI.getType()) {
8758       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8759       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8760       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8761       Constant *ShAmtV = Context->getConstantInt(CI.getType(), ShAmt);
8762       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8763                                                         CI.getName()), CI);
8764       return BinaryOperator::CreateAShr(I, ShAmtV);
8765     }
8766   }
8767   
8768   return 0;
8769 }
8770
8771 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8772 /// in the specified FP type without changing its value.
8773 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8774                               LLVMContext *Context) {
8775   bool losesInfo;
8776   APFloat F = CFP->getValueAPF();
8777   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8778   if (!losesInfo)
8779     return Context->getConstantFP(F);
8780   return 0;
8781 }
8782
8783 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8784 /// through it until we get the source value.
8785 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8786   if (Instruction *I = dyn_cast<Instruction>(V))
8787     if (I->getOpcode() == Instruction::FPExt)
8788       return LookThroughFPExtensions(I->getOperand(0), Context);
8789   
8790   // If this value is a constant, return the constant in the smallest FP type
8791   // that can accurately represent it.  This allows us to turn
8792   // (float)((double)X+2.0) into x+2.0f.
8793   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8794     if (CFP->getType() == Type::PPC_FP128Ty)
8795       return V;  // No constant folding of this.
8796     // See if the value can be truncated to float and then reextended.
8797     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8798       return V;
8799     if (CFP->getType() == Type::DoubleTy)
8800       return V;  // Won't shrink.
8801     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8802       return V;
8803     // Don't try to shrink to various long double types.
8804   }
8805   
8806   return V;
8807 }
8808
8809 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8810   if (Instruction *I = commonCastTransforms(CI))
8811     return I;
8812   
8813   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8814   // smaller than the destination type, we can eliminate the truncate by doing
8815   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8816   // many builtins (sqrt, etc).
8817   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8818   if (OpI && OpI->hasOneUse()) {
8819     switch (OpI->getOpcode()) {
8820     default: break;
8821     case Instruction::FAdd:
8822     case Instruction::FSub:
8823     case Instruction::FMul:
8824     case Instruction::FDiv:
8825     case Instruction::FRem:
8826       const Type *SrcTy = OpI->getType();
8827       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8828       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8829       if (LHSTrunc->getType() != SrcTy && 
8830           RHSTrunc->getType() != SrcTy) {
8831         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8832         // If the source types were both smaller than the destination type of
8833         // the cast, do this xform.
8834         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8835             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8836           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8837                                       CI.getType(), CI);
8838           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8839                                       CI.getType(), CI);
8840           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8841         }
8842       }
8843       break;  
8844     }
8845   }
8846   return 0;
8847 }
8848
8849 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8850   return commonCastTransforms(CI);
8851 }
8852
8853 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8854   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8855   if (OpI == 0)
8856     return commonCastTransforms(FI);
8857
8858   // fptoui(uitofp(X)) --> X
8859   // fptoui(sitofp(X)) --> X
8860   // This is safe if the intermediate type has enough bits in its mantissa to
8861   // accurately represent all values of X.  For example, do not do this with
8862   // i64->float->i64.  This is also safe for sitofp case, because any negative
8863   // 'X' value would cause an undefined result for the fptoui. 
8864   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8865       OpI->getOperand(0)->getType() == FI.getType() &&
8866       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8867                     OpI->getType()->getFPMantissaWidth())
8868     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8869
8870   return commonCastTransforms(FI);
8871 }
8872
8873 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8874   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8875   if (OpI == 0)
8876     return commonCastTransforms(FI);
8877   
8878   // fptosi(sitofp(X)) --> X
8879   // fptosi(uitofp(X)) --> X
8880   // This is safe if the intermediate type has enough bits in its mantissa to
8881   // accurately represent all values of X.  For example, do not do this with
8882   // i64->float->i64.  This is also safe for sitofp case, because any negative
8883   // 'X' value would cause an undefined result for the fptoui. 
8884   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8885       OpI->getOperand(0)->getType() == FI.getType() &&
8886       (int)FI.getType()->getScalarSizeInBits() <=
8887                     OpI->getType()->getFPMantissaWidth())
8888     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8889   
8890   return commonCastTransforms(FI);
8891 }
8892
8893 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8894   return commonCastTransforms(CI);
8895 }
8896
8897 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8898   return commonCastTransforms(CI);
8899 }
8900
8901 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8902   // If the destination integer type is smaller than the intptr_t type for
8903   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8904   // trunc to be exposed to other transforms.  Don't do this for extending
8905   // ptrtoint's, because we don't know if the target sign or zero extends its
8906   // pointers.
8907   if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8908     Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8909                                                     TD->getIntPtrType(),
8910                                                     "tmp"), CI);
8911     return new TruncInst(P, CI.getType());
8912   }
8913   
8914   return commonPointerCastTransforms(CI);
8915 }
8916
8917 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8918   // If the source integer type is larger than the intptr_t type for
8919   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8920   // allows the trunc to be exposed to other transforms.  Don't do this for
8921   // extending inttoptr's, because we don't know if the target sign or zero
8922   // extends to pointers.
8923   if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
8924       TD->getPointerSizeInBits()) {
8925     Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8926                                                  TD->getIntPtrType(),
8927                                                  "tmp"), CI);
8928     return new IntToPtrInst(P, CI.getType());
8929   }
8930   
8931   if (Instruction *I = commonCastTransforms(CI))
8932     return I;
8933   
8934   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8935   if (!DestPointee->isSized()) return 0;
8936
8937   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8938   ConstantInt *Cst;
8939   Value *X;
8940   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8941                                     m_ConstantInt(Cst)), *Context)) {
8942     // If the source and destination operands have the same type, see if this
8943     // is a single-index GEP.
8944     if (X->getType() == CI.getType()) {
8945       // Get the size of the pointee type.
8946       uint64_t Size = TD->getTypeAllocSize(DestPointee);
8947
8948       // Convert the constant to intptr type.
8949       APInt Offset = Cst->getValue();
8950       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8951
8952       // If Offset is evenly divisible by Size, we can do this xform.
8953       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8954         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8955         return GetElementPtrInst::Create(X, Context->getConstantInt(Offset));
8956       }
8957     }
8958     // TODO: Could handle other cases, e.g. where add is indexing into field of
8959     // struct etc.
8960   } else if (CI.getOperand(0)->hasOneUse() &&
8961              match(CI.getOperand(0), m_Add(m_Value(X),
8962                    m_ConstantInt(Cst)), *Context)) {
8963     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8964     // "inttoptr+GEP" instead of "add+intptr".
8965     
8966     // Get the size of the pointee type.
8967     uint64_t Size = TD->getTypeAllocSize(DestPointee);
8968     
8969     // Convert the constant to intptr type.
8970     APInt Offset = Cst->getValue();
8971     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8972     
8973     // If Offset is evenly divisible by Size, we can do this xform.
8974     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8975       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8976       
8977       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8978                                                             "tmp"), CI);
8979       return GetElementPtrInst::Create(P,
8980                                        Context->getConstantInt(Offset), "tmp");
8981     }
8982   }
8983   return 0;
8984 }
8985
8986 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8987   // If the operands are integer typed then apply the integer transforms,
8988   // otherwise just apply the common ones.
8989   Value *Src = CI.getOperand(0);
8990   const Type *SrcTy = Src->getType();
8991   const Type *DestTy = CI.getType();
8992
8993   if (isa<PointerType>(SrcTy)) {
8994     if (Instruction *I = commonPointerCastTransforms(CI))
8995       return I;
8996   } else {
8997     if (Instruction *Result = commonCastTransforms(CI))
8998       return Result;
8999   }
9000
9001
9002   // Get rid of casts from one type to the same type. These are useless and can
9003   // be replaced by the operand.
9004   if (DestTy == Src->getType())
9005     return ReplaceInstUsesWith(CI, Src);
9006
9007   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
9008     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
9009     const Type *DstElTy = DstPTy->getElementType();
9010     const Type *SrcElTy = SrcPTy->getElementType();
9011     
9012     // If the address spaces don't match, don't eliminate the bitcast, which is
9013     // required for changing types.
9014     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9015       return 0;
9016     
9017     // If we are casting a malloc or alloca to a pointer to a type of the same
9018     // size, rewrite the allocation instruction to allocate the "right" type.
9019     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
9020       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9021         return V;
9022     
9023     // If the source and destination are pointers, and this cast is equivalent
9024     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
9025     // This can enhance SROA and other transforms that want type-safe pointers.
9026     Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
9027     unsigned NumZeros = 0;
9028     while (SrcElTy != DstElTy && 
9029            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9030            SrcElTy->getNumContainedTypes() /* not "{}" */) {
9031       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9032       ++NumZeros;
9033     }
9034
9035     // If we found a path from the src to dest, create the getelementptr now.
9036     if (SrcElTy == DstElTy) {
9037       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
9038       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
9039                                        ((Instruction*) NULL));
9040     }
9041   }
9042
9043   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9044     if (SVI->hasOneUse()) {
9045       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
9046       // a bitconvert to a vector with the same # elts.
9047       if (isa<VectorType>(DestTy) && 
9048           cast<VectorType>(DestTy)->getNumElements() ==
9049                 SVI->getType()->getNumElements() &&
9050           SVI->getType()->getNumElements() ==
9051             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9052         CastInst *Tmp;
9053         // If either of the operands is a cast from CI.getType(), then
9054         // evaluating the shuffle in the casted destination's type will allow
9055         // us to eliminate at least one cast.
9056         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
9057              Tmp->getOperand(0)->getType() == DestTy) ||
9058             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
9059              Tmp->getOperand(0)->getType() == DestTy)) {
9060           Value *LHS = InsertCastBefore(Instruction::BitCast,
9061                                         SVI->getOperand(0), DestTy, CI);
9062           Value *RHS = InsertCastBefore(Instruction::BitCast,
9063                                         SVI->getOperand(1), DestTy, CI);
9064           // Return a new shuffle vector.  Use the same element ID's, as we
9065           // know the vector types match #elts.
9066           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9067         }
9068       }
9069     }
9070   }
9071   return 0;
9072 }
9073
9074 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9075 ///   %C = or %A, %B
9076 ///   %D = select %cond, %C, %A
9077 /// into:
9078 ///   %C = select %cond, %B, 0
9079 ///   %D = or %A, %C
9080 ///
9081 /// Assuming that the specified instruction is an operand to the select, return
9082 /// a bitmask indicating which operands of this instruction are foldable if they
9083 /// equal the other incoming value of the select.
9084 ///
9085 static unsigned GetSelectFoldableOperands(Instruction *I) {
9086   switch (I->getOpcode()) {
9087   case Instruction::Add:
9088   case Instruction::Mul:
9089   case Instruction::And:
9090   case Instruction::Or:
9091   case Instruction::Xor:
9092     return 3;              // Can fold through either operand.
9093   case Instruction::Sub:   // Can only fold on the amount subtracted.
9094   case Instruction::Shl:   // Can only fold on the shift amount.
9095   case Instruction::LShr:
9096   case Instruction::AShr:
9097     return 1;
9098   default:
9099     return 0;              // Cannot fold
9100   }
9101 }
9102
9103 /// GetSelectFoldableConstant - For the same transformation as the previous
9104 /// function, return the identity constant that goes into the select.
9105 static Constant *GetSelectFoldableConstant(Instruction *I,
9106                                            LLVMContext *Context) {
9107   switch (I->getOpcode()) {
9108   default: llvm_unreachable("This cannot happen!");
9109   case Instruction::Add:
9110   case Instruction::Sub:
9111   case Instruction::Or:
9112   case Instruction::Xor:
9113   case Instruction::Shl:
9114   case Instruction::LShr:
9115   case Instruction::AShr:
9116     return Context->getNullValue(I->getType());
9117   case Instruction::And:
9118     return Context->getAllOnesValue(I->getType());
9119   case Instruction::Mul:
9120     return Context->getConstantInt(I->getType(), 1);
9121   }
9122 }
9123
9124 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9125 /// have the same opcode and only one use each.  Try to simplify this.
9126 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9127                                           Instruction *FI) {
9128   if (TI->getNumOperands() == 1) {
9129     // If this is a non-volatile load or a cast from the same type,
9130     // merge.
9131     if (TI->isCast()) {
9132       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9133         return 0;
9134     } else {
9135       return 0;  // unknown unary op.
9136     }
9137
9138     // Fold this by inserting a select from the input values.
9139     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9140                                            FI->getOperand(0), SI.getName()+".v");
9141     InsertNewInstBefore(NewSI, SI);
9142     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9143                             TI->getType());
9144   }
9145
9146   // Only handle binary operators here.
9147   if (!isa<BinaryOperator>(TI))
9148     return 0;
9149
9150   // Figure out if the operations have any operands in common.
9151   Value *MatchOp, *OtherOpT, *OtherOpF;
9152   bool MatchIsOpZero;
9153   if (TI->getOperand(0) == FI->getOperand(0)) {
9154     MatchOp  = TI->getOperand(0);
9155     OtherOpT = TI->getOperand(1);
9156     OtherOpF = FI->getOperand(1);
9157     MatchIsOpZero = true;
9158   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9159     MatchOp  = TI->getOperand(1);
9160     OtherOpT = TI->getOperand(0);
9161     OtherOpF = FI->getOperand(0);
9162     MatchIsOpZero = false;
9163   } else if (!TI->isCommutative()) {
9164     return 0;
9165   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9166     MatchOp  = TI->getOperand(0);
9167     OtherOpT = TI->getOperand(1);
9168     OtherOpF = FI->getOperand(0);
9169     MatchIsOpZero = true;
9170   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9171     MatchOp  = TI->getOperand(1);
9172     OtherOpT = TI->getOperand(0);
9173     OtherOpF = FI->getOperand(1);
9174     MatchIsOpZero = true;
9175   } else {
9176     return 0;
9177   }
9178
9179   // If we reach here, they do have operations in common.
9180   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9181                                          OtherOpF, SI.getName()+".v");
9182   InsertNewInstBefore(NewSI, SI);
9183
9184   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9185     if (MatchIsOpZero)
9186       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9187     else
9188       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9189   }
9190   llvm_unreachable("Shouldn't get here");
9191   return 0;
9192 }
9193
9194 static bool isSelect01(Constant *C1, Constant *C2) {
9195   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9196   if (!C1I)
9197     return false;
9198   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9199   if (!C2I)
9200     return false;
9201   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9202 }
9203
9204 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9205 /// facilitate further optimization.
9206 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9207                                             Value *FalseVal) {
9208   // See the comment above GetSelectFoldableOperands for a description of the
9209   // transformation we are doing here.
9210   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9211     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9212         !isa<Constant>(FalseVal)) {
9213       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9214         unsigned OpToFold = 0;
9215         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9216           OpToFold = 1;
9217         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9218           OpToFold = 2;
9219         }
9220
9221         if (OpToFold) {
9222           Constant *C = GetSelectFoldableConstant(TVI, Context);
9223           Value *OOp = TVI->getOperand(2-OpToFold);
9224           // Avoid creating select between 2 constants unless it's selecting
9225           // between 0 and 1.
9226           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9227             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9228             InsertNewInstBefore(NewSel, SI);
9229             NewSel->takeName(TVI);
9230             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9231               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9232             llvm_unreachable("Unknown instruction!!");
9233           }
9234         }
9235       }
9236     }
9237   }
9238
9239   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9240     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9241         !isa<Constant>(TrueVal)) {
9242       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9243         unsigned OpToFold = 0;
9244         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9245           OpToFold = 1;
9246         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9247           OpToFold = 2;
9248         }
9249
9250         if (OpToFold) {
9251           Constant *C = GetSelectFoldableConstant(FVI, Context);
9252           Value *OOp = FVI->getOperand(2-OpToFold);
9253           // Avoid creating select between 2 constants unless it's selecting
9254           // between 0 and 1.
9255           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9256             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9257             InsertNewInstBefore(NewSel, SI);
9258             NewSel->takeName(FVI);
9259             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9260               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9261             llvm_unreachable("Unknown instruction!!");
9262           }
9263         }
9264       }
9265     }
9266   }
9267
9268   return 0;
9269 }
9270
9271 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9272 /// ICmpInst as its first operand.
9273 ///
9274 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9275                                                    ICmpInst *ICI) {
9276   bool Changed = false;
9277   ICmpInst::Predicate Pred = ICI->getPredicate();
9278   Value *CmpLHS = ICI->getOperand(0);
9279   Value *CmpRHS = ICI->getOperand(1);
9280   Value *TrueVal = SI.getTrueValue();
9281   Value *FalseVal = SI.getFalseValue();
9282
9283   // Check cases where the comparison is with a constant that
9284   // can be adjusted to fit the min/max idiom. We may edit ICI in
9285   // place here, so make sure the select is the only user.
9286   if (ICI->hasOneUse())
9287     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9288       switch (Pred) {
9289       default: break;
9290       case ICmpInst::ICMP_ULT:
9291       case ICmpInst::ICMP_SLT: {
9292         // X < MIN ? T : F  -->  F
9293         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9294           return ReplaceInstUsesWith(SI, FalseVal);
9295         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9296         Constant *AdjustedRHS = SubOne(CI, Context);
9297         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9298             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9299           Pred = ICmpInst::getSwappedPredicate(Pred);
9300           CmpRHS = AdjustedRHS;
9301           std::swap(FalseVal, TrueVal);
9302           ICI->setPredicate(Pred);
9303           ICI->setOperand(1, CmpRHS);
9304           SI.setOperand(1, TrueVal);
9305           SI.setOperand(2, FalseVal);
9306           Changed = true;
9307         }
9308         break;
9309       }
9310       case ICmpInst::ICMP_UGT:
9311       case ICmpInst::ICMP_SGT: {
9312         // X > MAX ? T : F  -->  F
9313         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9314           return ReplaceInstUsesWith(SI, FalseVal);
9315         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9316         Constant *AdjustedRHS = AddOne(CI, Context);
9317         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9318             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9319           Pred = ICmpInst::getSwappedPredicate(Pred);
9320           CmpRHS = AdjustedRHS;
9321           std::swap(FalseVal, TrueVal);
9322           ICI->setPredicate(Pred);
9323           ICI->setOperand(1, CmpRHS);
9324           SI.setOperand(1, TrueVal);
9325           SI.setOperand(2, FalseVal);
9326           Changed = true;
9327         }
9328         break;
9329       }
9330       }
9331
9332       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9333       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9334       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9335       if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9336           match(FalseVal, m_ConstantInt<0>(), *Context))
9337         Pred = ICI->getPredicate();
9338       else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9339                match(FalseVal, m_ConstantInt<-1>(), *Context))
9340         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9341       
9342       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9343         // If we are just checking for a icmp eq of a single bit and zext'ing it
9344         // to an integer, then shift the bit to the appropriate place and then
9345         // cast to integer to avoid the comparison.
9346         const APInt &Op1CV = CI->getValue();
9347     
9348         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9349         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9350         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9351             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9352           Value *In = ICI->getOperand(0);
9353           Value *Sh = Context->getConstantInt(In->getType(),
9354                                        In->getType()->getScalarSizeInBits()-1);
9355           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9356                                                           In->getName()+".lobit"),
9357                                    *ICI);
9358           if (In->getType() != SI.getType())
9359             In = CastInst::CreateIntegerCast(In, SI.getType(),
9360                                              true/*SExt*/, "tmp", ICI);
9361     
9362           if (Pred == ICmpInst::ICMP_SGT)
9363             In = InsertNewInstBefore(BinaryOperator::CreateNot(*Context, In,
9364                                        In->getName()+".not"), *ICI);
9365     
9366           return ReplaceInstUsesWith(SI, In);
9367         }
9368       }
9369     }
9370
9371   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9372     // Transform (X == Y) ? X : Y  -> Y
9373     if (Pred == ICmpInst::ICMP_EQ)
9374       return ReplaceInstUsesWith(SI, FalseVal);
9375     // Transform (X != Y) ? X : Y  -> X
9376     if (Pred == ICmpInst::ICMP_NE)
9377       return ReplaceInstUsesWith(SI, TrueVal);
9378     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9379
9380   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9381     // Transform (X == Y) ? Y : X  -> X
9382     if (Pred == ICmpInst::ICMP_EQ)
9383       return ReplaceInstUsesWith(SI, FalseVal);
9384     // Transform (X != Y) ? Y : X  -> Y
9385     if (Pred == ICmpInst::ICMP_NE)
9386       return ReplaceInstUsesWith(SI, TrueVal);
9387     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9388   }
9389
9390   /// NOTE: if we wanted to, this is where to detect integer ABS
9391
9392   return Changed ? &SI : 0;
9393 }
9394
9395 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9396   Value *CondVal = SI.getCondition();
9397   Value *TrueVal = SI.getTrueValue();
9398   Value *FalseVal = SI.getFalseValue();
9399
9400   // select true, X, Y  -> X
9401   // select false, X, Y -> Y
9402   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9403     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9404
9405   // select C, X, X -> X
9406   if (TrueVal == FalseVal)
9407     return ReplaceInstUsesWith(SI, TrueVal);
9408
9409   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9410     return ReplaceInstUsesWith(SI, FalseVal);
9411   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9412     return ReplaceInstUsesWith(SI, TrueVal);
9413   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9414     if (isa<Constant>(TrueVal))
9415       return ReplaceInstUsesWith(SI, TrueVal);
9416     else
9417       return ReplaceInstUsesWith(SI, FalseVal);
9418   }
9419
9420   if (SI.getType() == Type::Int1Ty) {
9421     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9422       if (C->getZExtValue()) {
9423         // Change: A = select B, true, C --> A = or B, C
9424         return BinaryOperator::CreateOr(CondVal, FalseVal);
9425       } else {
9426         // Change: A = select B, false, C --> A = and !B, C
9427         Value *NotCond =
9428           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9429                                              "not."+CondVal->getName()), SI);
9430         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9431       }
9432     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9433       if (C->getZExtValue() == false) {
9434         // Change: A = select B, C, false --> A = and B, C
9435         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9436       } else {
9437         // Change: A = select B, C, true --> A = or !B, C
9438         Value *NotCond =
9439           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9440                                              "not."+CondVal->getName()), SI);
9441         return BinaryOperator::CreateOr(NotCond, TrueVal);
9442       }
9443     }
9444     
9445     // select a, b, a  -> a&b
9446     // select a, a, b  -> a|b
9447     if (CondVal == TrueVal)
9448       return BinaryOperator::CreateOr(CondVal, FalseVal);
9449     else if (CondVal == FalseVal)
9450       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9451   }
9452
9453   // Selecting between two integer constants?
9454   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9455     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9456       // select C, 1, 0 -> zext C to int
9457       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9458         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9459       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9460         // select C, 0, 1 -> zext !C to int
9461         Value *NotCond =
9462           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9463                                                "not."+CondVal->getName()), SI);
9464         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9465       }
9466
9467       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9468         // If one of the constants is zero (we know they can't both be) and we
9469         // have an icmp instruction with zero, and we have an 'and' with the
9470         // non-constant value, eliminate this whole mess.  This corresponds to
9471         // cases like this: ((X & 27) ? 27 : 0)
9472         if (TrueValC->isZero() || FalseValC->isZero())
9473           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9474               cast<Constant>(IC->getOperand(1))->isNullValue())
9475             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9476               if (ICA->getOpcode() == Instruction::And &&
9477                   isa<ConstantInt>(ICA->getOperand(1)) &&
9478                   (ICA->getOperand(1) == TrueValC ||
9479                    ICA->getOperand(1) == FalseValC) &&
9480                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9481                 // Okay, now we know that everything is set up, we just don't
9482                 // know whether we have a icmp_ne or icmp_eq and whether the 
9483                 // true or false val is the zero.
9484                 bool ShouldNotVal = !TrueValC->isZero();
9485                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9486                 Value *V = ICA;
9487                 if (ShouldNotVal)
9488                   V = InsertNewInstBefore(BinaryOperator::Create(
9489                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9490                 return ReplaceInstUsesWith(SI, V);
9491               }
9492       }
9493     }
9494
9495   // See if we are selecting two values based on a comparison of the two values.
9496   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9497     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9498       // Transform (X == Y) ? X : Y  -> Y
9499       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9500         // This is not safe in general for floating point:  
9501         // consider X== -0, Y== +0.
9502         // It becomes safe if either operand is a nonzero constant.
9503         ConstantFP *CFPt, *CFPf;
9504         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9505               !CFPt->getValueAPF().isZero()) ||
9506             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9507              !CFPf->getValueAPF().isZero()))
9508         return ReplaceInstUsesWith(SI, FalseVal);
9509       }
9510       // Transform (X != Y) ? X : Y  -> X
9511       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9512         return ReplaceInstUsesWith(SI, TrueVal);
9513       // NOTE: if we wanted to, this is where to detect MIN/MAX
9514
9515     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9516       // Transform (X == Y) ? Y : X  -> X
9517       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9518         // This is not safe in general for floating point:  
9519         // consider X== -0, Y== +0.
9520         // It becomes safe if either operand is a nonzero constant.
9521         ConstantFP *CFPt, *CFPf;
9522         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9523               !CFPt->getValueAPF().isZero()) ||
9524             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9525              !CFPf->getValueAPF().isZero()))
9526           return ReplaceInstUsesWith(SI, FalseVal);
9527       }
9528       // Transform (X != Y) ? Y : X  -> Y
9529       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9530         return ReplaceInstUsesWith(SI, TrueVal);
9531       // NOTE: if we wanted to, this is where to detect MIN/MAX
9532     }
9533     // NOTE: if we wanted to, this is where to detect ABS
9534   }
9535
9536   // See if we are selecting two values based on a comparison of the two values.
9537   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9538     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9539       return Result;
9540
9541   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9542     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9543       if (TI->hasOneUse() && FI->hasOneUse()) {
9544         Instruction *AddOp = 0, *SubOp = 0;
9545
9546         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9547         if (TI->getOpcode() == FI->getOpcode())
9548           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9549             return IV;
9550
9551         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9552         // even legal for FP.
9553         if ((TI->getOpcode() == Instruction::Sub &&
9554              FI->getOpcode() == Instruction::Add) ||
9555             (TI->getOpcode() == Instruction::FSub &&
9556              FI->getOpcode() == Instruction::FAdd)) {
9557           AddOp = FI; SubOp = TI;
9558         } else if ((FI->getOpcode() == Instruction::Sub &&
9559                     TI->getOpcode() == Instruction::Add) ||
9560                    (FI->getOpcode() == Instruction::FSub &&
9561                     TI->getOpcode() == Instruction::FAdd)) {
9562           AddOp = TI; SubOp = FI;
9563         }
9564
9565         if (AddOp) {
9566           Value *OtherAddOp = 0;
9567           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9568             OtherAddOp = AddOp->getOperand(1);
9569           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9570             OtherAddOp = AddOp->getOperand(0);
9571           }
9572
9573           if (OtherAddOp) {
9574             // So at this point we know we have (Y -> OtherAddOp):
9575             //        select C, (add X, Y), (sub X, Z)
9576             Value *NegVal;  // Compute -Z
9577             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9578               NegVal = Context->getConstantExprNeg(C);
9579             } else {
9580               NegVal = InsertNewInstBefore(
9581                     BinaryOperator::CreateNeg(*Context, SubOp->getOperand(1),
9582                                               "tmp"), SI);
9583             }
9584
9585             Value *NewTrueOp = OtherAddOp;
9586             Value *NewFalseOp = NegVal;
9587             if (AddOp != TI)
9588               std::swap(NewTrueOp, NewFalseOp);
9589             Instruction *NewSel =
9590               SelectInst::Create(CondVal, NewTrueOp,
9591                                  NewFalseOp, SI.getName() + ".p");
9592
9593             NewSel = InsertNewInstBefore(NewSel, SI);
9594             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9595           }
9596         }
9597       }
9598
9599   // See if we can fold the select into one of our operands.
9600   if (SI.getType()->isInteger()) {
9601     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9602     if (FoldI)
9603       return FoldI;
9604   }
9605
9606   if (BinaryOperator::isNot(CondVal)) {
9607     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9608     SI.setOperand(1, FalseVal);
9609     SI.setOperand(2, TrueVal);
9610     return &SI;
9611   }
9612
9613   return 0;
9614 }
9615
9616 /// EnforceKnownAlignment - If the specified pointer points to an object that
9617 /// we control, modify the object's alignment to PrefAlign. This isn't
9618 /// often possible though. If alignment is important, a more reliable approach
9619 /// is to simply align all global variables and allocation instructions to
9620 /// their preferred alignment from the beginning.
9621 ///
9622 static unsigned EnforceKnownAlignment(Value *V,
9623                                       unsigned Align, unsigned PrefAlign) {
9624
9625   User *U = dyn_cast<User>(V);
9626   if (!U) return Align;
9627
9628   switch (getOpcode(U)) {
9629   default: break;
9630   case Instruction::BitCast:
9631     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9632   case Instruction::GetElementPtr: {
9633     // If all indexes are zero, it is just the alignment of the base pointer.
9634     bool AllZeroOperands = true;
9635     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9636       if (!isa<Constant>(*i) ||
9637           !cast<Constant>(*i)->isNullValue()) {
9638         AllZeroOperands = false;
9639         break;
9640       }
9641
9642     if (AllZeroOperands) {
9643       // Treat this like a bitcast.
9644       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9645     }
9646     break;
9647   }
9648   }
9649
9650   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9651     // If there is a large requested alignment and we can, bump up the alignment
9652     // of the global.
9653     if (!GV->isDeclaration()) {
9654       if (GV->getAlignment() >= PrefAlign)
9655         Align = GV->getAlignment();
9656       else {
9657         GV->setAlignment(PrefAlign);
9658         Align = PrefAlign;
9659       }
9660     }
9661   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9662     // If there is a requested alignment and if this is an alloca, round up.  We
9663     // don't do this for malloc, because some systems can't respect the request.
9664     if (isa<AllocaInst>(AI)) {
9665       if (AI->getAlignment() >= PrefAlign)
9666         Align = AI->getAlignment();
9667       else {
9668         AI->setAlignment(PrefAlign);
9669         Align = PrefAlign;
9670       }
9671     }
9672   }
9673
9674   return Align;
9675 }
9676
9677 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9678 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9679 /// and it is more than the alignment of the ultimate object, see if we can
9680 /// increase the alignment of the ultimate object, making this check succeed.
9681 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9682                                                   unsigned PrefAlign) {
9683   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9684                       sizeof(PrefAlign) * CHAR_BIT;
9685   APInt Mask = APInt::getAllOnesValue(BitWidth);
9686   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9687   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9688   unsigned TrailZ = KnownZero.countTrailingOnes();
9689   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9690
9691   if (PrefAlign > Align)
9692     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9693   
9694     // We don't need to make any adjustment.
9695   return Align;
9696 }
9697
9698 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9699   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9700   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9701   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9702   unsigned CopyAlign = MI->getAlignment();
9703
9704   if (CopyAlign < MinAlign) {
9705     MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(), 
9706                                              MinAlign, false));
9707     return MI;
9708   }
9709   
9710   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9711   // load/store.
9712   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9713   if (MemOpLength == 0) return 0;
9714   
9715   // Source and destination pointer types are always "i8*" for intrinsic.  See
9716   // if the size is something we can handle with a single primitive load/store.
9717   // A single load+store correctly handles overlapping memory in the memmove
9718   // case.
9719   unsigned Size = MemOpLength->getZExtValue();
9720   if (Size == 0) return MI;  // Delete this mem transfer.
9721   
9722   if (Size > 8 || (Size&(Size-1)))
9723     return 0;  // If not 1/2/4/8 bytes, exit.
9724   
9725   // Use an integer load+store unless we can find something better.
9726   Type *NewPtrTy =
9727                 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
9728   
9729   // Memcpy forces the use of i8* for the source and destination.  That means
9730   // that if you're using memcpy to move one double around, you'll get a cast
9731   // from double* to i8*.  We'd much rather use a double load+store rather than
9732   // an i64 load+store, here because this improves the odds that the source or
9733   // dest address will be promotable.  See if we can find a better type than the
9734   // integer datatype.
9735   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9736     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9737     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9738       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9739       // down through these levels if so.
9740       while (!SrcETy->isSingleValueType()) {
9741         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9742           if (STy->getNumElements() == 1)
9743             SrcETy = STy->getElementType(0);
9744           else
9745             break;
9746         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9747           if (ATy->getNumElements() == 1)
9748             SrcETy = ATy->getElementType();
9749           else
9750             break;
9751         } else
9752           break;
9753       }
9754       
9755       if (SrcETy->isSingleValueType())
9756         NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
9757     }
9758   }
9759   
9760   
9761   // If the memcpy/memmove provides better alignment info than we can
9762   // infer, use it.
9763   SrcAlign = std::max(SrcAlign, CopyAlign);
9764   DstAlign = std::max(DstAlign, CopyAlign);
9765   
9766   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9767   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9768   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9769   InsertNewInstBefore(L, *MI);
9770   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9771
9772   // Set the size of the copy to 0, it will be deleted on the next iteration.
9773   MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
9774   return MI;
9775 }
9776
9777 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9778   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9779   if (MI->getAlignment() < Alignment) {
9780     MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9781                                              Alignment, false));
9782     return MI;
9783   }
9784   
9785   // Extract the length and alignment and fill if they are constant.
9786   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9787   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9788   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9789     return 0;
9790   uint64_t Len = LenC->getZExtValue();
9791   Alignment = MI->getAlignment();
9792   
9793   // If the length is zero, this is a no-op
9794   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9795   
9796   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9797   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9798     const Type *ITy = Context->getIntegerType(Len*8);  // n=1 -> i8.
9799     
9800     Value *Dest = MI->getDest();
9801     Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
9802
9803     // Alignment 0 is identity for alignment 1 for memset, but not store.
9804     if (Alignment == 0) Alignment = 1;
9805     
9806     // Extract the fill value and store.
9807     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9808     InsertNewInstBefore(new StoreInst(Context->getConstantInt(ITy, Fill),
9809                                       Dest, false, Alignment), *MI);
9810     
9811     // Set the size of the copy to 0, it will be deleted on the next iteration.
9812     MI->setLength(Context->getNullValue(LenC->getType()));
9813     return MI;
9814   }
9815
9816   return 0;
9817 }
9818
9819
9820 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9821 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9822 /// the heavy lifting.
9823 ///
9824 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9825   // If the caller function is nounwind, mark the call as nounwind, even if the
9826   // callee isn't.
9827   if (CI.getParent()->getParent()->doesNotThrow() &&
9828       !CI.doesNotThrow()) {
9829     CI.setDoesNotThrow();
9830     return &CI;
9831   }
9832   
9833   
9834   
9835   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9836   if (!II) return visitCallSite(&CI);
9837   
9838   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9839   // visitCallSite.
9840   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9841     bool Changed = false;
9842
9843     // memmove/cpy/set of zero bytes is a noop.
9844     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9845       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9846
9847       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9848         if (CI->getZExtValue() == 1) {
9849           // Replace the instruction with just byte operations.  We would
9850           // transform other cases to loads/stores, but we don't know if
9851           // alignment is sufficient.
9852         }
9853     }
9854
9855     // If we have a memmove and the source operation is a constant global,
9856     // then the source and dest pointers can't alias, so we can change this
9857     // into a call to memcpy.
9858     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9859       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9860         if (GVSrc->isConstant()) {
9861           Module *M = CI.getParent()->getParent()->getParent();
9862           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9863           const Type *Tys[1];
9864           Tys[0] = CI.getOperand(3)->getType();
9865           CI.setOperand(0, 
9866                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9867           Changed = true;
9868         }
9869
9870       // memmove(x,x,size) -> noop.
9871       if (MMI->getSource() == MMI->getDest())
9872         return EraseInstFromFunction(CI);
9873     }
9874
9875     // If we can determine a pointer alignment that is bigger than currently
9876     // set, update the alignment.
9877     if (isa<MemTransferInst>(MI)) {
9878       if (Instruction *I = SimplifyMemTransfer(MI))
9879         return I;
9880     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9881       if (Instruction *I = SimplifyMemSet(MSI))
9882         return I;
9883     }
9884           
9885     if (Changed) return II;
9886   }
9887   
9888   switch (II->getIntrinsicID()) {
9889   default: break;
9890   case Intrinsic::bswap:
9891     // bswap(bswap(x)) -> x
9892     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9893       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9894         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9895     break;
9896   case Intrinsic::ppc_altivec_lvx:
9897   case Intrinsic::ppc_altivec_lvxl:
9898   case Intrinsic::x86_sse_loadu_ps:
9899   case Intrinsic::x86_sse2_loadu_pd:
9900   case Intrinsic::x86_sse2_loadu_dq:
9901     // Turn PPC lvx     -> load if the pointer is known aligned.
9902     // Turn X86 loadups -> load if the pointer is known aligned.
9903     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9904       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9905                                    Context->getPointerTypeUnqual(II->getType()),
9906                                        CI);
9907       return new LoadInst(Ptr);
9908     }
9909     break;
9910   case Intrinsic::ppc_altivec_stvx:
9911   case Intrinsic::ppc_altivec_stvxl:
9912     // Turn stvx -> store if the pointer is known aligned.
9913     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9914       const Type *OpPtrTy = 
9915         Context->getPointerTypeUnqual(II->getOperand(1)->getType());
9916       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9917       return new StoreInst(II->getOperand(1), Ptr);
9918     }
9919     break;
9920   case Intrinsic::x86_sse_storeu_ps:
9921   case Intrinsic::x86_sse2_storeu_pd:
9922   case Intrinsic::x86_sse2_storeu_dq:
9923     // Turn X86 storeu -> store if the pointer is known aligned.
9924     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9925       const Type *OpPtrTy = 
9926         Context->getPointerTypeUnqual(II->getOperand(2)->getType());
9927       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9928       return new StoreInst(II->getOperand(2), Ptr);
9929     }
9930     break;
9931     
9932   case Intrinsic::x86_sse_cvttss2si: {
9933     // These intrinsics only demands the 0th element of its input vector.  If
9934     // we can simplify the input based on that, do so now.
9935     unsigned VWidth =
9936       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9937     APInt DemandedElts(VWidth, 1);
9938     APInt UndefElts(VWidth, 0);
9939     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9940                                               UndefElts)) {
9941       II->setOperand(1, V);
9942       return II;
9943     }
9944     break;
9945   }
9946     
9947   case Intrinsic::ppc_altivec_vperm:
9948     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9949     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9950       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9951       
9952       // Check that all of the elements are integer constants or undefs.
9953       bool AllEltsOk = true;
9954       for (unsigned i = 0; i != 16; ++i) {
9955         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9956             !isa<UndefValue>(Mask->getOperand(i))) {
9957           AllEltsOk = false;
9958           break;
9959         }
9960       }
9961       
9962       if (AllEltsOk) {
9963         // Cast the input vectors to byte vectors.
9964         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9965         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9966         Value *Result = Context->getUndef(Op0->getType());
9967         
9968         // Only extract each element once.
9969         Value *ExtractedElts[32];
9970         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9971         
9972         for (unsigned i = 0; i != 16; ++i) {
9973           if (isa<UndefValue>(Mask->getOperand(i)))
9974             continue;
9975           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9976           Idx &= 31;  // Match the hardware behavior.
9977           
9978           if (ExtractedElts[Idx] == 0) {
9979             Instruction *Elt = 
9980               new ExtractElementInst(Idx < 16 ? Op0 : Op1, 
9981                   Context->getConstantInt(Type::Int32Ty, Idx&15, false), "tmp");
9982             InsertNewInstBefore(Elt, CI);
9983             ExtractedElts[Idx] = Elt;
9984           }
9985         
9986           // Insert this value into the result vector.
9987           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9988                                Context->getConstantInt(Type::Int32Ty, i, false), 
9989                                "tmp");
9990           InsertNewInstBefore(cast<Instruction>(Result), CI);
9991         }
9992         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9993       }
9994     }
9995     break;
9996
9997   case Intrinsic::stackrestore: {
9998     // If the save is right next to the restore, remove the restore.  This can
9999     // happen when variable allocas are DCE'd.
10000     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10001       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10002         BasicBlock::iterator BI = SS;
10003         if (&*++BI == II)
10004           return EraseInstFromFunction(CI);
10005       }
10006     }
10007     
10008     // Scan down this block to see if there is another stack restore in the
10009     // same block without an intervening call/alloca.
10010     BasicBlock::iterator BI = II;
10011     TerminatorInst *TI = II->getParent()->getTerminator();
10012     bool CannotRemove = false;
10013     for (++BI; &*BI != TI; ++BI) {
10014       if (isa<AllocaInst>(BI)) {
10015         CannotRemove = true;
10016         break;
10017       }
10018       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10019         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10020           // If there is a stackrestore below this one, remove this one.
10021           if (II->getIntrinsicID() == Intrinsic::stackrestore)
10022             return EraseInstFromFunction(CI);
10023           // Otherwise, ignore the intrinsic.
10024         } else {
10025           // If we found a non-intrinsic call, we can't remove the stack
10026           // restore.
10027           CannotRemove = true;
10028           break;
10029         }
10030       }
10031     }
10032     
10033     // If the stack restore is in a return/unwind block and if there are no
10034     // allocas or calls between the restore and the return, nuke the restore.
10035     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10036       return EraseInstFromFunction(CI);
10037     break;
10038   }
10039   }
10040
10041   return visitCallSite(II);
10042 }
10043
10044 // InvokeInst simplification
10045 //
10046 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10047   return visitCallSite(&II);
10048 }
10049
10050 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
10051 /// passed through the varargs area, we can eliminate the use of the cast.
10052 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10053                                          const CastInst * const CI,
10054                                          const TargetData * const TD,
10055                                          const int ix) {
10056   if (!CI->isLosslessCast())
10057     return false;
10058
10059   // The size of ByVal arguments is derived from the type, so we
10060   // can't change to a type with a different size.  If the size were
10061   // passed explicitly we could avoid this check.
10062   if (!CS.paramHasAttr(ix, Attribute::ByVal))
10063     return true;
10064
10065   const Type* SrcTy = 
10066             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10067   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10068   if (!SrcTy->isSized() || !DstTy->isSized())
10069     return false;
10070   if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10071     return false;
10072   return true;
10073 }
10074
10075 // visitCallSite - Improvements for call and invoke instructions.
10076 //
10077 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10078   bool Changed = false;
10079
10080   // If the callee is a constexpr cast of a function, attempt to move the cast
10081   // to the arguments of the call/invoke.
10082   if (transformConstExprCastCall(CS)) return 0;
10083
10084   Value *Callee = CS.getCalledValue();
10085
10086   if (Function *CalleeF = dyn_cast<Function>(Callee))
10087     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10088       Instruction *OldCall = CS.getInstruction();
10089       // If the call and callee calling conventions don't match, this call must
10090       // be unreachable, as the call is undefined.
10091       new StoreInst(Context->getConstantIntTrue(),
10092                 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), 
10093                                   OldCall);
10094       if (!OldCall->use_empty())
10095         OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
10096       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10097         return EraseInstFromFunction(*OldCall);
10098       return 0;
10099     }
10100
10101   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10102     // This instruction is not reachable, just remove it.  We insert a store to
10103     // undef so that we know that this code is not reachable, despite the fact
10104     // that we can't modify the CFG here.
10105     new StoreInst(Context->getConstantIntTrue(),
10106                Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10107                   CS.getInstruction());
10108
10109     if (!CS.getInstruction()->use_empty())
10110       CS.getInstruction()->
10111         replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
10112
10113     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10114       // Don't break the CFG, insert a dummy cond branch.
10115       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10116                          Context->getConstantIntTrue(), II);
10117     }
10118     return EraseInstFromFunction(*CS.getInstruction());
10119   }
10120
10121   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10122     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10123       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10124         return transformCallThroughTrampoline(CS);
10125
10126   const PointerType *PTy = cast<PointerType>(Callee->getType());
10127   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10128   if (FTy->isVarArg()) {
10129     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10130     // See if we can optimize any arguments passed through the varargs area of
10131     // the call.
10132     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10133            E = CS.arg_end(); I != E; ++I, ++ix) {
10134       CastInst *CI = dyn_cast<CastInst>(*I);
10135       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10136         *I = CI->getOperand(0);
10137         Changed = true;
10138       }
10139     }
10140   }
10141
10142   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10143     // Inline asm calls cannot throw - mark them 'nounwind'.
10144     CS.setDoesNotThrow();
10145     Changed = true;
10146   }
10147
10148   return Changed ? CS.getInstruction() : 0;
10149 }
10150
10151 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10152 // attempt to move the cast to the arguments of the call/invoke.
10153 //
10154 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10155   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10156   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10157   if (CE->getOpcode() != Instruction::BitCast || 
10158       !isa<Function>(CE->getOperand(0)))
10159     return false;
10160   Function *Callee = cast<Function>(CE->getOperand(0));
10161   Instruction *Caller = CS.getInstruction();
10162   const AttrListPtr &CallerPAL = CS.getAttributes();
10163
10164   // Okay, this is a cast from a function to a different type.  Unless doing so
10165   // would cause a type conversion of one of our arguments, change this call to
10166   // be a direct call with arguments casted to the appropriate types.
10167   //
10168   const FunctionType *FT = Callee->getFunctionType();
10169   const Type *OldRetTy = Caller->getType();
10170   const Type *NewRetTy = FT->getReturnType();
10171
10172   if (isa<StructType>(NewRetTy))
10173     return false; // TODO: Handle multiple return values.
10174
10175   // Check to see if we are changing the return type...
10176   if (OldRetTy != NewRetTy) {
10177     if (Callee->isDeclaration() &&
10178         // Conversion is ok if changing from one pointer type to another or from
10179         // a pointer to an integer of the same size.
10180         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
10181           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
10182       return false;   // Cannot transform this return value.
10183
10184     if (!Caller->use_empty() &&
10185         // void -> non-void is handled specially
10186         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
10187       return false;   // Cannot transform this return value.
10188
10189     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10190       Attributes RAttrs = CallerPAL.getRetAttributes();
10191       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10192         return false;   // Attribute not compatible with transformed value.
10193     }
10194
10195     // If the callsite is an invoke instruction, and the return value is used by
10196     // a PHI node in a successor, we cannot change the return type of the call
10197     // because there is no place to put the cast instruction (without breaking
10198     // the critical edge).  Bail out in this case.
10199     if (!Caller->use_empty())
10200       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10201         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10202              UI != E; ++UI)
10203           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10204             if (PN->getParent() == II->getNormalDest() ||
10205                 PN->getParent() == II->getUnwindDest())
10206               return false;
10207   }
10208
10209   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10210   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10211
10212   CallSite::arg_iterator AI = CS.arg_begin();
10213   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10214     const Type *ParamTy = FT->getParamType(i);
10215     const Type *ActTy = (*AI)->getType();
10216
10217     if (!CastInst::isCastable(ActTy, ParamTy))
10218       return false;   // Cannot transform this parameter value.
10219
10220     if (CallerPAL.getParamAttributes(i + 1) 
10221         & Attribute::typeIncompatible(ParamTy))
10222       return false;   // Attribute not compatible with transformed value.
10223
10224     // Converting from one pointer type to another or between a pointer and an
10225     // integer of the same size is safe even if we do not have a body.
10226     bool isConvertible = ActTy == ParamTy ||
10227       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10228        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
10229     if (Callee->isDeclaration() && !isConvertible) return false;
10230   }
10231
10232   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10233       Callee->isDeclaration())
10234     return false;   // Do not delete arguments unless we have a function body.
10235
10236   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10237       !CallerPAL.isEmpty())
10238     // In this case we have more arguments than the new function type, but we
10239     // won't be dropping them.  Check that these extra arguments have attributes
10240     // that are compatible with being a vararg call argument.
10241     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10242       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10243         break;
10244       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10245       if (PAttrs & Attribute::VarArgsIncompatible)
10246         return false;
10247     }
10248
10249   // Okay, we decided that this is a safe thing to do: go ahead and start
10250   // inserting cast instructions as necessary...
10251   std::vector<Value*> Args;
10252   Args.reserve(NumActualArgs);
10253   SmallVector<AttributeWithIndex, 8> attrVec;
10254   attrVec.reserve(NumCommonArgs);
10255
10256   // Get any return attributes.
10257   Attributes RAttrs = CallerPAL.getRetAttributes();
10258
10259   // If the return value is not being used, the type may not be compatible
10260   // with the existing attributes.  Wipe out any problematic attributes.
10261   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10262
10263   // Add the new return attributes.
10264   if (RAttrs)
10265     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10266
10267   AI = CS.arg_begin();
10268   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10269     const Type *ParamTy = FT->getParamType(i);
10270     if ((*AI)->getType() == ParamTy) {
10271       Args.push_back(*AI);
10272     } else {
10273       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10274           false, ParamTy, false);
10275       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10276       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10277     }
10278
10279     // Add any parameter attributes.
10280     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10281       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10282   }
10283
10284   // If the function takes more arguments than the call was taking, add them
10285   // now...
10286   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10287     Args.push_back(Context->getNullValue(FT->getParamType(i)));
10288
10289   // If we are removing arguments to the function, emit an obnoxious warning...
10290   if (FT->getNumParams() < NumActualArgs) {
10291     if (!FT->isVarArg()) {
10292       cerr << "WARNING: While resolving call to function '"
10293            << Callee->getName() << "' arguments were dropped!\n";
10294     } else {
10295       // Add all of the arguments in their promoted form to the arg list...
10296       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10297         const Type *PTy = getPromotedType((*AI)->getType());
10298         if (PTy != (*AI)->getType()) {
10299           // Must promote to pass through va_arg area!
10300           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
10301                                                                 PTy, false);
10302           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10303           InsertNewInstBefore(Cast, *Caller);
10304           Args.push_back(Cast);
10305         } else {
10306           Args.push_back(*AI);
10307         }
10308
10309         // Add any parameter attributes.
10310         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10311           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10312       }
10313     }
10314   }
10315
10316   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10317     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10318
10319   if (NewRetTy == Type::VoidTy)
10320     Caller->setName("");   // Void type should not have a name.
10321
10322   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
10323
10324   Instruction *NC;
10325   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10326     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10327                             Args.begin(), Args.end(),
10328                             Caller->getName(), Caller);
10329     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10330     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10331   } else {
10332     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10333                           Caller->getName(), Caller);
10334     CallInst *CI = cast<CallInst>(Caller);
10335     if (CI->isTailCall())
10336       cast<CallInst>(NC)->setTailCall();
10337     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10338     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10339   }
10340
10341   // Insert a cast of the return type as necessary.
10342   Value *NV = NC;
10343   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10344     if (NV->getType() != Type::VoidTy) {
10345       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10346                                                             OldRetTy, false);
10347       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10348
10349       // If this is an invoke instruction, we should insert it after the first
10350       // non-phi, instruction in the normal successor block.
10351       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10352         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10353         InsertNewInstBefore(NC, *I);
10354       } else {
10355         // Otherwise, it's a call, just insert cast right after the call instr
10356         InsertNewInstBefore(NC, *Caller);
10357       }
10358       AddUsersToWorkList(*Caller);
10359     } else {
10360       NV = Context->getUndef(Caller->getType());
10361     }
10362   }
10363
10364   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10365     Caller->replaceAllUsesWith(NV);
10366   Caller->eraseFromParent();
10367   RemoveFromWorkList(Caller);
10368   return true;
10369 }
10370
10371 // transformCallThroughTrampoline - Turn a call to a function created by the
10372 // init_trampoline intrinsic into a direct call to the underlying function.
10373 //
10374 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10375   Value *Callee = CS.getCalledValue();
10376   const PointerType *PTy = cast<PointerType>(Callee->getType());
10377   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10378   const AttrListPtr &Attrs = CS.getAttributes();
10379
10380   // If the call already has the 'nest' attribute somewhere then give up -
10381   // otherwise 'nest' would occur twice after splicing in the chain.
10382   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10383     return 0;
10384
10385   IntrinsicInst *Tramp =
10386     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10387
10388   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10389   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10390   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10391
10392   const AttrListPtr &NestAttrs = NestF->getAttributes();
10393   if (!NestAttrs.isEmpty()) {
10394     unsigned NestIdx = 1;
10395     const Type *NestTy = 0;
10396     Attributes NestAttr = Attribute::None;
10397
10398     // Look for a parameter marked with the 'nest' attribute.
10399     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10400          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10401       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10402         // Record the parameter type and any other attributes.
10403         NestTy = *I;
10404         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10405         break;
10406       }
10407
10408     if (NestTy) {
10409       Instruction *Caller = CS.getInstruction();
10410       std::vector<Value*> NewArgs;
10411       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10412
10413       SmallVector<AttributeWithIndex, 8> NewAttrs;
10414       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10415
10416       // Insert the nest argument into the call argument list, which may
10417       // mean appending it.  Likewise for attributes.
10418
10419       // Add any result attributes.
10420       if (Attributes Attr = Attrs.getRetAttributes())
10421         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10422
10423       {
10424         unsigned Idx = 1;
10425         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10426         do {
10427           if (Idx == NestIdx) {
10428             // Add the chain argument and attributes.
10429             Value *NestVal = Tramp->getOperand(3);
10430             if (NestVal->getType() != NestTy)
10431               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10432             NewArgs.push_back(NestVal);
10433             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10434           }
10435
10436           if (I == E)
10437             break;
10438
10439           // Add the original argument and attributes.
10440           NewArgs.push_back(*I);
10441           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10442             NewAttrs.push_back
10443               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10444
10445           ++Idx, ++I;
10446         } while (1);
10447       }
10448
10449       // Add any function attributes.
10450       if (Attributes Attr = Attrs.getFnAttributes())
10451         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10452
10453       // The trampoline may have been bitcast to a bogus type (FTy).
10454       // Handle this by synthesizing a new function type, equal to FTy
10455       // with the chain parameter inserted.
10456
10457       std::vector<const Type*> NewTypes;
10458       NewTypes.reserve(FTy->getNumParams()+1);
10459
10460       // Insert the chain's type into the list of parameter types, which may
10461       // mean appending it.
10462       {
10463         unsigned Idx = 1;
10464         FunctionType::param_iterator I = FTy->param_begin(),
10465           E = FTy->param_end();
10466
10467         do {
10468           if (Idx == NestIdx)
10469             // Add the chain's type.
10470             NewTypes.push_back(NestTy);
10471
10472           if (I == E)
10473             break;
10474
10475           // Add the original type.
10476           NewTypes.push_back(*I);
10477
10478           ++Idx, ++I;
10479         } while (1);
10480       }
10481
10482       // Replace the trampoline call with a direct call.  Let the generic
10483       // code sort out any function type mismatches.
10484       FunctionType *NewFTy =
10485                        Context->getFunctionType(FTy->getReturnType(), NewTypes, 
10486                                                 FTy->isVarArg());
10487       Constant *NewCallee =
10488         NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10489         NestF : Context->getConstantExprBitCast(NestF, 
10490                                          Context->getPointerTypeUnqual(NewFTy));
10491       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
10492
10493       Instruction *NewCaller;
10494       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10495         NewCaller = InvokeInst::Create(NewCallee,
10496                                        II->getNormalDest(), II->getUnwindDest(),
10497                                        NewArgs.begin(), NewArgs.end(),
10498                                        Caller->getName(), Caller);
10499         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10500         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10501       } else {
10502         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10503                                      Caller->getName(), Caller);
10504         if (cast<CallInst>(Caller)->isTailCall())
10505           cast<CallInst>(NewCaller)->setTailCall();
10506         cast<CallInst>(NewCaller)->
10507           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10508         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10509       }
10510       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10511         Caller->replaceAllUsesWith(NewCaller);
10512       Caller->eraseFromParent();
10513       RemoveFromWorkList(Caller);
10514       return 0;
10515     }
10516   }
10517
10518   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10519   // parameter, there is no need to adjust the argument list.  Let the generic
10520   // code sort out any function type mismatches.
10521   Constant *NewCallee =
10522     NestF->getType() == PTy ? NestF : 
10523                               Context->getConstantExprBitCast(NestF, PTy);
10524   CS.setCalledFunction(NewCallee);
10525   return CS.getInstruction();
10526 }
10527
10528 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10529 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10530 /// and a single binop.
10531 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10532   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10533   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10534   unsigned Opc = FirstInst->getOpcode();
10535   Value *LHSVal = FirstInst->getOperand(0);
10536   Value *RHSVal = FirstInst->getOperand(1);
10537     
10538   const Type *LHSType = LHSVal->getType();
10539   const Type *RHSType = RHSVal->getType();
10540   
10541   // Scan to see if all operands are the same opcode, all have one use, and all
10542   // kill their operands (i.e. the operands have one use).
10543   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10544     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10545     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10546         // Verify type of the LHS matches so we don't fold cmp's of different
10547         // types or GEP's with different index types.
10548         I->getOperand(0)->getType() != LHSType ||
10549         I->getOperand(1)->getType() != RHSType)
10550       return 0;
10551
10552     // If they are CmpInst instructions, check their predicates
10553     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10554       if (cast<CmpInst>(I)->getPredicate() !=
10555           cast<CmpInst>(FirstInst)->getPredicate())
10556         return 0;
10557     
10558     // Keep track of which operand needs a phi node.
10559     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10560     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10561   }
10562   
10563   // Otherwise, this is safe to transform!
10564   
10565   Value *InLHS = FirstInst->getOperand(0);
10566   Value *InRHS = FirstInst->getOperand(1);
10567   PHINode *NewLHS = 0, *NewRHS = 0;
10568   if (LHSVal == 0) {
10569     NewLHS = PHINode::Create(LHSType,
10570                              FirstInst->getOperand(0)->getName() + ".pn");
10571     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10572     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10573     InsertNewInstBefore(NewLHS, PN);
10574     LHSVal = NewLHS;
10575   }
10576   
10577   if (RHSVal == 0) {
10578     NewRHS = PHINode::Create(RHSType,
10579                              FirstInst->getOperand(1)->getName() + ".pn");
10580     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10581     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10582     InsertNewInstBefore(NewRHS, PN);
10583     RHSVal = NewRHS;
10584   }
10585   
10586   // Add all operands to the new PHIs.
10587   if (NewLHS || NewRHS) {
10588     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10589       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10590       if (NewLHS) {
10591         Value *NewInLHS = InInst->getOperand(0);
10592         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10593       }
10594       if (NewRHS) {
10595         Value *NewInRHS = InInst->getOperand(1);
10596         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10597       }
10598     }
10599   }
10600     
10601   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10602     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10603   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10604   return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10605                          LHSVal, RHSVal);
10606 }
10607
10608 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10609   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10610   
10611   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10612                                         FirstInst->op_end());
10613   // This is true if all GEP bases are allocas and if all indices into them are
10614   // constants.
10615   bool AllBasePointersAreAllocas = true;
10616   
10617   // Scan to see if all operands are the same opcode, all have one use, and all
10618   // kill their operands (i.e. the operands have one use).
10619   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10620     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10621     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10622       GEP->getNumOperands() != FirstInst->getNumOperands())
10623       return 0;
10624
10625     // Keep track of whether or not all GEPs are of alloca pointers.
10626     if (AllBasePointersAreAllocas &&
10627         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10628          !GEP->hasAllConstantIndices()))
10629       AllBasePointersAreAllocas = false;
10630     
10631     // Compare the operand lists.
10632     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10633       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10634         continue;
10635       
10636       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10637       // if one of the PHIs has a constant for the index.  The index may be
10638       // substantially cheaper to compute for the constants, so making it a
10639       // variable index could pessimize the path.  This also handles the case
10640       // for struct indices, which must always be constant.
10641       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10642           isa<ConstantInt>(GEP->getOperand(op)))
10643         return 0;
10644       
10645       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10646         return 0;
10647       FixedOperands[op] = 0;  // Needs a PHI.
10648     }
10649   }
10650   
10651   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10652   // bother doing this transformation.  At best, this will just save a bit of
10653   // offset calculation, but all the predecessors will have to materialize the
10654   // stack address into a register anyway.  We'd actually rather *clone* the
10655   // load up into the predecessors so that we have a load of a gep of an alloca,
10656   // which can usually all be folded into the load.
10657   if (AllBasePointersAreAllocas)
10658     return 0;
10659   
10660   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10661   // that is variable.
10662   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10663   
10664   bool HasAnyPHIs = false;
10665   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10666     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10667     Value *FirstOp = FirstInst->getOperand(i);
10668     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10669                                      FirstOp->getName()+".pn");
10670     InsertNewInstBefore(NewPN, PN);
10671     
10672     NewPN->reserveOperandSpace(e);
10673     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10674     OperandPhis[i] = NewPN;
10675     FixedOperands[i] = NewPN;
10676     HasAnyPHIs = true;
10677   }
10678
10679   
10680   // Add all operands to the new PHIs.
10681   if (HasAnyPHIs) {
10682     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10683       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10684       BasicBlock *InBB = PN.getIncomingBlock(i);
10685       
10686       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10687         if (PHINode *OpPhi = OperandPhis[op])
10688           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10689     }
10690   }
10691   
10692   Value *Base = FixedOperands[0];
10693   return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10694                                    FixedOperands.end());
10695 }
10696
10697
10698 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10699 /// sink the load out of the block that defines it.  This means that it must be
10700 /// obvious the value of the load is not changed from the point of the load to
10701 /// the end of the block it is in.
10702 ///
10703 /// Finally, it is safe, but not profitable, to sink a load targetting a
10704 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10705 /// to a register.
10706 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10707   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10708   
10709   for (++BBI; BBI != E; ++BBI)
10710     if (BBI->mayWriteToMemory())
10711       return false;
10712   
10713   // Check for non-address taken alloca.  If not address-taken already, it isn't
10714   // profitable to do this xform.
10715   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10716     bool isAddressTaken = false;
10717     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10718          UI != E; ++UI) {
10719       if (isa<LoadInst>(UI)) continue;
10720       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10721         // If storing TO the alloca, then the address isn't taken.
10722         if (SI->getOperand(1) == AI) continue;
10723       }
10724       isAddressTaken = true;
10725       break;
10726     }
10727     
10728     if (!isAddressTaken && AI->isStaticAlloca())
10729       return false;
10730   }
10731   
10732   // If this load is a load from a GEP with a constant offset from an alloca,
10733   // then we don't want to sink it.  In its present form, it will be
10734   // load [constant stack offset].  Sinking it will cause us to have to
10735   // materialize the stack addresses in each predecessor in a register only to
10736   // do a shared load from register in the successor.
10737   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10738     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10739       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10740         return false;
10741   
10742   return true;
10743 }
10744
10745
10746 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10747 // operator and they all are only used by the PHI, PHI together their
10748 // inputs, and do the operation once, to the result of the PHI.
10749 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10750   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10751
10752   // Scan the instruction, looking for input operations that can be folded away.
10753   // If all input operands to the phi are the same instruction (e.g. a cast from
10754   // the same type or "+42") we can pull the operation through the PHI, reducing
10755   // code size and simplifying code.
10756   Constant *ConstantOp = 0;
10757   const Type *CastSrcTy = 0;
10758   bool isVolatile = false;
10759   if (isa<CastInst>(FirstInst)) {
10760     CastSrcTy = FirstInst->getOperand(0)->getType();
10761   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10762     // Can fold binop, compare or shift here if the RHS is a constant, 
10763     // otherwise call FoldPHIArgBinOpIntoPHI.
10764     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10765     if (ConstantOp == 0)
10766       return FoldPHIArgBinOpIntoPHI(PN);
10767   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10768     isVolatile = LI->isVolatile();
10769     // We can't sink the load if the loaded value could be modified between the
10770     // load and the PHI.
10771     if (LI->getParent() != PN.getIncomingBlock(0) ||
10772         !isSafeAndProfitableToSinkLoad(LI))
10773       return 0;
10774     
10775     // If the PHI is of volatile loads and the load block has multiple
10776     // successors, sinking it would remove a load of the volatile value from
10777     // the path through the other successor.
10778     if (isVolatile &&
10779         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10780       return 0;
10781     
10782   } else if (isa<GetElementPtrInst>(FirstInst)) {
10783     return FoldPHIArgGEPIntoPHI(PN);
10784   } else {
10785     return 0;  // Cannot fold this operation.
10786   }
10787
10788   // Check to see if all arguments are the same operation.
10789   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10790     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10791     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10792     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10793       return 0;
10794     if (CastSrcTy) {
10795       if (I->getOperand(0)->getType() != CastSrcTy)
10796         return 0;  // Cast operation must match.
10797     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10798       // We can't sink the load if the loaded value could be modified between 
10799       // the load and the PHI.
10800       if (LI->isVolatile() != isVolatile ||
10801           LI->getParent() != PN.getIncomingBlock(i) ||
10802           !isSafeAndProfitableToSinkLoad(LI))
10803         return 0;
10804       
10805       // If the PHI is of volatile loads and the load block has multiple
10806       // successors, sinking it would remove a load of the volatile value from
10807       // the path through the other successor.
10808       if (isVolatile &&
10809           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10810         return 0;
10811       
10812     } else if (I->getOperand(1) != ConstantOp) {
10813       return 0;
10814     }
10815   }
10816
10817   // Okay, they are all the same operation.  Create a new PHI node of the
10818   // correct type, and PHI together all of the LHS's of the instructions.
10819   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10820                                    PN.getName()+".in");
10821   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10822
10823   Value *InVal = FirstInst->getOperand(0);
10824   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10825
10826   // Add all operands to the new PHI.
10827   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10828     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10829     if (NewInVal != InVal)
10830       InVal = 0;
10831     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10832   }
10833
10834   Value *PhiVal;
10835   if (InVal) {
10836     // The new PHI unions all of the same values together.  This is really
10837     // common, so we handle it intelligently here for compile-time speed.
10838     PhiVal = InVal;
10839     delete NewPN;
10840   } else {
10841     InsertNewInstBefore(NewPN, PN);
10842     PhiVal = NewPN;
10843   }
10844
10845   // Insert and return the new operation.
10846   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10847     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10848   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10849     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10850   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10851     return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10852                            PhiVal, ConstantOp);
10853   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10854   
10855   // If this was a volatile load that we are merging, make sure to loop through
10856   // and mark all the input loads as non-volatile.  If we don't do this, we will
10857   // insert a new volatile load and the old ones will not be deletable.
10858   if (isVolatile)
10859     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10860       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10861   
10862   return new LoadInst(PhiVal, "", isVolatile);
10863 }
10864
10865 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10866 /// that is dead.
10867 static bool DeadPHICycle(PHINode *PN,
10868                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10869   if (PN->use_empty()) return true;
10870   if (!PN->hasOneUse()) return false;
10871
10872   // Remember this node, and if we find the cycle, return.
10873   if (!PotentiallyDeadPHIs.insert(PN))
10874     return true;
10875   
10876   // Don't scan crazily complex things.
10877   if (PotentiallyDeadPHIs.size() == 16)
10878     return false;
10879
10880   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10881     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10882
10883   return false;
10884 }
10885
10886 /// PHIsEqualValue - Return true if this phi node is always equal to
10887 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10888 ///   z = some value; x = phi (y, z); y = phi (x, z)
10889 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10890                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10891   // See if we already saw this PHI node.
10892   if (!ValueEqualPHIs.insert(PN))
10893     return true;
10894   
10895   // Don't scan crazily complex things.
10896   if (ValueEqualPHIs.size() == 16)
10897     return false;
10898  
10899   // Scan the operands to see if they are either phi nodes or are equal to
10900   // the value.
10901   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10902     Value *Op = PN->getIncomingValue(i);
10903     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10904       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10905         return false;
10906     } else if (Op != NonPhiInVal)
10907       return false;
10908   }
10909   
10910   return true;
10911 }
10912
10913
10914 // PHINode simplification
10915 //
10916 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10917   // If LCSSA is around, don't mess with Phi nodes
10918   if (MustPreserveLCSSA) return 0;
10919   
10920   if (Value *V = PN.hasConstantValue())
10921     return ReplaceInstUsesWith(PN, V);
10922
10923   // If all PHI operands are the same operation, pull them through the PHI,
10924   // reducing code size.
10925   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10926       isa<Instruction>(PN.getIncomingValue(1)) &&
10927       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10928       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10929       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10930       // than themselves more than once.
10931       PN.getIncomingValue(0)->hasOneUse())
10932     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10933       return Result;
10934
10935   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10936   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10937   // PHI)... break the cycle.
10938   if (PN.hasOneUse()) {
10939     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10940     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10941       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10942       PotentiallyDeadPHIs.insert(&PN);
10943       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10944         return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10945     }
10946    
10947     // If this phi has a single use, and if that use just computes a value for
10948     // the next iteration of a loop, delete the phi.  This occurs with unused
10949     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10950     // common case here is good because the only other things that catch this
10951     // are induction variable analysis (sometimes) and ADCE, which is only run
10952     // late.
10953     if (PHIUser->hasOneUse() &&
10954         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10955         PHIUser->use_back() == &PN) {
10956       return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10957     }
10958   }
10959
10960   // We sometimes end up with phi cycles that non-obviously end up being the
10961   // same value, for example:
10962   //   z = some value; x = phi (y, z); y = phi (x, z)
10963   // where the phi nodes don't necessarily need to be in the same block.  Do a
10964   // quick check to see if the PHI node only contains a single non-phi value, if
10965   // so, scan to see if the phi cycle is actually equal to that value.
10966   {
10967     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10968     // Scan for the first non-phi operand.
10969     while (InValNo != NumOperandVals && 
10970            isa<PHINode>(PN.getIncomingValue(InValNo)))
10971       ++InValNo;
10972
10973     if (InValNo != NumOperandVals) {
10974       Value *NonPhiInVal = PN.getOperand(InValNo);
10975       
10976       // Scan the rest of the operands to see if there are any conflicts, if so
10977       // there is no need to recursively scan other phis.
10978       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10979         Value *OpVal = PN.getIncomingValue(InValNo);
10980         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10981           break;
10982       }
10983       
10984       // If we scanned over all operands, then we have one unique value plus
10985       // phi values.  Scan PHI nodes to see if they all merge in each other or
10986       // the value.
10987       if (InValNo == NumOperandVals) {
10988         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10989         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10990           return ReplaceInstUsesWith(PN, NonPhiInVal);
10991       }
10992     }
10993   }
10994   return 0;
10995 }
10996
10997 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10998                                    Instruction *InsertPoint,
10999                                    InstCombiner *IC) {
11000   unsigned PtrSize = DTy->getScalarSizeInBits();
11001   unsigned VTySize = V->getType()->getScalarSizeInBits();
11002   // We must cast correctly to the pointer type. Ensure that we
11003   // sign extend the integer value if it is smaller as this is
11004   // used for address computation.
11005   Instruction::CastOps opcode = 
11006      (VTySize < PtrSize ? Instruction::SExt :
11007       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
11008   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
11009 }
11010
11011
11012 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
11013   Value *PtrOp = GEP.getOperand(0);
11014   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
11015   // If so, eliminate the noop.
11016   if (GEP.getNumOperands() == 1)
11017     return ReplaceInstUsesWith(GEP, PtrOp);
11018
11019   if (isa<UndefValue>(GEP.getOperand(0)))
11020     return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
11021
11022   bool HasZeroPointerIndex = false;
11023   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11024     HasZeroPointerIndex = C->isNullValue();
11025
11026   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11027     return ReplaceInstUsesWith(GEP, PtrOp);
11028
11029   // Eliminate unneeded casts for indices.
11030   bool MadeChange = false;
11031   
11032   gep_type_iterator GTI = gep_type_begin(GEP);
11033   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11034        i != e; ++i, ++GTI) {
11035     if (isa<SequentialType>(*GTI)) {
11036       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
11037         if (CI->getOpcode() == Instruction::ZExt ||
11038             CI->getOpcode() == Instruction::SExt) {
11039           const Type *SrcTy = CI->getOperand(0)->getType();
11040           // We can eliminate a cast from i32 to i64 iff the target 
11041           // is a 32-bit pointer target.
11042           if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
11043             MadeChange = true;
11044             *i = CI->getOperand(0);
11045           }
11046         }
11047       }
11048       // If we are using a wider index than needed for this platform, shrink it
11049       // to what we need.  If narrower, sign-extend it to what we need.
11050       // If the incoming value needs a cast instruction,
11051       // insert it.  This explicit cast can make subsequent optimizations more
11052       // obvious.
11053       Value *Op = *i;
11054       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
11055         if (Constant *C = dyn_cast<Constant>(Op)) {
11056           *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
11057           MadeChange = true;
11058         } else {
11059           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11060                                 GEP);
11061           *i = Op;
11062           MadeChange = true;
11063         }
11064       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
11065         if (Constant *C = dyn_cast<Constant>(Op)) {
11066           *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
11067           MadeChange = true;
11068         } else {
11069           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11070                                 GEP);
11071           *i = Op;
11072           MadeChange = true;
11073         }
11074       }
11075     }
11076   }
11077   if (MadeChange) return &GEP;
11078
11079   // Combine Indices - If the source pointer to this getelementptr instruction
11080   // is a getelementptr instruction, combine the indices of the two
11081   // getelementptr instructions into a single instruction.
11082   //
11083   SmallVector<Value*, 8> SrcGEPOperands;
11084   if (User *Src = dyn_castGetElementPtr(PtrOp))
11085     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
11086
11087   if (!SrcGEPOperands.empty()) {
11088     // Note that if our source is a gep chain itself that we wait for that
11089     // chain to be resolved before we perform this transformation.  This
11090     // avoids us creating a TON of code in some cases.
11091     //
11092     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11093         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11094       return 0;   // Wait until our source is folded to completion.
11095
11096     SmallVector<Value*, 8> Indices;
11097
11098     // Find out whether the last index in the source GEP is a sequential idx.
11099     bool EndsWithSequential = false;
11100     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11101            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11102       EndsWithSequential = !isa<StructType>(*I);
11103
11104     // Can we combine the two pointer arithmetics offsets?
11105     if (EndsWithSequential) {
11106       // Replace: gep (gep %P, long B), long A, ...
11107       // With:    T = long A+B; gep %P, T, ...
11108       //
11109       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
11110       if (SO1 == Context->getNullValue(SO1->getType())) {
11111         Sum = GO1;
11112       } else if (GO1 == Context->getNullValue(GO1->getType())) {
11113         Sum = SO1;
11114       } else {
11115         // If they aren't the same type, convert both to an integer of the
11116         // target's pointer size.
11117         if (SO1->getType() != GO1->getType()) {
11118           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
11119             SO1 =
11120                 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
11121           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
11122             GO1 =
11123                 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
11124           } else {
11125             unsigned PS = TD->getPointerSizeInBits();
11126             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
11127               // Convert GO1 to SO1's type.
11128               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11129
11130             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
11131               // Convert SO1 to GO1's type.
11132               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11133             } else {
11134               const Type *PT = TD->getIntPtrType();
11135               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11136               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11137             }
11138           }
11139         }
11140         if (isa<Constant>(SO1) && isa<Constant>(GO1))
11141           Sum = Context->getConstantExprAdd(cast<Constant>(SO1), 
11142                                             cast<Constant>(GO1));
11143         else {
11144           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11145           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11146         }
11147       }
11148
11149       // Recycle the GEP we already have if possible.
11150       if (SrcGEPOperands.size() == 2) {
11151         GEP.setOperand(0, SrcGEPOperands[0]);
11152         GEP.setOperand(1, Sum);
11153         return &GEP;
11154       } else {
11155         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11156                        SrcGEPOperands.end()-1);
11157         Indices.push_back(Sum);
11158         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11159       }
11160     } else if (isa<Constant>(*GEP.idx_begin()) &&
11161                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11162                SrcGEPOperands.size() != 1) {
11163       // Otherwise we can do the fold if the first index of the GEP is a zero
11164       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11165                      SrcGEPOperands.end());
11166       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11167     }
11168
11169     if (!Indices.empty())
11170       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11171                                        Indices.end(), GEP.getName());
11172
11173   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11174     // GEP of global variable.  If all of the indices for this GEP are
11175     // constants, we can promote this to a constexpr instead of an instruction.
11176
11177     // Scan for nonconstants...
11178     SmallVector<Constant*, 8> Indices;
11179     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11180     for (; I != E && isa<Constant>(*I); ++I)
11181       Indices.push_back(cast<Constant>(*I));
11182
11183     if (I == E) {  // If they are all constants...
11184       Constant *CE = Context->getConstantExprGetElementPtr(GV,
11185                                                     &Indices[0],Indices.size());
11186
11187       // Replace all uses of the GEP with the new constexpr...
11188       return ReplaceInstUsesWith(GEP, CE);
11189     }
11190   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
11191     if (!isa<PointerType>(X->getType())) {
11192       // Not interesting.  Source pointer must be a cast from pointer.
11193     } else if (HasZeroPointerIndex) {
11194       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11195       // into     : GEP [10 x i8]* X, i32 0, ...
11196       //
11197       // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11198       //           into     : GEP i8* X, ...
11199       // 
11200       // This occurs when the program declares an array extern like "int X[];"
11201       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11202       const PointerType *XTy = cast<PointerType>(X->getType());
11203       if (const ArrayType *CATy =
11204           dyn_cast<ArrayType>(CPTy->getElementType())) {
11205         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11206         if (CATy->getElementType() == XTy->getElementType()) {
11207           // -> GEP i8* X, ...
11208           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11209           return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11210                                            GEP.getName());
11211         } else if (const ArrayType *XATy =
11212                  dyn_cast<ArrayType>(XTy->getElementType())) {
11213           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11214           if (CATy->getElementType() == XATy->getElementType()) {
11215             // -> GEP [10 x i8]* X, i32 0, ...
11216             // At this point, we know that the cast source type is a pointer
11217             // to an array of the same type as the destination pointer
11218             // array.  Because the array type is never stepped over (there
11219             // is a leading zero) we can fold the cast into this GEP.
11220             GEP.setOperand(0, X);
11221             return &GEP;
11222           }
11223         }
11224       }
11225     } else if (GEP.getNumOperands() == 2) {
11226       // Transform things like:
11227       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11228       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11229       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11230       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11231       if (isa<ArrayType>(SrcElTy) &&
11232           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11233           TD->getTypeAllocSize(ResElTy)) {
11234         Value *Idx[2];
11235         Idx[0] = Context->getNullValue(Type::Int32Ty);
11236         Idx[1] = GEP.getOperand(1);
11237         Value *V = InsertNewInstBefore(
11238                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
11239         // V and GEP are both pointer types --> BitCast
11240         return new BitCastInst(V, GEP.getType());
11241       }
11242       
11243       // Transform things like:
11244       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11245       //   (where tmp = 8*tmp2) into:
11246       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11247       
11248       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
11249         uint64_t ArrayEltSize =
11250             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11251         
11252         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11253         // allow either a mul, shift, or constant here.
11254         Value *NewIdx = 0;
11255         ConstantInt *Scale = 0;
11256         if (ArrayEltSize == 1) {
11257           NewIdx = GEP.getOperand(1);
11258           Scale = 
11259                Context->getConstantInt(cast<IntegerType>(NewIdx->getType()), 1);
11260         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11261           NewIdx = Context->getConstantInt(CI->getType(), 1);
11262           Scale = CI;
11263         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11264           if (Inst->getOpcode() == Instruction::Shl &&
11265               isa<ConstantInt>(Inst->getOperand(1))) {
11266             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11267             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11268             Scale = Context->getConstantInt(cast<IntegerType>(Inst->getType()),
11269                                      1ULL << ShAmtVal);
11270             NewIdx = Inst->getOperand(0);
11271           } else if (Inst->getOpcode() == Instruction::Mul &&
11272                      isa<ConstantInt>(Inst->getOperand(1))) {
11273             Scale = cast<ConstantInt>(Inst->getOperand(1));
11274             NewIdx = Inst->getOperand(0);
11275           }
11276         }
11277         
11278         // If the index will be to exactly the right offset with the scale taken
11279         // out, perform the transformation. Note, we don't know whether Scale is
11280         // signed or not. We'll use unsigned version of division/modulo
11281         // operation after making sure Scale doesn't have the sign bit set.
11282         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11283             Scale->getZExtValue() % ArrayEltSize == 0) {
11284           Scale = Context->getConstantInt(Scale->getType(),
11285                                    Scale->getZExtValue() / ArrayEltSize);
11286           if (Scale->getZExtValue() != 1) {
11287             Constant *C =
11288                    Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
11289                                                        false /*ZExt*/);
11290             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11291             NewIdx = InsertNewInstBefore(Sc, GEP);
11292           }
11293
11294           // Insert the new GEP instruction.
11295           Value *Idx[2];
11296           Idx[0] = Context->getNullValue(Type::Int32Ty);
11297           Idx[1] = NewIdx;
11298           Instruction *NewGEP =
11299             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11300           NewGEP = InsertNewInstBefore(NewGEP, GEP);
11301           // The NewGEP must be pointer typed, so must the old one -> BitCast
11302           return new BitCastInst(NewGEP, GEP.getType());
11303         }
11304       }
11305     }
11306   }
11307   
11308   /// See if we can simplify:
11309   ///   X = bitcast A to B*
11310   ///   Y = gep X, <...constant indices...>
11311   /// into a gep of the original struct.  This is important for SROA and alias
11312   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11313   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11314     if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11315       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11316       // a constant back from EmitGEPOffset.
11317       ConstantInt *OffsetV =
11318                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11319       int64_t Offset = OffsetV->getSExtValue();
11320       
11321       // If this GEP instruction doesn't move the pointer, just replace the GEP
11322       // with a bitcast of the real input to the dest type.
11323       if (Offset == 0) {
11324         // If the bitcast is of an allocation, and the allocation will be
11325         // converted to match the type of the cast, don't touch this.
11326         if (isa<AllocationInst>(BCI->getOperand(0))) {
11327           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11328           if (Instruction *I = visitBitCast(*BCI)) {
11329             if (I != BCI) {
11330               I->takeName(BCI);
11331               BCI->getParent()->getInstList().insert(BCI, I);
11332               ReplaceInstUsesWith(*BCI, I);
11333             }
11334             return &GEP;
11335           }
11336         }
11337         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11338       }
11339       
11340       // Otherwise, if the offset is non-zero, we need to find out if there is a
11341       // field at Offset in 'A's type.  If so, we can pull the cast through the
11342       // GEP.
11343       SmallVector<Value*, 8> NewIndices;
11344       const Type *InTy =
11345         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11346       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11347         Instruction *NGEP =
11348            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11349                                      NewIndices.end());
11350         if (NGEP->getType() == GEP.getType()) return NGEP;
11351         InsertNewInstBefore(NGEP, GEP);
11352         NGEP->takeName(&GEP);
11353         return new BitCastInst(NGEP, GEP.getType());
11354       }
11355     }
11356   }    
11357     
11358   return 0;
11359 }
11360
11361 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11362   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11363   if (AI.isArrayAllocation()) {  // Check C != 1
11364     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11365       const Type *NewTy = 
11366         Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
11367       AllocationInst *New = 0;
11368
11369       // Create and insert the replacement instruction...
11370       if (isa<MallocInst>(AI))
11371         New = new MallocInst(*Context, NewTy, 0,
11372                              AI.getAlignment(), AI.getName());
11373       else {
11374         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11375         New = new AllocaInst(*Context, NewTy, 0,
11376                              AI.getAlignment(), AI.getName());
11377       }
11378
11379       InsertNewInstBefore(New, AI);
11380
11381       // Scan to the end of the allocation instructions, to skip over a block of
11382       // allocas if possible...also skip interleaved debug info
11383       //
11384       BasicBlock::iterator It = New;
11385       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11386
11387       // Now that I is pointing to the first non-allocation-inst in the block,
11388       // insert our getelementptr instruction...
11389       //
11390       Value *NullIdx = Context->getNullValue(Type::Int32Ty);
11391       Value *Idx[2];
11392       Idx[0] = NullIdx;
11393       Idx[1] = NullIdx;
11394       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11395                                            New->getName()+".sub", It);
11396
11397       // Now make everything use the getelementptr instead of the original
11398       // allocation.
11399       return ReplaceInstUsesWith(AI, V);
11400     } else if (isa<UndefValue>(AI.getArraySize())) {
11401       return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11402     }
11403   }
11404
11405   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11406     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11407     // Note that we only do this for alloca's, because malloc should allocate
11408     // and return a unique pointer, even for a zero byte allocation.
11409     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11410       return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11411
11412     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11413     if (AI.getAlignment() == 0)
11414       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11415   }
11416
11417   return 0;
11418 }
11419
11420 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11421   Value *Op = FI.getOperand(0);
11422
11423   // free undef -> unreachable.
11424   if (isa<UndefValue>(Op)) {
11425     // Insert a new store to null because we cannot modify the CFG here.
11426     new StoreInst(Context->getConstantIntTrue(),
11427            Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
11428     return EraseInstFromFunction(FI);
11429   }
11430   
11431   // If we have 'free null' delete the instruction.  This can happen in stl code
11432   // when lots of inlining happens.
11433   if (isa<ConstantPointerNull>(Op))
11434     return EraseInstFromFunction(FI);
11435   
11436   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11437   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11438     FI.setOperand(0, CI->getOperand(0));
11439     return &FI;
11440   }
11441   
11442   // Change free (gep X, 0,0,0,0) into free(X)
11443   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11444     if (GEPI->hasAllZeroIndices()) {
11445       AddToWorkList(GEPI);
11446       FI.setOperand(0, GEPI->getOperand(0));
11447       return &FI;
11448     }
11449   }
11450   
11451   // Change free(malloc) into nothing, if the malloc has a single use.
11452   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11453     if (MI->hasOneUse()) {
11454       EraseInstFromFunction(FI);
11455       return EraseInstFromFunction(*MI);
11456     }
11457
11458   return 0;
11459 }
11460
11461
11462 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11463 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11464                                         const TargetData *TD) {
11465   User *CI = cast<User>(LI.getOperand(0));
11466   Value *CastOp = CI->getOperand(0);
11467   LLVMContext *Context = IC.getContext();
11468
11469   if (TD) {
11470     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11471       // Instead of loading constant c string, use corresponding integer value
11472       // directly if string length is small enough.
11473       std::string Str;
11474       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11475         unsigned len = Str.length();
11476         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11477         unsigned numBits = Ty->getPrimitiveSizeInBits();
11478         // Replace LI with immediate integer store.
11479         if ((numBits >> 3) == len + 1) {
11480           APInt StrVal(numBits, 0);
11481           APInt SingleChar(numBits, 0);
11482           if (TD->isLittleEndian()) {
11483             for (signed i = len-1; i >= 0; i--) {
11484               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11485               StrVal = (StrVal << 8) | SingleChar;
11486             }
11487           } else {
11488             for (unsigned i = 0; i < len; i++) {
11489               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11490               StrVal = (StrVal << 8) | SingleChar;
11491             }
11492             // Append NULL at the end.
11493             SingleChar = 0;
11494             StrVal = (StrVal << 8) | SingleChar;
11495           }
11496           Value *NL = Context->getConstantInt(StrVal);
11497           return IC.ReplaceInstUsesWith(LI, NL);
11498         }
11499       }
11500     }
11501   }
11502
11503   const PointerType *DestTy = cast<PointerType>(CI->getType());
11504   const Type *DestPTy = DestTy->getElementType();
11505   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11506
11507     // If the address spaces don't match, don't eliminate the cast.
11508     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11509       return 0;
11510
11511     const Type *SrcPTy = SrcTy->getElementType();
11512
11513     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11514          isa<VectorType>(DestPTy)) {
11515       // If the source is an array, the code below will not succeed.  Check to
11516       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11517       // constants.
11518       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11519         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11520           if (ASrcTy->getNumElements() != 0) {
11521             Value *Idxs[2];
11522             Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11523             CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
11524             SrcTy = cast<PointerType>(CastOp->getType());
11525             SrcPTy = SrcTy->getElementType();
11526           }
11527
11528       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11529             isa<VectorType>(SrcPTy)) &&
11530           // Do not allow turning this into a load of an integer, which is then
11531           // casted to a pointer, this pessimizes pointer analysis a lot.
11532           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11533           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11534                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11535
11536         // Okay, we are casting from one integer or pointer type to another of
11537         // the same size.  Instead of casting the pointer before the load, cast
11538         // the result of the loaded value.
11539         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11540                                                              CI->getName(),
11541                                                          LI.isVolatile()),LI);
11542         // Now cast the result of the load.
11543         return new BitCastInst(NewLoad, LI.getType());
11544       }
11545     }
11546   }
11547   return 0;
11548 }
11549
11550 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11551   Value *Op = LI.getOperand(0);
11552
11553   // Attempt to improve the alignment.
11554   unsigned KnownAlign =
11555     GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11556   if (KnownAlign >
11557       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11558                                 LI.getAlignment()))
11559     LI.setAlignment(KnownAlign);
11560
11561   // load (cast X) --> cast (load X) iff safe
11562   if (isa<CastInst>(Op))
11563     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11564       return Res;
11565
11566   // None of the following transforms are legal for volatile loads.
11567   if (LI.isVolatile()) return 0;
11568   
11569   // Do really simple store-to-load forwarding and load CSE, to catch cases
11570   // where there are several consequtive memory accesses to the same location,
11571   // separated by a few arithmetic operations.
11572   BasicBlock::iterator BBI = &LI;
11573   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11574     return ReplaceInstUsesWith(LI, AvailableVal);
11575
11576   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11577     const Value *GEPI0 = GEPI->getOperand(0);
11578     // TODO: Consider a target hook for valid address spaces for this xform.
11579     if (isa<ConstantPointerNull>(GEPI0) &&
11580         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11581       // Insert a new store to null instruction before the load to indicate
11582       // that this code is not reachable.  We do this instead of inserting
11583       // an unreachable instruction directly because we cannot modify the
11584       // CFG.
11585       new StoreInst(Context->getUndef(LI.getType()),
11586                     Context->getNullValue(Op->getType()), &LI);
11587       return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11588     }
11589   } 
11590
11591   if (Constant *C = dyn_cast<Constant>(Op)) {
11592     // load null/undef -> undef
11593     // TODO: Consider a target hook for valid address spaces for this xform.
11594     if (isa<UndefValue>(C) || (C->isNullValue() && 
11595         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11596       // Insert a new store to null instruction before the load to indicate that
11597       // this code is not reachable.  We do this instead of inserting an
11598       // unreachable instruction directly because we cannot modify the CFG.
11599       new StoreInst(Context->getUndef(LI.getType()),
11600                     Context->getNullValue(Op->getType()), &LI);
11601       return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11602     }
11603
11604     // Instcombine load (constant global) into the value loaded.
11605     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11606       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11607         return ReplaceInstUsesWith(LI, GV->getInitializer());
11608
11609     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11610     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11611       if (CE->getOpcode() == Instruction::GetElementPtr) {
11612         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11613           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11614             if (Constant *V = 
11615                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE, 
11616                                                       Context))
11617               return ReplaceInstUsesWith(LI, V);
11618         if (CE->getOperand(0)->isNullValue()) {
11619           // Insert a new store to null instruction before the load to indicate
11620           // that this code is not reachable.  We do this instead of inserting
11621           // an unreachable instruction directly because we cannot modify the
11622           // CFG.
11623           new StoreInst(Context->getUndef(LI.getType()),
11624                         Context->getNullValue(Op->getType()), &LI);
11625           return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11626         }
11627
11628       } else if (CE->isCast()) {
11629         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11630           return Res;
11631       }
11632     }
11633   }
11634     
11635   // If this load comes from anywhere in a constant global, and if the global
11636   // is all undef or zero, we know what it loads.
11637   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11638     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11639       if (GV->getInitializer()->isNullValue())
11640         return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
11641       else if (isa<UndefValue>(GV->getInitializer()))
11642         return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11643     }
11644   }
11645
11646   if (Op->hasOneUse()) {
11647     // Change select and PHI nodes to select values instead of addresses: this
11648     // helps alias analysis out a lot, allows many others simplifications, and
11649     // exposes redundancy in the code.
11650     //
11651     // Note that we cannot do the transformation unless we know that the
11652     // introduced loads cannot trap!  Something like this is valid as long as
11653     // the condition is always false: load (select bool %C, int* null, int* %G),
11654     // but it would not be valid if we transformed it to load from null
11655     // unconditionally.
11656     //
11657     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11658       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11659       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11660           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11661         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11662                                      SI->getOperand(1)->getName()+".val"), LI);
11663         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11664                                      SI->getOperand(2)->getName()+".val"), LI);
11665         return SelectInst::Create(SI->getCondition(), V1, V2);
11666       }
11667
11668       // load (select (cond, null, P)) -> load P
11669       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11670         if (C->isNullValue()) {
11671           LI.setOperand(0, SI->getOperand(2));
11672           return &LI;
11673         }
11674
11675       // load (select (cond, P, null)) -> load P
11676       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11677         if (C->isNullValue()) {
11678           LI.setOperand(0, SI->getOperand(1));
11679           return &LI;
11680         }
11681     }
11682   }
11683   return 0;
11684 }
11685
11686 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11687 /// when possible.  This makes it generally easy to do alias analysis and/or
11688 /// SROA/mem2reg of the memory object.
11689 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11690   User *CI = cast<User>(SI.getOperand(1));
11691   Value *CastOp = CI->getOperand(0);
11692   LLVMContext *Context = IC.getContext();
11693
11694   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11695   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11696   if (SrcTy == 0) return 0;
11697   
11698   const Type *SrcPTy = SrcTy->getElementType();
11699
11700   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11701     return 0;
11702   
11703   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11704   /// to its first element.  This allows us to handle things like:
11705   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11706   /// on 32-bit hosts.
11707   SmallVector<Value*, 4> NewGEPIndices;
11708   
11709   // If the source is an array, the code below will not succeed.  Check to
11710   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11711   // constants.
11712   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11713     // Index through pointer.
11714     Constant *Zero = Context->getNullValue(Type::Int32Ty);
11715     NewGEPIndices.push_back(Zero);
11716     
11717     while (1) {
11718       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11719         if (!STy->getNumElements()) /* Struct can be empty {} */
11720           break;
11721         NewGEPIndices.push_back(Zero);
11722         SrcPTy = STy->getElementType(0);
11723       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11724         NewGEPIndices.push_back(Zero);
11725         SrcPTy = ATy->getElementType();
11726       } else {
11727         break;
11728       }
11729     }
11730     
11731     SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
11732   }
11733
11734   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11735     return 0;
11736   
11737   // If the pointers point into different address spaces or if they point to
11738   // values with different sizes, we can't do the transformation.
11739   if (SrcTy->getAddressSpace() != 
11740         cast<PointerType>(CI->getType())->getAddressSpace() ||
11741       IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
11742       IC.getTargetData().getTypeSizeInBits(DestPTy))
11743     return 0;
11744
11745   // Okay, we are casting from one integer or pointer type to another of
11746   // the same size.  Instead of casting the pointer before 
11747   // the store, cast the value to be stored.
11748   Value *NewCast;
11749   Value *SIOp0 = SI.getOperand(0);
11750   Instruction::CastOps opcode = Instruction::BitCast;
11751   const Type* CastSrcTy = SIOp0->getType();
11752   const Type* CastDstTy = SrcPTy;
11753   if (isa<PointerType>(CastDstTy)) {
11754     if (CastSrcTy->isInteger())
11755       opcode = Instruction::IntToPtr;
11756   } else if (isa<IntegerType>(CastDstTy)) {
11757     if (isa<PointerType>(SIOp0->getType()))
11758       opcode = Instruction::PtrToInt;
11759   }
11760   
11761   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11762   // emit a GEP to index into its first field.
11763   if (!NewGEPIndices.empty()) {
11764     if (Constant *C = dyn_cast<Constant>(CastOp))
11765       CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0], 
11766                                               NewGEPIndices.size());
11767     else
11768       CastOp = IC.InsertNewInstBefore(
11769               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11770                                         NewGEPIndices.end()), SI);
11771   }
11772   
11773   if (Constant *C = dyn_cast<Constant>(SIOp0))
11774     NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
11775   else
11776     NewCast = IC.InsertNewInstBefore(
11777       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11778       SI);
11779   return new StoreInst(NewCast, CastOp);
11780 }
11781
11782 /// equivalentAddressValues - Test if A and B will obviously have the same
11783 /// value. This includes recognizing that %t0 and %t1 will have the same
11784 /// value in code like this:
11785 ///   %t0 = getelementptr \@a, 0, 3
11786 ///   store i32 0, i32* %t0
11787 ///   %t1 = getelementptr \@a, 0, 3
11788 ///   %t2 = load i32* %t1
11789 ///
11790 static bool equivalentAddressValues(Value *A, Value *B) {
11791   // Test if the values are trivially equivalent.
11792   if (A == B) return true;
11793   
11794   // Test if the values come form identical arithmetic instructions.
11795   if (isa<BinaryOperator>(A) ||
11796       isa<CastInst>(A) ||
11797       isa<PHINode>(A) ||
11798       isa<GetElementPtrInst>(A))
11799     if (Instruction *BI = dyn_cast<Instruction>(B))
11800       if (cast<Instruction>(A)->isIdenticalTo(BI))
11801         return true;
11802   
11803   // Otherwise they may not be equivalent.
11804   return false;
11805 }
11806
11807 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11808 // return the llvm.dbg.declare.
11809 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11810   if (!V->hasNUses(2))
11811     return 0;
11812   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11813        UI != E; ++UI) {
11814     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11815       return DI;
11816     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11817       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11818         return DI;
11819       }
11820   }
11821   return 0;
11822 }
11823
11824 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11825   Value *Val = SI.getOperand(0);
11826   Value *Ptr = SI.getOperand(1);
11827
11828   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11829     EraseInstFromFunction(SI);
11830     ++NumCombined;
11831     return 0;
11832   }
11833   
11834   // If the RHS is an alloca with a single use, zapify the store, making the
11835   // alloca dead.
11836   // If the RHS is an alloca with a two uses, the other one being a 
11837   // llvm.dbg.declare, zapify the store and the declare, making the
11838   // alloca dead.  We must do this to prevent declare's from affecting
11839   // codegen.
11840   if (!SI.isVolatile()) {
11841     if (Ptr->hasOneUse()) {
11842       if (isa<AllocaInst>(Ptr)) {
11843         EraseInstFromFunction(SI);
11844         ++NumCombined;
11845         return 0;
11846       }
11847       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11848         if (isa<AllocaInst>(GEP->getOperand(0))) {
11849           if (GEP->getOperand(0)->hasOneUse()) {
11850             EraseInstFromFunction(SI);
11851             ++NumCombined;
11852             return 0;
11853           }
11854           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11855             EraseInstFromFunction(*DI);
11856             EraseInstFromFunction(SI);
11857             ++NumCombined;
11858             return 0;
11859           }
11860         }
11861       }
11862     }
11863     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11864       EraseInstFromFunction(*DI);
11865       EraseInstFromFunction(SI);
11866       ++NumCombined;
11867       return 0;
11868     }
11869   }
11870
11871   // Attempt to improve the alignment.
11872   unsigned KnownAlign =
11873     GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11874   if (KnownAlign >
11875       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11876                                 SI.getAlignment()))
11877     SI.setAlignment(KnownAlign);
11878
11879   // Do really simple DSE, to catch cases where there are several consecutive
11880   // stores to the same location, separated by a few arithmetic operations. This
11881   // situation often occurs with bitfield accesses.
11882   BasicBlock::iterator BBI = &SI;
11883   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11884        --ScanInsts) {
11885     --BBI;
11886     // Don't count debug info directives, lest they affect codegen,
11887     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11888     // It is necessary for correctness to skip those that feed into a
11889     // llvm.dbg.declare, as these are not present when debugging is off.
11890     if (isa<DbgInfoIntrinsic>(BBI) ||
11891         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11892       ScanInsts++;
11893       continue;
11894     }    
11895     
11896     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11897       // Prev store isn't volatile, and stores to the same location?
11898       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11899                                                           SI.getOperand(1))) {
11900         ++NumDeadStore;
11901         ++BBI;
11902         EraseInstFromFunction(*PrevSI);
11903         continue;
11904       }
11905       break;
11906     }
11907     
11908     // If this is a load, we have to stop.  However, if the loaded value is from
11909     // the pointer we're loading and is producing the pointer we're storing,
11910     // then *this* store is dead (X = load P; store X -> P).
11911     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11912       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11913           !SI.isVolatile()) {
11914         EraseInstFromFunction(SI);
11915         ++NumCombined;
11916         return 0;
11917       }
11918       // Otherwise, this is a load from some other location.  Stores before it
11919       // may not be dead.
11920       break;
11921     }
11922     
11923     // Don't skip over loads or things that can modify memory.
11924     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11925       break;
11926   }
11927   
11928   
11929   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11930
11931   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11932   if (isa<ConstantPointerNull>(Ptr) &&
11933       cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11934     if (!isa<UndefValue>(Val)) {
11935       SI.setOperand(0, Context->getUndef(Val->getType()));
11936       if (Instruction *U = dyn_cast<Instruction>(Val))
11937         AddToWorkList(U);  // Dropped a use.
11938       ++NumCombined;
11939     }
11940     return 0;  // Do not modify these!
11941   }
11942
11943   // store undef, Ptr -> noop
11944   if (isa<UndefValue>(Val)) {
11945     EraseInstFromFunction(SI);
11946     ++NumCombined;
11947     return 0;
11948   }
11949
11950   // If the pointer destination is a cast, see if we can fold the cast into the
11951   // source instead.
11952   if (isa<CastInst>(Ptr))
11953     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11954       return Res;
11955   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11956     if (CE->isCast())
11957       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11958         return Res;
11959
11960   
11961   // If this store is the last instruction in the basic block (possibly
11962   // excepting debug info instructions and the pointer bitcasts that feed
11963   // into them), and if the block ends with an unconditional branch, try
11964   // to move it to the successor block.
11965   BBI = &SI; 
11966   do {
11967     ++BBI;
11968   } while (isa<DbgInfoIntrinsic>(BBI) ||
11969            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11970   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11971     if (BI->isUnconditional())
11972       if (SimplifyStoreAtEndOfBlock(SI))
11973         return 0;  // xform done!
11974   
11975   return 0;
11976 }
11977
11978 /// SimplifyStoreAtEndOfBlock - Turn things like:
11979 ///   if () { *P = v1; } else { *P = v2 }
11980 /// into a phi node with a store in the successor.
11981 ///
11982 /// Simplify things like:
11983 ///   *P = v1; if () { *P = v2; }
11984 /// into a phi node with a store in the successor.
11985 ///
11986 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11987   BasicBlock *StoreBB = SI.getParent();
11988   
11989   // Check to see if the successor block has exactly two incoming edges.  If
11990   // so, see if the other predecessor contains a store to the same location.
11991   // if so, insert a PHI node (if needed) and move the stores down.
11992   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11993   
11994   // Determine whether Dest has exactly two predecessors and, if so, compute
11995   // the other predecessor.
11996   pred_iterator PI = pred_begin(DestBB);
11997   BasicBlock *OtherBB = 0;
11998   if (*PI != StoreBB)
11999     OtherBB = *PI;
12000   ++PI;
12001   if (PI == pred_end(DestBB))
12002     return false;
12003   
12004   if (*PI != StoreBB) {
12005     if (OtherBB)
12006       return false;
12007     OtherBB = *PI;
12008   }
12009   if (++PI != pred_end(DestBB))
12010     return false;
12011
12012   // Bail out if all the relevant blocks aren't distinct (this can happen,
12013   // for example, if SI is in an infinite loop)
12014   if (StoreBB == DestBB || OtherBB == DestBB)
12015     return false;
12016
12017   // Verify that the other block ends in a branch and is not otherwise empty.
12018   BasicBlock::iterator BBI = OtherBB->getTerminator();
12019   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12020   if (!OtherBr || BBI == OtherBB->begin())
12021     return false;
12022   
12023   // If the other block ends in an unconditional branch, check for the 'if then
12024   // else' case.  there is an instruction before the branch.
12025   StoreInst *OtherStore = 0;
12026   if (OtherBr->isUnconditional()) {
12027     --BBI;
12028     // Skip over debugging info.
12029     while (isa<DbgInfoIntrinsic>(BBI) ||
12030            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12031       if (BBI==OtherBB->begin())
12032         return false;
12033       --BBI;
12034     }
12035     // If this isn't a store, or isn't a store to the same location, bail out.
12036     OtherStore = dyn_cast<StoreInst>(BBI);
12037     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12038       return false;
12039   } else {
12040     // Otherwise, the other block ended with a conditional branch. If one of the
12041     // destinations is StoreBB, then we have the if/then case.
12042     if (OtherBr->getSuccessor(0) != StoreBB && 
12043         OtherBr->getSuccessor(1) != StoreBB)
12044       return false;
12045     
12046     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12047     // if/then triangle.  See if there is a store to the same ptr as SI that
12048     // lives in OtherBB.
12049     for (;; --BBI) {
12050       // Check to see if we find the matching store.
12051       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12052         if (OtherStore->getOperand(1) != SI.getOperand(1))
12053           return false;
12054         break;
12055       }
12056       // If we find something that may be using or overwriting the stored
12057       // value, or if we run out of instructions, we can't do the xform.
12058       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12059           BBI == OtherBB->begin())
12060         return false;
12061     }
12062     
12063     // In order to eliminate the store in OtherBr, we have to
12064     // make sure nothing reads or overwrites the stored value in
12065     // StoreBB.
12066     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12067       // FIXME: This should really be AA driven.
12068       if (I->mayReadFromMemory() || I->mayWriteToMemory())
12069         return false;
12070     }
12071   }
12072   
12073   // Insert a PHI node now if we need it.
12074   Value *MergedVal = OtherStore->getOperand(0);
12075   if (MergedVal != SI.getOperand(0)) {
12076     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12077     PN->reserveOperandSpace(2);
12078     PN->addIncoming(SI.getOperand(0), SI.getParent());
12079     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12080     MergedVal = InsertNewInstBefore(PN, DestBB->front());
12081   }
12082   
12083   // Advance to a place where it is safe to insert the new store and
12084   // insert it.
12085   BBI = DestBB->getFirstNonPHI();
12086   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12087                                     OtherStore->isVolatile()), *BBI);
12088   
12089   // Nuke the old stores.
12090   EraseInstFromFunction(SI);
12091   EraseInstFromFunction(*OtherStore);
12092   ++NumCombined;
12093   return true;
12094 }
12095
12096
12097 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12098   // Change br (not X), label True, label False to: br X, label False, True
12099   Value *X = 0;
12100   BasicBlock *TrueDest;
12101   BasicBlock *FalseDest;
12102   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
12103       !isa<Constant>(X)) {
12104     // Swap Destinations and condition...
12105     BI.setCondition(X);
12106     BI.setSuccessor(0, FalseDest);
12107     BI.setSuccessor(1, TrueDest);
12108     return &BI;
12109   }
12110
12111   // Cannonicalize fcmp_one -> fcmp_oeq
12112   FCmpInst::Predicate FPred; Value *Y;
12113   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
12114                              TrueDest, FalseDest), *Context))
12115     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12116          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12117       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12118       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
12119       Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
12120       NewSCC->takeName(I);
12121       // Swap Destinations and condition...
12122       BI.setCondition(NewSCC);
12123       BI.setSuccessor(0, FalseDest);
12124       BI.setSuccessor(1, TrueDest);
12125       RemoveFromWorkList(I);
12126       I->eraseFromParent();
12127       AddToWorkList(NewSCC);
12128       return &BI;
12129     }
12130
12131   // Cannonicalize icmp_ne -> icmp_eq
12132   ICmpInst::Predicate IPred;
12133   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12134                       TrueDest, FalseDest), *Context))
12135     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12136          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12137          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12138       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12139       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
12140       Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
12141       NewSCC->takeName(I);
12142       // Swap Destinations and condition...
12143       BI.setCondition(NewSCC);
12144       BI.setSuccessor(0, FalseDest);
12145       BI.setSuccessor(1, TrueDest);
12146       RemoveFromWorkList(I);
12147       I->eraseFromParent();;
12148       AddToWorkList(NewSCC);
12149       return &BI;
12150     }
12151
12152   return 0;
12153 }
12154
12155 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12156   Value *Cond = SI.getCondition();
12157   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12158     if (I->getOpcode() == Instruction::Add)
12159       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12160         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12161         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12162           SI.setOperand(i,
12163                    Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
12164                                                 AddRHS));
12165         SI.setOperand(0, I->getOperand(0));
12166         AddToWorkList(I);
12167         return &SI;
12168       }
12169   }
12170   return 0;
12171 }
12172
12173 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12174   Value *Agg = EV.getAggregateOperand();
12175
12176   if (!EV.hasIndices())
12177     return ReplaceInstUsesWith(EV, Agg);
12178
12179   if (Constant *C = dyn_cast<Constant>(Agg)) {
12180     if (isa<UndefValue>(C))
12181       return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
12182       
12183     if (isa<ConstantAggregateZero>(C))
12184       return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
12185
12186     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12187       // Extract the element indexed by the first index out of the constant
12188       Value *V = C->getOperand(*EV.idx_begin());
12189       if (EV.getNumIndices() > 1)
12190         // Extract the remaining indices out of the constant indexed by the
12191         // first index
12192         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12193       else
12194         return ReplaceInstUsesWith(EV, V);
12195     }
12196     return 0; // Can't handle other constants
12197   } 
12198   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12199     // We're extracting from an insertvalue instruction, compare the indices
12200     const unsigned *exti, *exte, *insi, *inse;
12201     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12202          exte = EV.idx_end(), inse = IV->idx_end();
12203          exti != exte && insi != inse;
12204          ++exti, ++insi) {
12205       if (*insi != *exti)
12206         // The insert and extract both reference distinctly different elements.
12207         // This means the extract is not influenced by the insert, and we can
12208         // replace the aggregate operand of the extract with the aggregate
12209         // operand of the insert. i.e., replace
12210         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12211         // %E = extractvalue { i32, { i32 } } %I, 0
12212         // with
12213         // %E = extractvalue { i32, { i32 } } %A, 0
12214         return ExtractValueInst::Create(IV->getAggregateOperand(),
12215                                         EV.idx_begin(), EV.idx_end());
12216     }
12217     if (exti == exte && insi == inse)
12218       // Both iterators are at the end: Index lists are identical. Replace
12219       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12220       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12221       // with "i32 42"
12222       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12223     if (exti == exte) {
12224       // The extract list is a prefix of the insert list. i.e. replace
12225       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12226       // %E = extractvalue { i32, { i32 } } %I, 1
12227       // with
12228       // %X = extractvalue { i32, { i32 } } %A, 1
12229       // %E = insertvalue { i32 } %X, i32 42, 0
12230       // by switching the order of the insert and extract (though the
12231       // insertvalue should be left in, since it may have other uses).
12232       Value *NewEV = InsertNewInstBefore(
12233         ExtractValueInst::Create(IV->getAggregateOperand(),
12234                                  EV.idx_begin(), EV.idx_end()),
12235         EV);
12236       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12237                                      insi, inse);
12238     }
12239     if (insi == inse)
12240       // The insert list is a prefix of the extract list
12241       // We can simply remove the common indices from the extract and make it
12242       // operate on the inserted value instead of the insertvalue result.
12243       // i.e., replace
12244       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12245       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12246       // with
12247       // %E extractvalue { i32 } { i32 42 }, 0
12248       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12249                                       exti, exte);
12250   }
12251   // Can't simplify extracts from other values. Note that nested extracts are
12252   // already simplified implicitely by the above (extract ( extract (insert) )
12253   // will be translated into extract ( insert ( extract ) ) first and then just
12254   // the value inserted, if appropriate).
12255   return 0;
12256 }
12257
12258 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12259 /// is to leave as a vector operation.
12260 static bool CheapToScalarize(Value *V, bool isConstant) {
12261   if (isa<ConstantAggregateZero>(V)) 
12262     return true;
12263   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12264     if (isConstant) return true;
12265     // If all elts are the same, we can extract.
12266     Constant *Op0 = C->getOperand(0);
12267     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12268       if (C->getOperand(i) != Op0)
12269         return false;
12270     return true;
12271   }
12272   Instruction *I = dyn_cast<Instruction>(V);
12273   if (!I) return false;
12274   
12275   // Insert element gets simplified to the inserted element or is deleted if
12276   // this is constant idx extract element and its a constant idx insertelt.
12277   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12278       isa<ConstantInt>(I->getOperand(2)))
12279     return true;
12280   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12281     return true;
12282   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12283     if (BO->hasOneUse() &&
12284         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12285          CheapToScalarize(BO->getOperand(1), isConstant)))
12286       return true;
12287   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12288     if (CI->hasOneUse() &&
12289         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12290          CheapToScalarize(CI->getOperand(1), isConstant)))
12291       return true;
12292   
12293   return false;
12294 }
12295
12296 /// Read and decode a shufflevector mask.
12297 ///
12298 /// It turns undef elements into values that are larger than the number of
12299 /// elements in the input.
12300 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12301   unsigned NElts = SVI->getType()->getNumElements();
12302   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12303     return std::vector<unsigned>(NElts, 0);
12304   if (isa<UndefValue>(SVI->getOperand(2)))
12305     return std::vector<unsigned>(NElts, 2*NElts);
12306
12307   std::vector<unsigned> Result;
12308   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12309   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12310     if (isa<UndefValue>(*i))
12311       Result.push_back(NElts*2);  // undef -> 8
12312     else
12313       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12314   return Result;
12315 }
12316
12317 /// FindScalarElement - Given a vector and an element number, see if the scalar
12318 /// value is already around as a register, for example if it were inserted then
12319 /// extracted from the vector.
12320 static Value *FindScalarElement(Value *V, unsigned EltNo,
12321                                 LLVMContext *Context) {
12322   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12323   const VectorType *PTy = cast<VectorType>(V->getType());
12324   unsigned Width = PTy->getNumElements();
12325   if (EltNo >= Width)  // Out of range access.
12326     return Context->getUndef(PTy->getElementType());
12327   
12328   if (isa<UndefValue>(V))
12329     return Context->getUndef(PTy->getElementType());
12330   else if (isa<ConstantAggregateZero>(V))
12331     return Context->getNullValue(PTy->getElementType());
12332   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12333     return CP->getOperand(EltNo);
12334   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12335     // If this is an insert to a variable element, we don't know what it is.
12336     if (!isa<ConstantInt>(III->getOperand(2))) 
12337       return 0;
12338     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12339     
12340     // If this is an insert to the element we are looking for, return the
12341     // inserted value.
12342     if (EltNo == IIElt) 
12343       return III->getOperand(1);
12344     
12345     // Otherwise, the insertelement doesn't modify the value, recurse on its
12346     // vector input.
12347     return FindScalarElement(III->getOperand(0), EltNo, Context);
12348   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12349     unsigned LHSWidth =
12350       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12351     unsigned InEl = getShuffleMask(SVI)[EltNo];
12352     if (InEl < LHSWidth)
12353       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12354     else if (InEl < LHSWidth*2)
12355       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12356     else
12357       return Context->getUndef(PTy->getElementType());
12358   }
12359   
12360   // Otherwise, we don't know.
12361   return 0;
12362 }
12363
12364 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12365   // If vector val is undef, replace extract with scalar undef.
12366   if (isa<UndefValue>(EI.getOperand(0)))
12367     return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12368
12369   // If vector val is constant 0, replace extract with scalar 0.
12370   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12371     return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
12372   
12373   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12374     // If vector val is constant with all elements the same, replace EI with
12375     // that element. When the elements are not identical, we cannot replace yet
12376     // (we do that below, but only when the index is constant).
12377     Constant *op0 = C->getOperand(0);
12378     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12379       if (C->getOperand(i) != op0) {
12380         op0 = 0; 
12381         break;
12382       }
12383     if (op0)
12384       return ReplaceInstUsesWith(EI, op0);
12385   }
12386   
12387   // If extracting a specified index from the vector, see if we can recursively
12388   // find a previously computed scalar that was inserted into the vector.
12389   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12390     unsigned IndexVal = IdxC->getZExtValue();
12391     unsigned VectorWidth = 
12392       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12393       
12394     // If this is extracting an invalid index, turn this into undef, to avoid
12395     // crashing the code below.
12396     if (IndexVal >= VectorWidth)
12397       return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12398     
12399     // This instruction only demands the single element from the input vector.
12400     // If the input vector has a single use, simplify it based on this use
12401     // property.
12402     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12403       APInt UndefElts(VectorWidth, 0);
12404       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12405       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12406                                                 DemandedMask, UndefElts)) {
12407         EI.setOperand(0, V);
12408         return &EI;
12409       }
12410     }
12411     
12412     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12413       return ReplaceInstUsesWith(EI, Elt);
12414     
12415     // If the this extractelement is directly using a bitcast from a vector of
12416     // the same number of elements, see if we can find the source element from
12417     // it.  In this case, we will end up needing to bitcast the scalars.
12418     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12419       if (const VectorType *VT = 
12420               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12421         if (VT->getNumElements() == VectorWidth)
12422           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12423                                              IndexVal, Context))
12424             return new BitCastInst(Elt, EI.getType());
12425     }
12426   }
12427   
12428   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12429     if (I->hasOneUse()) {
12430       // Push extractelement into predecessor operation if legal and
12431       // profitable to do so
12432       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12433         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12434         if (CheapToScalarize(BO, isConstantElt)) {
12435           ExtractElementInst *newEI0 = 
12436             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12437                                    EI.getName()+".lhs");
12438           ExtractElementInst *newEI1 =
12439             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12440                                    EI.getName()+".rhs");
12441           InsertNewInstBefore(newEI0, EI);
12442           InsertNewInstBefore(newEI1, EI);
12443           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12444         }
12445       } else if (isa<LoadInst>(I)) {
12446         unsigned AS = 
12447           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12448         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12449                                   Context->getPointerType(EI.getType(), AS),EI);
12450         GetElementPtrInst *GEP =
12451           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12452         InsertNewInstBefore(GEP, EI);
12453         return new LoadInst(GEP);
12454       }
12455     }
12456     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12457       // Extracting the inserted element?
12458       if (IE->getOperand(2) == EI.getOperand(1))
12459         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12460       // If the inserted and extracted elements are constants, they must not
12461       // be the same value, extract from the pre-inserted value instead.
12462       if (isa<Constant>(IE->getOperand(2)) &&
12463           isa<Constant>(EI.getOperand(1))) {
12464         AddUsesToWorkList(EI);
12465         EI.setOperand(0, IE->getOperand(0));
12466         return &EI;
12467       }
12468     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12469       // If this is extracting an element from a shufflevector, figure out where
12470       // it came from and extract from the appropriate input element instead.
12471       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12472         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12473         Value *Src;
12474         unsigned LHSWidth =
12475           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12476
12477         if (SrcIdx < LHSWidth)
12478           Src = SVI->getOperand(0);
12479         else if (SrcIdx < LHSWidth*2) {
12480           SrcIdx -= LHSWidth;
12481           Src = SVI->getOperand(1);
12482         } else {
12483           return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12484         }
12485         return new ExtractElementInst(Src,
12486                          Context->getConstantInt(Type::Int32Ty, SrcIdx, false));
12487       }
12488     }
12489   }
12490   return 0;
12491 }
12492
12493 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12494 /// elements from either LHS or RHS, return the shuffle mask and true. 
12495 /// Otherwise, return false.
12496 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12497                                          std::vector<Constant*> &Mask,
12498                                          LLVMContext *Context) {
12499   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12500          "Invalid CollectSingleShuffleElements");
12501   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12502
12503   if (isa<UndefValue>(V)) {
12504     Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12505     return true;
12506   } else if (V == LHS) {
12507     for (unsigned i = 0; i != NumElts; ++i)
12508       Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12509     return true;
12510   } else if (V == RHS) {
12511     for (unsigned i = 0; i != NumElts; ++i)
12512       Mask.push_back(Context->getConstantInt(Type::Int32Ty, i+NumElts));
12513     return true;
12514   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12515     // If this is an insert of an extract from some other vector, include it.
12516     Value *VecOp    = IEI->getOperand(0);
12517     Value *ScalarOp = IEI->getOperand(1);
12518     Value *IdxOp    = IEI->getOperand(2);
12519     
12520     if (!isa<ConstantInt>(IdxOp))
12521       return false;
12522     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12523     
12524     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12525       // Okay, we can handle this if the vector we are insertinting into is
12526       // transitively ok.
12527       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12528         // If so, update the mask to reflect the inserted undef.
12529         Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
12530         return true;
12531       }      
12532     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12533       if (isa<ConstantInt>(EI->getOperand(1)) &&
12534           EI->getOperand(0)->getType() == V->getType()) {
12535         unsigned ExtractedIdx =
12536           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12537         
12538         // This must be extracting from either LHS or RHS.
12539         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12540           // Okay, we can handle this if the vector we are insertinting into is
12541           // transitively ok.
12542           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12543             // If so, update the mask to reflect the inserted value.
12544             if (EI->getOperand(0) == LHS) {
12545               Mask[InsertedIdx % NumElts] = 
12546                  Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12547             } else {
12548               assert(EI->getOperand(0) == RHS);
12549               Mask[InsertedIdx % NumElts] = 
12550                 Context->getConstantInt(Type::Int32Ty, ExtractedIdx+NumElts);
12551               
12552             }
12553             return true;
12554           }
12555         }
12556       }
12557     }
12558   }
12559   // TODO: Handle shufflevector here!
12560   
12561   return false;
12562 }
12563
12564 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12565 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12566 /// that computes V and the LHS value of the shuffle.
12567 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12568                                      Value *&RHS, LLVMContext *Context) {
12569   assert(isa<VectorType>(V->getType()) && 
12570          (RHS == 0 || V->getType() == RHS->getType()) &&
12571          "Invalid shuffle!");
12572   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12573
12574   if (isa<UndefValue>(V)) {
12575     Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12576     return V;
12577   } else if (isa<ConstantAggregateZero>(V)) {
12578     Mask.assign(NumElts, Context->getConstantInt(Type::Int32Ty, 0));
12579     return V;
12580   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12581     // If this is an insert of an extract from some other vector, include it.
12582     Value *VecOp    = IEI->getOperand(0);
12583     Value *ScalarOp = IEI->getOperand(1);
12584     Value *IdxOp    = IEI->getOperand(2);
12585     
12586     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12587       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12588           EI->getOperand(0)->getType() == V->getType()) {
12589         unsigned ExtractedIdx =
12590           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12591         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12592         
12593         // Either the extracted from or inserted into vector must be RHSVec,
12594         // otherwise we'd end up with a shuffle of three inputs.
12595         if (EI->getOperand(0) == RHS || RHS == 0) {
12596           RHS = EI->getOperand(0);
12597           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12598           Mask[InsertedIdx % NumElts] = 
12599             Context->getConstantInt(Type::Int32Ty, NumElts+ExtractedIdx);
12600           return V;
12601         }
12602         
12603         if (VecOp == RHS) {
12604           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12605                                             RHS, Context);
12606           // Everything but the extracted element is replaced with the RHS.
12607           for (unsigned i = 0; i != NumElts; ++i) {
12608             if (i != InsertedIdx)
12609               Mask[i] = Context->getConstantInt(Type::Int32Ty, NumElts+i);
12610           }
12611           return V;
12612         }
12613         
12614         // If this insertelement is a chain that comes from exactly these two
12615         // vectors, return the vector and the effective shuffle.
12616         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12617                                          Context))
12618           return EI->getOperand(0);
12619         
12620       }
12621     }
12622   }
12623   // TODO: Handle shufflevector here!
12624   
12625   // Otherwise, can't do anything fancy.  Return an identity vector.
12626   for (unsigned i = 0; i != NumElts; ++i)
12627     Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12628   return V;
12629 }
12630
12631 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12632   Value *VecOp    = IE.getOperand(0);
12633   Value *ScalarOp = IE.getOperand(1);
12634   Value *IdxOp    = IE.getOperand(2);
12635   
12636   // Inserting an undef or into an undefined place, remove this.
12637   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12638     ReplaceInstUsesWith(IE, VecOp);
12639   
12640   // If the inserted element was extracted from some other vector, and if the 
12641   // indexes are constant, try to turn this into a shufflevector operation.
12642   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12643     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12644         EI->getOperand(0)->getType() == IE.getType()) {
12645       unsigned NumVectorElts = IE.getType()->getNumElements();
12646       unsigned ExtractedIdx =
12647         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12648       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12649       
12650       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12651         return ReplaceInstUsesWith(IE, VecOp);
12652       
12653       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12654         return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
12655       
12656       // If we are extracting a value from a vector, then inserting it right
12657       // back into the same place, just use the input vector.
12658       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12659         return ReplaceInstUsesWith(IE, VecOp);      
12660       
12661       // We could theoretically do this for ANY input.  However, doing so could
12662       // turn chains of insertelement instructions into a chain of shufflevector
12663       // instructions, and right now we do not merge shufflevectors.  As such,
12664       // only do this in a situation where it is clear that there is benefit.
12665       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12666         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12667         // the values of VecOp, except then one read from EIOp0.
12668         // Build a new shuffle mask.
12669         std::vector<Constant*> Mask;
12670         if (isa<UndefValue>(VecOp))
12671           Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
12672         else {
12673           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12674           Mask.assign(NumVectorElts, Context->getConstantInt(Type::Int32Ty,
12675                                                        NumVectorElts));
12676         } 
12677         Mask[InsertedIdx] = 
12678                            Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12679         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12680                                      Context->getConstantVector(Mask));
12681       }
12682       
12683       // If this insertelement isn't used by some other insertelement, turn it
12684       // (and any insertelements it points to), into one big shuffle.
12685       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12686         std::vector<Constant*> Mask;
12687         Value *RHS = 0;
12688         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12689         if (RHS == 0) RHS = Context->getUndef(LHS->getType());
12690         // We now have a shuffle of LHS, RHS, Mask.
12691         return new ShuffleVectorInst(LHS, RHS,
12692                                      Context->getConstantVector(Mask));
12693       }
12694     }
12695   }
12696
12697   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12698   APInt UndefElts(VWidth, 0);
12699   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12700   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12701     return &IE;
12702
12703   return 0;
12704 }
12705
12706
12707 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12708   Value *LHS = SVI.getOperand(0);
12709   Value *RHS = SVI.getOperand(1);
12710   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12711
12712   bool MadeChange = false;
12713
12714   // Undefined shuffle mask -> undefined value.
12715   if (isa<UndefValue>(SVI.getOperand(2)))
12716     return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
12717
12718   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12719
12720   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12721     return 0;
12722
12723   APInt UndefElts(VWidth, 0);
12724   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12725   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12726     LHS = SVI.getOperand(0);
12727     RHS = SVI.getOperand(1);
12728     MadeChange = true;
12729   }
12730   
12731   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12732   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12733   if (LHS == RHS || isa<UndefValue>(LHS)) {
12734     if (isa<UndefValue>(LHS) && LHS == RHS) {
12735       // shuffle(undef,undef,mask) -> undef.
12736       return ReplaceInstUsesWith(SVI, LHS);
12737     }
12738     
12739     // Remap any references to RHS to use LHS.
12740     std::vector<Constant*> Elts;
12741     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12742       if (Mask[i] >= 2*e)
12743         Elts.push_back(Context->getUndef(Type::Int32Ty));
12744       else {
12745         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12746             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12747           Mask[i] = 2*e;     // Turn into undef.
12748           Elts.push_back(Context->getUndef(Type::Int32Ty));
12749         } else {
12750           Mask[i] = Mask[i] % e;  // Force to LHS.
12751           Elts.push_back(Context->getConstantInt(Type::Int32Ty, Mask[i]));
12752         }
12753       }
12754     }
12755     SVI.setOperand(0, SVI.getOperand(1));
12756     SVI.setOperand(1, Context->getUndef(RHS->getType()));
12757     SVI.setOperand(2, Context->getConstantVector(Elts));
12758     LHS = SVI.getOperand(0);
12759     RHS = SVI.getOperand(1);
12760     MadeChange = true;
12761   }
12762   
12763   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12764   bool isLHSID = true, isRHSID = true;
12765     
12766   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12767     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12768     // Is this an identity shuffle of the LHS value?
12769     isLHSID &= (Mask[i] == i);
12770       
12771     // Is this an identity shuffle of the RHS value?
12772     isRHSID &= (Mask[i]-e == i);
12773   }
12774
12775   // Eliminate identity shuffles.
12776   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12777   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12778   
12779   // If the LHS is a shufflevector itself, see if we can combine it with this
12780   // one without producing an unusual shuffle.  Here we are really conservative:
12781   // we are absolutely afraid of producing a shuffle mask not in the input
12782   // program, because the code gen may not be smart enough to turn a merged
12783   // shuffle into two specific shuffles: it may produce worse code.  As such,
12784   // we only merge two shuffles if the result is one of the two input shuffle
12785   // masks.  In this case, merging the shuffles just removes one instruction,
12786   // which we know is safe.  This is good for things like turning:
12787   // (splat(splat)) -> splat.
12788   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12789     if (isa<UndefValue>(RHS)) {
12790       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12791
12792       std::vector<unsigned> NewMask;
12793       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12794         if (Mask[i] >= 2*e)
12795           NewMask.push_back(2*e);
12796         else
12797           NewMask.push_back(LHSMask[Mask[i]]);
12798       
12799       // If the result mask is equal to the src shuffle or this shuffle mask, do
12800       // the replacement.
12801       if (NewMask == LHSMask || NewMask == Mask) {
12802         unsigned LHSInNElts =
12803           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12804         std::vector<Constant*> Elts;
12805         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12806           if (NewMask[i] >= LHSInNElts*2) {
12807             Elts.push_back(Context->getUndef(Type::Int32Ty));
12808           } else {
12809             Elts.push_back(Context->getConstantInt(Type::Int32Ty, NewMask[i]));
12810           }
12811         }
12812         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12813                                      LHSSVI->getOperand(1),
12814                                      Context->getConstantVector(Elts));
12815       }
12816     }
12817   }
12818
12819   return MadeChange ? &SVI : 0;
12820 }
12821
12822
12823
12824
12825 /// TryToSinkInstruction - Try to move the specified instruction from its
12826 /// current block into the beginning of DestBlock, which can only happen if it's
12827 /// safe to move the instruction past all of the instructions between it and the
12828 /// end of its block.
12829 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12830   assert(I->hasOneUse() && "Invariants didn't hold!");
12831
12832   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12833   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12834     return false;
12835
12836   // Do not sink alloca instructions out of the entry block.
12837   if (isa<AllocaInst>(I) && I->getParent() ==
12838         &DestBlock->getParent()->getEntryBlock())
12839     return false;
12840
12841   // We can only sink load instructions if there is nothing between the load and
12842   // the end of block that could change the value.
12843   if (I->mayReadFromMemory()) {
12844     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12845          Scan != E; ++Scan)
12846       if (Scan->mayWriteToMemory())
12847         return false;
12848   }
12849
12850   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12851
12852   CopyPrecedingStopPoint(I, InsertPos);
12853   I->moveBefore(InsertPos);
12854   ++NumSunkInst;
12855   return true;
12856 }
12857
12858
12859 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12860 /// all reachable code to the worklist.
12861 ///
12862 /// This has a couple of tricks to make the code faster and more powerful.  In
12863 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12864 /// them to the worklist (this significantly speeds up instcombine on code where
12865 /// many instructions are dead or constant).  Additionally, if we find a branch
12866 /// whose condition is a known constant, we only visit the reachable successors.
12867 ///
12868 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12869                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12870                                        InstCombiner &IC,
12871                                        const TargetData *TD) {
12872   SmallVector<BasicBlock*, 256> Worklist;
12873   Worklist.push_back(BB);
12874
12875   while (!Worklist.empty()) {
12876     BB = Worklist.back();
12877     Worklist.pop_back();
12878     
12879     // We have now visited this block!  If we've already been here, ignore it.
12880     if (!Visited.insert(BB)) continue;
12881
12882     DbgInfoIntrinsic *DBI_Prev = NULL;
12883     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12884       Instruction *Inst = BBI++;
12885       
12886       // DCE instruction if trivially dead.
12887       if (isInstructionTriviallyDead(Inst)) {
12888         ++NumDeadInst;
12889         DOUT << "IC: DCE: " << *Inst;
12890         Inst->eraseFromParent();
12891         continue;
12892       }
12893       
12894       // ConstantProp instruction if trivially constant.
12895       if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12896         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12897         Inst->replaceAllUsesWith(C);
12898         ++NumConstProp;
12899         Inst->eraseFromParent();
12900         continue;
12901       }
12902      
12903       // If there are two consecutive llvm.dbg.stoppoint calls then
12904       // it is likely that the optimizer deleted code in between these
12905       // two intrinsics. 
12906       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12907       if (DBI_Next) {
12908         if (DBI_Prev
12909             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12910             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12911           IC.RemoveFromWorkList(DBI_Prev);
12912           DBI_Prev->eraseFromParent();
12913         }
12914         DBI_Prev = DBI_Next;
12915       } else {
12916         DBI_Prev = 0;
12917       }
12918
12919       IC.AddToWorkList(Inst);
12920     }
12921
12922     // Recursively visit successors.  If this is a branch or switch on a
12923     // constant, only visit the reachable successor.
12924     TerminatorInst *TI = BB->getTerminator();
12925     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12926       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12927         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12928         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12929         Worklist.push_back(ReachableBB);
12930         continue;
12931       }
12932     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12933       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12934         // See if this is an explicit destination.
12935         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12936           if (SI->getCaseValue(i) == Cond) {
12937             BasicBlock *ReachableBB = SI->getSuccessor(i);
12938             Worklist.push_back(ReachableBB);
12939             continue;
12940           }
12941         
12942         // Otherwise it is the default destination.
12943         Worklist.push_back(SI->getSuccessor(0));
12944         continue;
12945       }
12946     }
12947     
12948     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12949       Worklist.push_back(TI->getSuccessor(i));
12950   }
12951 }
12952
12953 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12954   bool Changed = false;
12955   TD = &getAnalysis<TargetData>();
12956   
12957   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12958              << F.getNameStr() << "\n");
12959
12960   {
12961     // Do a depth-first traversal of the function, populate the worklist with
12962     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12963     // track of which blocks we visit.
12964     SmallPtrSet<BasicBlock*, 64> Visited;
12965     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12966
12967     // Do a quick scan over the function.  If we find any blocks that are
12968     // unreachable, remove any instructions inside of them.  This prevents
12969     // the instcombine code from having to deal with some bad special cases.
12970     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12971       if (!Visited.count(BB)) {
12972         Instruction *Term = BB->getTerminator();
12973         while (Term != BB->begin()) {   // Remove instrs bottom-up
12974           BasicBlock::iterator I = Term; --I;
12975
12976           DOUT << "IC: DCE: " << *I;
12977           // A debug intrinsic shouldn't force another iteration if we weren't
12978           // going to do one without it.
12979           if (!isa<DbgInfoIntrinsic>(I)) {
12980             ++NumDeadInst;
12981             Changed = true;
12982           }
12983           if (!I->use_empty())
12984             I->replaceAllUsesWith(Context->getUndef(I->getType()));
12985           I->eraseFromParent();
12986         }
12987       }
12988   }
12989
12990   while (!Worklist.empty()) {
12991     Instruction *I = RemoveOneFromWorkList();
12992     if (I == 0) continue;  // skip null values.
12993
12994     // Check to see if we can DCE the instruction.
12995     if (isInstructionTriviallyDead(I)) {
12996       // Add operands to the worklist.
12997       if (I->getNumOperands() < 4)
12998         AddUsesToWorkList(*I);
12999       ++NumDeadInst;
13000
13001       DOUT << "IC: DCE: " << *I;
13002
13003       I->eraseFromParent();
13004       RemoveFromWorkList(I);
13005       Changed = true;
13006       continue;
13007     }
13008
13009     // Instruction isn't dead, see if we can constant propagate it.
13010     if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
13011       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
13012
13013       // Add operands to the worklist.
13014       AddUsesToWorkList(*I);
13015       ReplaceInstUsesWith(*I, C);
13016
13017       ++NumConstProp;
13018       I->eraseFromParent();
13019       RemoveFromWorkList(I);
13020       Changed = true;
13021       continue;
13022     }
13023
13024     if (TD &&
13025         (I->getType()->getTypeID() == Type::VoidTyID ||
13026          I->isTrapping())) {
13027       // See if we can constant fold its operands.
13028       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13029         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
13030           if (Constant *NewC = ConstantFoldConstantExpression(CE,   
13031                                   F.getContext(), TD))
13032             if (NewC != CE) {
13033               i->set(NewC);
13034               Changed = true;
13035             }
13036     }
13037
13038     // See if we can trivially sink this instruction to a successor basic block.
13039     if (I->hasOneUse()) {
13040       BasicBlock *BB = I->getParent();
13041       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13042       if (UserParent != BB) {
13043         bool UserIsSuccessor = false;
13044         // See if the user is one of our successors.
13045         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13046           if (*SI == UserParent) {
13047             UserIsSuccessor = true;
13048             break;
13049           }
13050
13051         // If the user is one of our immediate successors, and if that successor
13052         // only has us as a predecessors (we'd have to split the critical edge
13053         // otherwise), we can keep going.
13054         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13055             next(pred_begin(UserParent)) == pred_end(UserParent))
13056           // Okay, the CFG is simple enough, try to sink this instruction.
13057           Changed |= TryToSinkInstruction(I, UserParent);
13058       }
13059     }
13060
13061     // Now that we have an instruction, try combining it to simplify it...
13062 #ifndef NDEBUG
13063     std::string OrigI;
13064 #endif
13065     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
13066     if (Instruction *Result = visit(*I)) {
13067       ++NumCombined;
13068       // Should we replace the old instruction with a new one?
13069       if (Result != I) {
13070         DOUT << "IC: Old = " << *I
13071              << "    New = " << *Result;
13072
13073         // Everything uses the new instruction now.
13074         I->replaceAllUsesWith(Result);
13075
13076         // Push the new instruction and any users onto the worklist.
13077         AddToWorkList(Result);
13078         AddUsersToWorkList(*Result);
13079
13080         // Move the name to the new instruction first.
13081         Result->takeName(I);
13082
13083         // Insert the new instruction into the basic block...
13084         BasicBlock *InstParent = I->getParent();
13085         BasicBlock::iterator InsertPos = I;
13086
13087         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
13088           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13089             ++InsertPos;
13090
13091         InstParent->getInstList().insert(InsertPos, Result);
13092
13093         // Make sure that we reprocess all operands now that we reduced their
13094         // use counts.
13095         AddUsesToWorkList(*I);
13096
13097         // Instructions can end up on the worklist more than once.  Make sure
13098         // we do not process an instruction that has been deleted.
13099         RemoveFromWorkList(I);
13100
13101         // Erase the old instruction.
13102         InstParent->getInstList().erase(I);
13103       } else {
13104 #ifndef NDEBUG
13105         DOUT << "IC: Mod = " << OrigI
13106              << "    New = " << *I;
13107 #endif
13108
13109         // If the instruction was modified, it's possible that it is now dead.
13110         // if so, remove it.
13111         if (isInstructionTriviallyDead(I)) {
13112           // Make sure we process all operands now that we are reducing their
13113           // use counts.
13114           AddUsesToWorkList(*I);
13115
13116           // Instructions may end up in the worklist more than once.  Erase all
13117           // occurrences of this instruction.
13118           RemoveFromWorkList(I);
13119           I->eraseFromParent();
13120         } else {
13121           AddToWorkList(I);
13122           AddUsersToWorkList(*I);
13123         }
13124       }
13125       Changed = true;
13126     }
13127   }
13128
13129   assert(WorklistMap.empty() && "Worklist empty, but map not?");
13130     
13131   // Do an explicit clear, this shrinks the map if needed.
13132   WorklistMap.clear();
13133   return Changed;
13134 }
13135
13136
13137 bool InstCombiner::runOnFunction(Function &F) {
13138   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13139   
13140   bool EverMadeChange = false;
13141
13142   // Iterate while there is work to do.
13143   unsigned Iteration = 0;
13144   while (DoOneIteration(F, Iteration++))
13145     EverMadeChange = true;
13146   return EverMadeChange;
13147 }
13148
13149 FunctionPass *llvm::createInstructionCombiningPass() {
13150   return new InstCombiner();
13151 }