Get rid of the Pass+Context magic.
[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/Operator.h"
44 #include "llvm/Analysis/ConstantFolding.h"
45 #include "llvm/Analysis/ValueTracking.h"
46 #include "llvm/Target/TargetData.h"
47 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
48 #include "llvm/Transforms/Utils/Local.h"
49 #include "llvm/Support/CallSite.h"
50 #include "llvm/Support/ConstantRange.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/GetElementPtrTypeIterator.h"
54 #include "llvm/Support/InstVisitor.h"
55 #include "llvm/Support/MathExtras.h"
56 #include "llvm/Support/PatternMatch.h"
57 #include "llvm/Support/Compiler.h"
58 #include "llvm/ADT/DenseMap.h"
59 #include "llvm/ADT/SmallVector.h"
60 #include "llvm/ADT/SmallPtrSet.h"
61 #include "llvm/ADT/Statistic.h"
62 #include "llvm/ADT/STLExtras.h"
63 #include <algorithm>
64 #include <climits>
65 #include <sstream>
66 using namespace llvm;
67 using namespace llvm::PatternMatch;
68
69 STATISTIC(NumCombined , "Number of insts combined");
70 STATISTIC(NumConstProp, "Number of constant folds");
71 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
72 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
73 STATISTIC(NumSunkInst , "Number of instructions sunk");
74
75 namespace {
76   class VISIBILITY_HIDDEN InstCombiner
77     : public FunctionPass,
78       public InstVisitor<InstCombiner, Instruction*> {
79     // Worklist of all of the instructions that need to be simplified.
80     SmallVector<Instruction*, 256> Worklist;
81     DenseMap<Instruction*, unsigned> WorklistMap;
82     TargetData *TD;
83     bool MustPreserveLCSSA;
84   public:
85     static char ID; // Pass identification, replacement for typeid
86     InstCombiner() : FunctionPass(&ID) {}
87
88     LLVMContext *Context;
89     LLVMContext *getContext() const { return Context; }
90
91     /// AddToWorkList - Add the specified instruction to the worklist if it
92     /// isn't already in it.
93     void AddToWorkList(Instruction *I) {
94       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
95         Worklist.push_back(I);
96     }
97     
98     // RemoveFromWorkList - remove I from the worklist if it exists.
99     void RemoveFromWorkList(Instruction *I) {
100       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
101       if (It == WorklistMap.end()) return; // Not in worklist.
102       
103       // Don't bother moving everything down, just null out the slot.
104       Worklist[It->second] = 0;
105       
106       WorklistMap.erase(It);
107     }
108     
109     Instruction *RemoveOneFromWorkList() {
110       Instruction *I = Worklist.back();
111       Worklist.pop_back();
112       WorklistMap.erase(I);
113       return I;
114     }
115
116     
117     /// AddUsersToWorkList - When an instruction is simplified, add all users of
118     /// the instruction to the work lists because they might get more simplified
119     /// now.
120     ///
121     void AddUsersToWorkList(Value &I) {
122       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
123            UI != UE; ++UI)
124         AddToWorkList(cast<Instruction>(*UI));
125     }
126
127     /// AddUsesToWorkList - When an instruction is simplified, add operands to
128     /// the work lists because they might get more simplified now.
129     ///
130     void AddUsesToWorkList(Instruction &I) {
131       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
132         if (Instruction *Op = dyn_cast<Instruction>(*i))
133           AddToWorkList(Op);
134     }
135     
136     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
137     /// dead.  Add all of its operands to the worklist, turning them into
138     /// undef's to reduce the number of uses of those instructions.
139     ///
140     /// Return the specified operand before it is turned into an undef.
141     ///
142     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
143       Value *R = I.getOperand(op);
144       
145       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
146         if (Instruction *Op = dyn_cast<Instruction>(*i)) {
147           AddToWorkList(Op);
148           // Set the operand to undef to drop the use.
149           *i = Context->getUndef(Op->getType());
150         }
151       
152       return R;
153     }
154
155   public:
156     virtual bool runOnFunction(Function &F);
157     
158     bool DoOneIteration(Function &F, unsigned ItNum);
159
160     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
161       AU.addPreservedID(LCSSAID);
162       AU.setPreservesCFG();
163     }
164
165     TargetData *getTargetData() const { return TD; }
166
167     // Visitation implementation - Implement instruction combining for different
168     // instruction types.  The semantics are as follows:
169     // Return Value:
170     //    null        - No change was made
171     //     I          - Change was made, I is still valid, I may be dead though
172     //   otherwise    - Change was made, replace I with returned instruction
173     //
174     Instruction *visitAdd(BinaryOperator &I);
175     Instruction *visitFAdd(BinaryOperator &I);
176     Instruction *visitSub(BinaryOperator &I);
177     Instruction *visitFSub(BinaryOperator &I);
178     Instruction *visitMul(BinaryOperator &I);
179     Instruction *visitFMul(BinaryOperator &I);
180     Instruction *visitURem(BinaryOperator &I);
181     Instruction *visitSRem(BinaryOperator &I);
182     Instruction *visitFRem(BinaryOperator &I);
183     bool SimplifyDivRemOfSelect(BinaryOperator &I);
184     Instruction *commonRemTransforms(BinaryOperator &I);
185     Instruction *commonIRemTransforms(BinaryOperator &I);
186     Instruction *commonDivTransforms(BinaryOperator &I);
187     Instruction *commonIDivTransforms(BinaryOperator &I);
188     Instruction *visitUDiv(BinaryOperator &I);
189     Instruction *visitSDiv(BinaryOperator &I);
190     Instruction *visitFDiv(BinaryOperator &I);
191     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
192     Instruction *visitAnd(BinaryOperator &I);
193     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
194     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
195                                      Value *A, Value *B, Value *C);
196     Instruction *visitOr (BinaryOperator &I);
197     Instruction *visitXor(BinaryOperator &I);
198     Instruction *visitShl(BinaryOperator &I);
199     Instruction *visitAShr(BinaryOperator &I);
200     Instruction *visitLShr(BinaryOperator &I);
201     Instruction *commonShiftTransforms(BinaryOperator &I);
202     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
203                                       Constant *RHSC);
204     Instruction *visitFCmpInst(FCmpInst &I);
205     Instruction *visitICmpInst(ICmpInst &I);
206     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
207     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
208                                                 Instruction *LHS,
209                                                 ConstantInt *RHS);
210     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
211                                 ConstantInt *DivRHS);
212
213     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
214                              ICmpInst::Predicate Cond, Instruction &I);
215     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
216                                      BinaryOperator &I);
217     Instruction *commonCastTransforms(CastInst &CI);
218     Instruction *commonIntCastTransforms(CastInst &CI);
219     Instruction *commonPointerCastTransforms(CastInst &CI);
220     Instruction *visitTrunc(TruncInst &CI);
221     Instruction *visitZExt(ZExtInst &CI);
222     Instruction *visitSExt(SExtInst &CI);
223     Instruction *visitFPTrunc(FPTruncInst &CI);
224     Instruction *visitFPExt(CastInst &CI);
225     Instruction *visitFPToUI(FPToUIInst &FI);
226     Instruction *visitFPToSI(FPToSIInst &FI);
227     Instruction *visitUIToFP(CastInst &CI);
228     Instruction *visitSIToFP(CastInst &CI);
229     Instruction *visitPtrToInt(PtrToIntInst &CI);
230     Instruction *visitIntToPtr(IntToPtrInst &CI);
231     Instruction *visitBitCast(BitCastInst &CI);
232     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
233                                 Instruction *FI);
234     Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
235     Instruction *visitSelectInst(SelectInst &SI);
236     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
237     Instruction *visitCallInst(CallInst &CI);
238     Instruction *visitInvokeInst(InvokeInst &II);
239     Instruction *visitPHINode(PHINode &PN);
240     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
241     Instruction *visitAllocationInst(AllocationInst &AI);
242     Instruction *visitFreeInst(FreeInst &FI);
243     Instruction *visitLoadInst(LoadInst &LI);
244     Instruction *visitStoreInst(StoreInst &SI);
245     Instruction *visitBranchInst(BranchInst &BI);
246     Instruction *visitSwitchInst(SwitchInst &SI);
247     Instruction *visitInsertElementInst(InsertElementInst &IE);
248     Instruction *visitExtractElementInst(ExtractElementInst &EI);
249     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
250     Instruction *visitExtractValueInst(ExtractValueInst &EV);
251
252     // visitInstruction - Specify what to return for unhandled instructions...
253     Instruction *visitInstruction(Instruction &I) { return 0; }
254
255   private:
256     Instruction *visitCallSite(CallSite CS);
257     bool transformConstExprCastCall(CallSite CS);
258     Instruction *transformCallThroughTrampoline(CallSite CS);
259     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
260                                    bool DoXform = true);
261     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
262     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
263
264
265   public:
266     // InsertNewInstBefore - insert an instruction New before instruction Old
267     // in the program.  Add the new instruction to the worklist.
268     //
269     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
270       assert(New && New->getParent() == 0 &&
271              "New instruction already inserted into a basic block!");
272       BasicBlock *BB = Old.getParent();
273       BB->getInstList().insert(&Old, New);  // Insert inst
274       AddToWorkList(New);
275       return New;
276     }
277
278     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
279     /// This also adds the cast to the worklist.  Finally, this returns the
280     /// cast.
281     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
282                             Instruction &Pos) {
283       if (V->getType() == Ty) return V;
284
285       if (Constant *CV = dyn_cast<Constant>(V))
286         return Context->getConstantExprCast(opc, CV, Ty);
287       
288       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
289       AddToWorkList(C);
290       return C;
291     }
292         
293     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
294       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
295     }
296
297
298     // ReplaceInstUsesWith - This method is to be used when an instruction is
299     // found to be dead, replacable with another preexisting expression.  Here
300     // we add all uses of I to the worklist, replace all uses of I with the new
301     // value, then return I, so that the inst combiner will know that I was
302     // modified.
303     //
304     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
305       AddUsersToWorkList(I);         // Add all modified instrs to worklist
306       if (&I != V) {
307         I.replaceAllUsesWith(V);
308         return &I;
309       } else {
310         // If we are replacing the instruction with itself, this must be in a
311         // segment of unreachable code, so just clobber the instruction.
312         I.replaceAllUsesWith(Context->getUndef(I.getType()));
313         return &I;
314       }
315     }
316
317     // EraseInstFromFunction - When dealing with an instruction that has side
318     // effects or produces a void value, we can't rely on DCE to delete the
319     // instruction.  Instead, visit methods should return the value returned by
320     // this function.
321     Instruction *EraseInstFromFunction(Instruction &I) {
322       assert(I.use_empty() && "Cannot erase instruction that is used!");
323       AddUsesToWorkList(I);
324       RemoveFromWorkList(&I);
325       I.eraseFromParent();
326       return 0;  // Don't do anything with FI
327     }
328         
329     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
330                            APInt &KnownOne, unsigned Depth = 0) const {
331       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
332     }
333     
334     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
335                            unsigned Depth = 0) const {
336       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
337     }
338     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
339       return llvm::ComputeNumSignBits(Op, TD, Depth);
340     }
341
342   private:
343
344     /// SimplifyCommutative - This performs a few simplifications for 
345     /// commutative operators.
346     bool SimplifyCommutative(BinaryOperator &I);
347
348     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
349     /// most-complex to least-complex order.
350     bool SimplifyCompare(CmpInst &I);
351
352     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
353     /// based on the demanded bits.
354     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
355                                    APInt& KnownZero, APInt& KnownOne,
356                                    unsigned Depth);
357     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
358                               APInt& KnownZero, APInt& KnownOne,
359                               unsigned Depth=0);
360         
361     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
362     /// SimplifyDemandedBits knows about.  See if the instruction has any
363     /// properties that allow us to simplify its operands.
364     bool SimplifyDemandedInstructionBits(Instruction &Inst);
365         
366     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
367                                       APInt& UndefElts, unsigned Depth = 0);
368       
369     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
370     // PHI node as operand #0, see if we can fold the instruction into the PHI
371     // (which is only possible if all operands to the PHI are constants).
372     Instruction *FoldOpIntoPhi(Instruction &I);
373
374     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
375     // operator and they all are only used by the PHI, PHI together their
376     // inputs, and do the operation once, to the result of the PHI.
377     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
378     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
379     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
380
381     
382     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
383                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
384     
385     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
386                               bool isSub, Instruction &I);
387     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
388                                  bool isSigned, bool Inside, Instruction &IB);
389     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
390     Instruction *MatchBSwap(BinaryOperator &I);
391     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
392     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
393     Instruction *SimplifyMemSet(MemSetInst *MI);
394
395
396     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
397
398     bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
399                                     unsigned CastOpc, int &NumCastsRemoved);
400     unsigned GetOrEnforceKnownAlignment(Value *V,
401                                         unsigned PrefAlign = 0);
402
403   };
404 }
405
406 char InstCombiner::ID = 0;
407 static RegisterPass<InstCombiner>
408 X("instcombine", "Combine redundant instructions");
409
410 // getComplexity:  Assign a complexity or rank value to LLVM Values...
411 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
412 static unsigned getComplexity(LLVMContext *Context, Value *V) {
413   if (isa<Instruction>(V)) {
414     if (BinaryOperator::isNeg(V) ||
415         BinaryOperator::isFNeg(V) ||
416         BinaryOperator::isNot(V))
417       return 3;
418     return 4;
419   }
420   if (isa<Argument>(V)) return 3;
421   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
422 }
423
424 // isOnlyUse - Return true if this instruction will be deleted if we stop using
425 // it.
426 static bool isOnlyUse(Value *V) {
427   return V->hasOneUse() || isa<Constant>(V);
428 }
429
430 // getPromotedType - Return the specified type promoted as it would be to pass
431 // though a va_arg area...
432 static const Type *getPromotedType(const Type *Ty) {
433   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
434     if (ITy->getBitWidth() < 32)
435       return Type::Int32Ty;
436   }
437   return Ty;
438 }
439
440 /// getBitCastOperand - If the specified operand is a CastInst, a constant
441 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
442 /// operand value, otherwise return null.
443 static Value *getBitCastOperand(Value *V) {
444   if (Operator *O = dyn_cast<Operator>(V)) {
445     if (O->getOpcode() == Instruction::BitCast)
446       return O->getOperand(0);
447     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
448       if (GEP->hasAllZeroIndices())
449         return GEP->getPointerOperand();
450   }
451   return 0;
452 }
453
454 /// This function is a wrapper around CastInst::isEliminableCastPair. It
455 /// simply extracts arguments and returns what that function returns.
456 static Instruction::CastOps 
457 isEliminableCastPair(
458   const CastInst *CI, ///< The first cast instruction
459   unsigned opcode,       ///< The opcode of the second cast instruction
460   const Type *DstTy,     ///< The target type for the second cast instruction
461   TargetData *TD         ///< The target data for pointer size
462 ) {
463
464   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
465   const Type *MidTy = CI->getType();                  // B from above
466
467   // Get the opcodes of the two Cast instructions
468   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
469   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
470
471   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
472                                                 DstTy,
473                                                 TD ? TD->getIntPtrType() : 0);
474   
475   // We don't want to form an inttoptr or ptrtoint that converts to an integer
476   // type that differs from the pointer size.
477   if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
478       (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
479     Res = 0;
480   
481   return Instruction::CastOps(Res);
482 }
483
484 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
485 /// in any code being generated.  It does not require codegen if V is simple
486 /// enough or if the cast can be folded into other casts.
487 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
488                               const Type *Ty, TargetData *TD) {
489   if (V->getType() == Ty || isa<Constant>(V)) return false;
490   
491   // If this is another cast that can be eliminated, it isn't codegen either.
492   if (const CastInst *CI = dyn_cast<CastInst>(V))
493     if (isEliminableCastPair(CI, opcode, Ty, TD))
494       return false;
495   return true;
496 }
497
498 // SimplifyCommutative - This performs a few simplifications for commutative
499 // operators:
500 //
501 //  1. Order operands such that they are listed from right (least complex) to
502 //     left (most complex).  This puts constants before unary operators before
503 //     binary operators.
504 //
505 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
506 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
507 //
508 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
509   bool Changed = false;
510   if (getComplexity(Context, I.getOperand(0)) < 
511       getComplexity(Context, I.getOperand(1)))
512     Changed = !I.swapOperands();
513
514   if (!I.isAssociative()) return Changed;
515   Instruction::BinaryOps Opcode = I.getOpcode();
516   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
517     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
518       if (isa<Constant>(I.getOperand(1))) {
519         Constant *Folded = Context->getConstantExpr(I.getOpcode(),
520                                              cast<Constant>(I.getOperand(1)),
521                                              cast<Constant>(Op->getOperand(1)));
522         I.setOperand(0, Op->getOperand(0));
523         I.setOperand(1, Folded);
524         return true;
525       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
526         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
527             isOnlyUse(Op) && isOnlyUse(Op1)) {
528           Constant *C1 = cast<Constant>(Op->getOperand(1));
529           Constant *C2 = cast<Constant>(Op1->getOperand(1));
530
531           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
532           Constant *Folded = Context->getConstantExpr(I.getOpcode(), C1, C2);
533           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
534                                                     Op1->getOperand(0),
535                                                     Op1->getName(), &I);
536           AddToWorkList(New);
537           I.setOperand(0, New);
538           I.setOperand(1, Folded);
539           return true;
540         }
541     }
542   return Changed;
543 }
544
545 /// SimplifyCompare - For a CmpInst this function just orders the operands
546 /// so that theyare listed from right (least complex) to left (most complex).
547 /// This puts constants before unary operators before binary operators.
548 bool InstCombiner::SimplifyCompare(CmpInst &I) {
549   if (getComplexity(Context, I.getOperand(0)) >=
550       getComplexity(Context, I.getOperand(1)))
551     return false;
552   I.swapOperands();
553   // Compare instructions are not associative so there's nothing else we can do.
554   return true;
555 }
556
557 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
558 // if the LHS is a constant zero (which is the 'negate' form).
559 //
560 static inline Value *dyn_castNegVal(Value *V, LLVMContext *Context) {
561   if (BinaryOperator::isNeg(V))
562     return BinaryOperator::getNegArgument(V);
563
564   // Constants can be considered to be negated values if they can be folded.
565   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
566     return Context->getConstantExprNeg(C);
567
568   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
569     if (C->getType()->getElementType()->isInteger())
570       return Context->getConstantExprNeg(C);
571
572   return 0;
573 }
574
575 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
576 // instruction if the LHS is a constant negative zero (which is the 'negate'
577 // form).
578 //
579 static inline Value *dyn_castFNegVal(Value *V, LLVMContext *Context) {
580   if (BinaryOperator::isFNeg(V))
581     return BinaryOperator::getFNegArgument(V);
582
583   // Constants can be considered to be negated values if they can be folded.
584   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
585     return Context->getConstantExprFNeg(C);
586
587   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
588     if (C->getType()->getElementType()->isFloatingPoint())
589       return Context->getConstantExprFNeg(C);
590
591   return 0;
592 }
593
594 static inline Value *dyn_castNotVal(Value *V, LLVMContext *Context) {
595   if (BinaryOperator::isNot(V))
596     return BinaryOperator::getNotArgument(V);
597
598   // Constants can be considered to be not'ed values...
599   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
600     return Context->getConstantInt(~C->getValue());
601   return 0;
602 }
603
604 // dyn_castFoldableMul - If this value is a multiply that can be folded into
605 // other computations (because it has a constant operand), return the
606 // non-constant operand of the multiply, and set CST to point to the multiplier.
607 // Otherwise, return null.
608 //
609 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST,
610                                          LLVMContext *Context) {
611   if (V->hasOneUse() && V->getType()->isInteger())
612     if (Instruction *I = dyn_cast<Instruction>(V)) {
613       if (I->getOpcode() == Instruction::Mul)
614         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
615           return I->getOperand(0);
616       if (I->getOpcode() == Instruction::Shl)
617         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
618           // The multiplier is really 1 << CST.
619           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
620           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
621           CST = Context->getConstantInt(APInt(BitWidth, 1).shl(CSTVal));
622           return I->getOperand(0);
623         }
624     }
625   return 0;
626 }
627
628 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
629 /// expression, return it.
630 static User *dyn_castGetElementPtr(Value *V) {
631   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
632   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
633     if (CE->getOpcode() == Instruction::GetElementPtr)
634       return cast<User>(V);
635   return false;
636 }
637
638 /// AddOne - Add one to a ConstantInt
639 static Constant *AddOne(Constant *C, LLVMContext *Context) {
640   return Context->getConstantExprAdd(C, 
641     Context->getConstantInt(C->getType(), 1));
642 }
643 /// SubOne - Subtract one from a ConstantInt
644 static Constant *SubOne(ConstantInt *C, LLVMContext *Context) {
645   return Context->getConstantExprSub(C, 
646     Context->getConstantInt(C->getType(), 1));
647 }
648 /// MultiplyOverflows - True if the multiply can not be expressed in an int
649 /// this size.
650 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign,
651                               LLVMContext *Context) {
652   uint32_t W = C1->getBitWidth();
653   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
654   if (sign) {
655     LHSExt.sext(W * 2);
656     RHSExt.sext(W * 2);
657   } else {
658     LHSExt.zext(W * 2);
659     RHSExt.zext(W * 2);
660   }
661
662   APInt MulExt = LHSExt * RHSExt;
663
664   if (sign) {
665     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
666     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
667     return MulExt.slt(Min) || MulExt.sgt(Max);
668   } else 
669     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
670 }
671
672
673 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
674 /// specified instruction is a constant integer.  If so, check to see if there
675 /// are any bits set in the constant that are not demanded.  If so, shrink the
676 /// constant and return true.
677 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
678                                    APInt Demanded, LLVMContext *Context) {
679   assert(I && "No instruction?");
680   assert(OpNo < I->getNumOperands() && "Operand index too large");
681
682   // If the operand is not a constant integer, nothing to do.
683   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
684   if (!OpC) return false;
685
686   // If there are no bits set that aren't demanded, nothing to do.
687   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
688   if ((~Demanded & OpC->getValue()) == 0)
689     return false;
690
691   // This instruction is producing bits that are not demanded. Shrink the RHS.
692   Demanded &= OpC->getValue();
693   I->setOperand(OpNo, Context->getConstantInt(Demanded));
694   return true;
695 }
696
697 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
698 // set of known zero and one bits, compute the maximum and minimum values that
699 // could have the specified known zero and known one bits, returning them in
700 // min/max.
701 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
702                                                    const APInt& KnownOne,
703                                                    APInt& Min, APInt& Max) {
704   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
705          KnownZero.getBitWidth() == Min.getBitWidth() &&
706          KnownZero.getBitWidth() == Max.getBitWidth() &&
707          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
708   APInt UnknownBits = ~(KnownZero|KnownOne);
709
710   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
711   // bit if it is unknown.
712   Min = KnownOne;
713   Max = KnownOne|UnknownBits;
714   
715   if (UnknownBits.isNegative()) { // Sign bit is unknown
716     Min.set(Min.getBitWidth()-1);
717     Max.clear(Max.getBitWidth()-1);
718   }
719 }
720
721 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
722 // a set of known zero and one bits, compute the maximum and minimum values that
723 // could have the specified known zero and known one bits, returning them in
724 // min/max.
725 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
726                                                      const APInt &KnownOne,
727                                                      APInt &Min, APInt &Max) {
728   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
729          KnownZero.getBitWidth() == Min.getBitWidth() &&
730          KnownZero.getBitWidth() == Max.getBitWidth() &&
731          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
732   APInt UnknownBits = ~(KnownZero|KnownOne);
733   
734   // The minimum value is when the unknown bits are all zeros.
735   Min = KnownOne;
736   // The maximum value is when the unknown bits are all ones.
737   Max = KnownOne|UnknownBits;
738 }
739
740 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
741 /// SimplifyDemandedBits knows about.  See if the instruction has any
742 /// properties that allow us to simplify its operands.
743 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
744   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
745   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
746   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
747   
748   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
749                                      KnownZero, KnownOne, 0);
750   if (V == 0) return false;
751   if (V == &Inst) return true;
752   ReplaceInstUsesWith(Inst, V);
753   return true;
754 }
755
756 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
757 /// specified instruction operand if possible, updating it in place.  It returns
758 /// true if it made any change and false otherwise.
759 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
760                                         APInt &KnownZero, APInt &KnownOne,
761                                         unsigned Depth) {
762   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
763                                           KnownZero, KnownOne, Depth);
764   if (NewVal == 0) return false;
765   U.set(NewVal);
766   return true;
767 }
768
769
770 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
771 /// value based on the demanded bits.  When this function is called, it is known
772 /// that only the bits set in DemandedMask of the result of V are ever used
773 /// downstream. Consequently, depending on the mask and V, it may be possible
774 /// to replace V with a constant or one of its operands. In such cases, this
775 /// function does the replacement and returns true. In all other cases, it
776 /// returns false after analyzing the expression and setting KnownOne and known
777 /// to be one in the expression.  KnownZero contains all the bits that are known
778 /// to be zero in the expression. These are provided to potentially allow the
779 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
780 /// the expression. KnownOne and KnownZero always follow the invariant that 
781 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
782 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
783 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
784 /// and KnownOne must all be the same.
785 ///
786 /// This returns null if it did not change anything and it permits no
787 /// simplification.  This returns V itself if it did some simplification of V's
788 /// operands based on the information about what bits are demanded. This returns
789 /// some other non-null value if it found out that V is equal to another value
790 /// in the context where the specified bits are demanded, but not for all users.
791 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
792                                              APInt &KnownZero, APInt &KnownOne,
793                                              unsigned Depth) {
794   assert(V != 0 && "Null pointer of Value???");
795   assert(Depth <= 6 && "Limit Search Depth");
796   uint32_t BitWidth = DemandedMask.getBitWidth();
797   const Type *VTy = V->getType();
798   assert((TD || !isa<PointerType>(VTy)) &&
799          "SimplifyDemandedBits needs to know bit widths!");
800   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
801          (!VTy->isIntOrIntVector() ||
802           VTy->getScalarSizeInBits() == BitWidth) &&
803          KnownZero.getBitWidth() == BitWidth &&
804          KnownOne.getBitWidth() == BitWidth &&
805          "Value *V, DemandedMask, KnownZero and KnownOne "
806          "must have same BitWidth");
807   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
808     // We know all of the bits for a constant!
809     KnownOne = CI->getValue() & DemandedMask;
810     KnownZero = ~KnownOne & DemandedMask;
811     return 0;
812   }
813   if (isa<ConstantPointerNull>(V)) {
814     // We know all of the bits for a constant!
815     KnownOne.clear();
816     KnownZero = DemandedMask;
817     return 0;
818   }
819
820   KnownZero.clear();
821   KnownOne.clear();
822   if (DemandedMask == 0) {   // Not demanding any bits from V.
823     if (isa<UndefValue>(V))
824       return 0;
825     return Context->getUndef(VTy);
826   }
827   
828   if (Depth == 6)        // Limit search depth.
829     return 0;
830   
831   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
832   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
833
834   Instruction *I = dyn_cast<Instruction>(V);
835   if (!I) {
836     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
837     return 0;        // Only analyze instructions.
838   }
839
840   // If there are multiple uses of this value and we aren't at the root, then
841   // we can't do any simplifications of the operands, because DemandedMask
842   // only reflects the bits demanded by *one* of the users.
843   if (Depth != 0 && !I->hasOneUse()) {
844     // Despite the fact that we can't simplify this instruction in all User's
845     // context, we can at least compute the knownzero/knownone bits, and we can
846     // do simplifications that apply to *just* the one user if we know that
847     // this instruction has a simpler value in that context.
848     if (I->getOpcode() == Instruction::And) {
849       // If either the LHS or the RHS are Zero, the result is zero.
850       ComputeMaskedBits(I->getOperand(1), DemandedMask,
851                         RHSKnownZero, RHSKnownOne, Depth+1);
852       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
853                         LHSKnownZero, LHSKnownOne, Depth+1);
854       
855       // If all of the demanded bits are known 1 on one side, return the other.
856       // These bits cannot contribute to the result of the 'and' in this
857       // context.
858       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
859           (DemandedMask & ~LHSKnownZero))
860         return I->getOperand(0);
861       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
862           (DemandedMask & ~RHSKnownZero))
863         return I->getOperand(1);
864       
865       // If all of the demanded bits in the inputs are known zeros, return zero.
866       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
867         return Context->getNullValue(VTy);
868       
869     } else if (I->getOpcode() == Instruction::Or) {
870       // We can simplify (X|Y) -> X or Y in the user's context if we know that
871       // only bits from X or Y are demanded.
872       
873       // If either the LHS or the RHS are One, the result is One.
874       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
875                         RHSKnownZero, RHSKnownOne, Depth+1);
876       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
877                         LHSKnownZero, LHSKnownOne, Depth+1);
878       
879       // If all of the demanded bits are known zero on one side, return the
880       // other.  These bits cannot contribute to the result of the 'or' in this
881       // context.
882       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
883           (DemandedMask & ~LHSKnownOne))
884         return I->getOperand(0);
885       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
886           (DemandedMask & ~RHSKnownOne))
887         return I->getOperand(1);
888       
889       // If all of the potentially set bits on one side are known to be set on
890       // the other side, just use the 'other' side.
891       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
892           (DemandedMask & (~RHSKnownZero)))
893         return I->getOperand(0);
894       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
895           (DemandedMask & (~LHSKnownZero)))
896         return I->getOperand(1);
897     }
898     
899     // Compute the KnownZero/KnownOne bits to simplify things downstream.
900     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
901     return 0;
902   }
903   
904   // If this is the root being simplified, allow it to have multiple uses,
905   // just set the DemandedMask to all bits so that we can try to simplify the
906   // operands.  This allows visitTruncInst (for example) to simplify the
907   // operand of a trunc without duplicating all the logic below.
908   if (Depth == 0 && !V->hasOneUse())
909     DemandedMask = APInt::getAllOnesValue(BitWidth);
910   
911   switch (I->getOpcode()) {
912   default:
913     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
914     break;
915   case Instruction::And:
916     // If either the LHS or the RHS are Zero, the result is zero.
917     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
918                              RHSKnownZero, RHSKnownOne, Depth+1) ||
919         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
920                              LHSKnownZero, LHSKnownOne, Depth+1))
921       return I;
922     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
923     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
924
925     // If all of the demanded bits are known 1 on one side, return the other.
926     // These bits cannot contribute to the result of the 'and'.
927     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
928         (DemandedMask & ~LHSKnownZero))
929       return I->getOperand(0);
930     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
931         (DemandedMask & ~RHSKnownZero))
932       return I->getOperand(1);
933     
934     // If all of the demanded bits in the inputs are known zeros, return zero.
935     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
936       return Context->getNullValue(VTy);
937       
938     // If the RHS is a constant, see if we can simplify it.
939     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero, Context))
940       return I;
941       
942     // Output known-1 bits are only known if set in both the LHS & RHS.
943     RHSKnownOne &= LHSKnownOne;
944     // Output known-0 are known to be clear if zero in either the LHS | RHS.
945     RHSKnownZero |= LHSKnownZero;
946     break;
947   case Instruction::Or:
948     // If either the LHS or the RHS are One, the result is One.
949     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
950                              RHSKnownZero, RHSKnownOne, Depth+1) ||
951         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
952                              LHSKnownZero, LHSKnownOne, Depth+1))
953       return I;
954     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
955     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
956     
957     // If all of the demanded bits are known zero on one side, return the other.
958     // These bits cannot contribute to the result of the 'or'.
959     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
960         (DemandedMask & ~LHSKnownOne))
961       return I->getOperand(0);
962     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
963         (DemandedMask & ~RHSKnownOne))
964       return I->getOperand(1);
965
966     // If all of the potentially set bits on one side are known to be set on
967     // the other side, just use the 'other' side.
968     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
969         (DemandedMask & (~RHSKnownZero)))
970       return I->getOperand(0);
971     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
972         (DemandedMask & (~LHSKnownZero)))
973       return I->getOperand(1);
974         
975     // If the RHS is a constant, see if we can simplify it.
976     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
977       return I;
978           
979     // Output known-0 bits are only known if clear in both the LHS & RHS.
980     RHSKnownZero &= LHSKnownZero;
981     // Output known-1 are known to be set if set in either the LHS | RHS.
982     RHSKnownOne |= LHSKnownOne;
983     break;
984   case Instruction::Xor: {
985     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
986                              RHSKnownZero, RHSKnownOne, Depth+1) ||
987         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
988                              LHSKnownZero, LHSKnownOne, Depth+1))
989       return I;
990     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
991     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
992     
993     // If all of the demanded bits are known zero on one side, return the other.
994     // These bits cannot contribute to the result of the 'xor'.
995     if ((DemandedMask & RHSKnownZero) == DemandedMask)
996       return I->getOperand(0);
997     if ((DemandedMask & LHSKnownZero) == DemandedMask)
998       return I->getOperand(1);
999     
1000     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1001     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1002                          (RHSKnownOne & LHSKnownOne);
1003     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1004     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1005                         (RHSKnownOne & LHSKnownZero);
1006     
1007     // If all of the demanded bits are known to be zero on one side or the
1008     // other, turn this into an *inclusive* or.
1009     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1010     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1011       Instruction *Or =
1012         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1013                                  I->getName());
1014       return InsertNewInstBefore(Or, *I);
1015     }
1016     
1017     // If all of the demanded bits on one side are known, and all of the set
1018     // bits on that side are also known to be set on the other side, turn this
1019     // into an AND, as we know the bits will be cleared.
1020     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1021     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1022       // all known
1023       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1024         Constant *AndC = Context->getConstantInt(~RHSKnownOne & DemandedMask);
1025         Instruction *And = 
1026           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1027         return InsertNewInstBefore(And, *I);
1028       }
1029     }
1030     
1031     // If the RHS is a constant, see if we can simplify it.
1032     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1033     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
1034       return I;
1035     
1036     RHSKnownZero = KnownZeroOut;
1037     RHSKnownOne  = KnownOneOut;
1038     break;
1039   }
1040   case Instruction::Select:
1041     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1042                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1043         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1044                              LHSKnownZero, LHSKnownOne, Depth+1))
1045       return I;
1046     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1047     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1048     
1049     // If the operands are constants, see if we can simplify them.
1050     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context) ||
1051         ShrinkDemandedConstant(I, 2, DemandedMask, Context))
1052       return I;
1053     
1054     // Only known if known in both the LHS and RHS.
1055     RHSKnownOne &= LHSKnownOne;
1056     RHSKnownZero &= LHSKnownZero;
1057     break;
1058   case Instruction::Trunc: {
1059     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1060     DemandedMask.zext(truncBf);
1061     RHSKnownZero.zext(truncBf);
1062     RHSKnownOne.zext(truncBf);
1063     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1064                              RHSKnownZero, RHSKnownOne, Depth+1))
1065       return I;
1066     DemandedMask.trunc(BitWidth);
1067     RHSKnownZero.trunc(BitWidth);
1068     RHSKnownOne.trunc(BitWidth);
1069     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1070     break;
1071   }
1072   case Instruction::BitCast:
1073     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1074       return false;  // vector->int or fp->int?
1075
1076     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1077       if (const VectorType *SrcVTy =
1078             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1079         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1080           // Don't touch a bitcast between vectors of different element counts.
1081           return false;
1082       } else
1083         // Don't touch a scalar-to-vector bitcast.
1084         return false;
1085     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1086       // Don't touch a vector-to-scalar bitcast.
1087       return false;
1088
1089     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1090                              RHSKnownZero, RHSKnownOne, Depth+1))
1091       return I;
1092     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1093     break;
1094   case Instruction::ZExt: {
1095     // Compute the bits in the result that are not present in the input.
1096     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1097     
1098     DemandedMask.trunc(SrcBitWidth);
1099     RHSKnownZero.trunc(SrcBitWidth);
1100     RHSKnownOne.trunc(SrcBitWidth);
1101     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1102                              RHSKnownZero, RHSKnownOne, Depth+1))
1103       return I;
1104     DemandedMask.zext(BitWidth);
1105     RHSKnownZero.zext(BitWidth);
1106     RHSKnownOne.zext(BitWidth);
1107     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1108     // The top bits are known to be zero.
1109     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1110     break;
1111   }
1112   case Instruction::SExt: {
1113     // Compute the bits in the result that are not present in the input.
1114     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1115     
1116     APInt InputDemandedBits = DemandedMask & 
1117                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1118
1119     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1120     // If any of the sign extended bits are demanded, we know that the sign
1121     // bit is demanded.
1122     if ((NewBits & DemandedMask) != 0)
1123       InputDemandedBits.set(SrcBitWidth-1);
1124       
1125     InputDemandedBits.trunc(SrcBitWidth);
1126     RHSKnownZero.trunc(SrcBitWidth);
1127     RHSKnownOne.trunc(SrcBitWidth);
1128     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1129                              RHSKnownZero, RHSKnownOne, Depth+1))
1130       return I;
1131     InputDemandedBits.zext(BitWidth);
1132     RHSKnownZero.zext(BitWidth);
1133     RHSKnownOne.zext(BitWidth);
1134     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1135       
1136     // If the sign bit of the input is known set or clear, then we know the
1137     // top bits of the result.
1138
1139     // If the input sign bit is known zero, or if the NewBits are not demanded
1140     // convert this into a zero extension.
1141     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1142       // Convert to ZExt cast
1143       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1144       return InsertNewInstBefore(NewCast, *I);
1145     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1146       RHSKnownOne |= NewBits;
1147     }
1148     break;
1149   }
1150   case Instruction::Add: {
1151     // Figure out what the input bits are.  If the top bits of the and result
1152     // are not demanded, then the add doesn't demand them from its input
1153     // either.
1154     unsigned NLZ = DemandedMask.countLeadingZeros();
1155       
1156     // If there is a constant on the RHS, there are a variety of xformations
1157     // we can do.
1158     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1159       // If null, this should be simplified elsewhere.  Some of the xforms here
1160       // won't work if the RHS is zero.
1161       if (RHS->isZero())
1162         break;
1163       
1164       // If the top bit of the output is demanded, demand everything from the
1165       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1166       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1167
1168       // Find information about known zero/one bits in the input.
1169       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1170                                LHSKnownZero, LHSKnownOne, Depth+1))
1171         return I;
1172
1173       // If the RHS of the add has bits set that can't affect the input, reduce
1174       // the constant.
1175       if (ShrinkDemandedConstant(I, 1, InDemandedBits, Context))
1176         return I;
1177       
1178       // Avoid excess work.
1179       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1180         break;
1181       
1182       // Turn it into OR if input bits are zero.
1183       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1184         Instruction *Or =
1185           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1186                                    I->getName());
1187         return InsertNewInstBefore(Or, *I);
1188       }
1189       
1190       // We can say something about the output known-zero and known-one bits,
1191       // depending on potential carries from the input constant and the
1192       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1193       // bits set and the RHS constant is 0x01001, then we know we have a known
1194       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1195       
1196       // To compute this, we first compute the potential carry bits.  These are
1197       // the bits which may be modified.  I'm not aware of a better way to do
1198       // this scan.
1199       const APInt &RHSVal = RHS->getValue();
1200       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1201       
1202       // Now that we know which bits have carries, compute the known-1/0 sets.
1203       
1204       // Bits are known one if they are known zero in one operand and one in the
1205       // other, and there is no input carry.
1206       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1207                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1208       
1209       // Bits are known zero if they are known zero in both operands and there
1210       // is no input carry.
1211       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1212     } else {
1213       // If the high-bits of this ADD are not demanded, then it does not demand
1214       // the high bits of its LHS or RHS.
1215       if (DemandedMask[BitWidth-1] == 0) {
1216         // Right fill the mask of bits for this ADD to demand the most
1217         // significant bit and all those below it.
1218         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1219         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1220                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1221             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1222                                  LHSKnownZero, LHSKnownOne, Depth+1))
1223           return I;
1224       }
1225     }
1226     break;
1227   }
1228   case Instruction::Sub:
1229     // If the high-bits of this SUB are not demanded, then it does not demand
1230     // the high bits of its LHS or RHS.
1231     if (DemandedMask[BitWidth-1] == 0) {
1232       // Right fill the mask of bits for this SUB to demand the most
1233       // significant bit and all those below it.
1234       uint32_t NLZ = DemandedMask.countLeadingZeros();
1235       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1236       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1237                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1238           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1239                                LHSKnownZero, LHSKnownOne, Depth+1))
1240         return I;
1241     }
1242     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1243     // the known zeros and ones.
1244     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1245     break;
1246   case Instruction::Shl:
1247     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1248       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1249       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1250       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1251                                RHSKnownZero, RHSKnownOne, Depth+1))
1252         return I;
1253       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1254       RHSKnownZero <<= ShiftAmt;
1255       RHSKnownOne  <<= ShiftAmt;
1256       // low bits known zero.
1257       if (ShiftAmt)
1258         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1259     }
1260     break;
1261   case Instruction::LShr:
1262     // For a logical shift right
1263     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1264       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1265       
1266       // Unsigned shift right.
1267       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1268       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1269                                RHSKnownZero, RHSKnownOne, Depth+1))
1270         return I;
1271       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1272       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1273       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1274       if (ShiftAmt) {
1275         // Compute the new bits that are at the top now.
1276         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1277         RHSKnownZero |= HighBits;  // high bits known zero.
1278       }
1279     }
1280     break;
1281   case Instruction::AShr:
1282     // If this is an arithmetic shift right and only the low-bit is set, we can
1283     // always convert this into a logical shr, even if the shift amount is
1284     // variable.  The low bit of the shift cannot be an input sign bit unless
1285     // the shift amount is >= the size of the datatype, which is undefined.
1286     if (DemandedMask == 1) {
1287       // Perform the logical shift right.
1288       Instruction *NewVal = BinaryOperator::CreateLShr(
1289                         I->getOperand(0), I->getOperand(1), I->getName());
1290       return InsertNewInstBefore(NewVal, *I);
1291     }    
1292
1293     // If the sign bit is the only bit demanded by this ashr, then there is no
1294     // need to do it, the shift doesn't change the high bit.
1295     if (DemandedMask.isSignBit())
1296       return I->getOperand(0);
1297     
1298     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1299       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1300       
1301       // Signed shift right.
1302       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1303       // If any of the "high bits" are demanded, we should set the sign bit as
1304       // demanded.
1305       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1306         DemandedMaskIn.set(BitWidth-1);
1307       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1308                                RHSKnownZero, RHSKnownOne, Depth+1))
1309         return I;
1310       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1311       // Compute the new bits that are at the top now.
1312       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1313       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1314       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1315         
1316       // Handle the sign bits.
1317       APInt SignBit(APInt::getSignBit(BitWidth));
1318       // Adjust to where it is now in the mask.
1319       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1320         
1321       // If the input sign bit is known to be zero, or if none of the top bits
1322       // are demanded, turn this into an unsigned shift right.
1323       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1324           (HighBits & ~DemandedMask) == HighBits) {
1325         // Perform the logical shift right.
1326         Instruction *NewVal = BinaryOperator::CreateLShr(
1327                           I->getOperand(0), SA, I->getName());
1328         return InsertNewInstBefore(NewVal, *I);
1329       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1330         RHSKnownOne |= HighBits;
1331       }
1332     }
1333     break;
1334   case Instruction::SRem:
1335     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1336       APInt RA = Rem->getValue().abs();
1337       if (RA.isPowerOf2()) {
1338         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1339           return I->getOperand(0);
1340
1341         APInt LowBits = RA - 1;
1342         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1343         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1344                                  LHSKnownZero, LHSKnownOne, Depth+1))
1345           return I;
1346
1347         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1348           LHSKnownZero |= ~LowBits;
1349
1350         KnownZero |= LHSKnownZero & DemandedMask;
1351
1352         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1353       }
1354     }
1355     break;
1356   case Instruction::URem: {
1357     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1358     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1359     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1360                              KnownZero2, KnownOne2, Depth+1) ||
1361         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1362                              KnownZero2, KnownOne2, Depth+1))
1363       return I;
1364
1365     unsigned Leaders = KnownZero2.countLeadingOnes();
1366     Leaders = std::max(Leaders,
1367                        KnownZero2.countLeadingOnes());
1368     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1369     break;
1370   }
1371   case Instruction::Call:
1372     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1373       switch (II->getIntrinsicID()) {
1374       default: break;
1375       case Intrinsic::bswap: {
1376         // If the only bits demanded come from one byte of the bswap result,
1377         // just shift the input byte into position to eliminate the bswap.
1378         unsigned NLZ = DemandedMask.countLeadingZeros();
1379         unsigned NTZ = DemandedMask.countTrailingZeros();
1380           
1381         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1382         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1383         // have 14 leading zeros, round to 8.
1384         NLZ &= ~7;
1385         NTZ &= ~7;
1386         // If we need exactly one byte, we can do this transformation.
1387         if (BitWidth-NLZ-NTZ == 8) {
1388           unsigned ResultBit = NTZ;
1389           unsigned InputBit = BitWidth-NTZ-8;
1390           
1391           // Replace this with either a left or right shift to get the byte into
1392           // the right place.
1393           Instruction *NewVal;
1394           if (InputBit > ResultBit)
1395             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1396                     Context->getConstantInt(I->getType(), InputBit-ResultBit));
1397           else
1398             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1399                     Context->getConstantInt(I->getType(), ResultBit-InputBit));
1400           NewVal->takeName(I);
1401           return InsertNewInstBefore(NewVal, *I);
1402         }
1403           
1404         // TODO: Could compute known zero/one bits based on the input.
1405         break;
1406       }
1407       }
1408     }
1409     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1410     break;
1411   }
1412   
1413   // If the client is only demanding bits that we know, return the known
1414   // constant.
1415   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1416     Constant *C = Context->getConstantInt(RHSKnownOne);
1417     if (isa<PointerType>(V->getType()))
1418       C = Context->getConstantExprIntToPtr(C, V->getType());
1419     return C;
1420   }
1421   return false;
1422 }
1423
1424
1425 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1426 /// any number of elements. DemandedElts contains the set of elements that are
1427 /// actually used by the caller.  This method analyzes which elements of the
1428 /// operand are undef and returns that information in UndefElts.
1429 ///
1430 /// If the information about demanded elements can be used to simplify the
1431 /// operation, the operation is simplified, then the resultant value is
1432 /// returned.  This returns null if no change was made.
1433 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1434                                                 APInt& UndefElts,
1435                                                 unsigned Depth) {
1436   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1437   APInt EltMask(APInt::getAllOnesValue(VWidth));
1438   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1439
1440   if (isa<UndefValue>(V)) {
1441     // If the entire vector is undefined, just return this info.
1442     UndefElts = EltMask;
1443     return 0;
1444   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1445     UndefElts = EltMask;
1446     return Context->getUndef(V->getType());
1447   }
1448
1449   UndefElts = 0;
1450   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1451     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1452     Constant *Undef = Context->getUndef(EltTy);
1453
1454     std::vector<Constant*> Elts;
1455     for (unsigned i = 0; i != VWidth; ++i)
1456       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1457         Elts.push_back(Undef);
1458         UndefElts.set(i);
1459       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1460         Elts.push_back(Undef);
1461         UndefElts.set(i);
1462       } else {                               // Otherwise, defined.
1463         Elts.push_back(CP->getOperand(i));
1464       }
1465
1466     // If we changed the constant, return it.
1467     Constant *NewCP = Context->getConstantVector(Elts);
1468     return NewCP != CP ? NewCP : 0;
1469   } else if (isa<ConstantAggregateZero>(V)) {
1470     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1471     // set to undef.
1472     
1473     // Check if this is identity. If so, return 0 since we are not simplifying
1474     // anything.
1475     if (DemandedElts == ((1ULL << VWidth) -1))
1476       return 0;
1477     
1478     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1479     Constant *Zero = Context->getNullValue(EltTy);
1480     Constant *Undef = Context->getUndef(EltTy);
1481     std::vector<Constant*> Elts;
1482     for (unsigned i = 0; i != VWidth; ++i) {
1483       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1484       Elts.push_back(Elt);
1485     }
1486     UndefElts = DemandedElts ^ EltMask;
1487     return Context->getConstantVector(Elts);
1488   }
1489   
1490   // Limit search depth.
1491   if (Depth == 10)
1492     return 0;
1493
1494   // If multiple users are using the root value, procede with
1495   // simplification conservatively assuming that all elements
1496   // are needed.
1497   if (!V->hasOneUse()) {
1498     // Quit if we find multiple users of a non-root value though.
1499     // They'll be handled when it's their turn to be visited by
1500     // the main instcombine process.
1501     if (Depth != 0)
1502       // TODO: Just compute the UndefElts information recursively.
1503       return 0;
1504
1505     // Conservatively assume that all elements are needed.
1506     DemandedElts = EltMask;
1507   }
1508   
1509   Instruction *I = dyn_cast<Instruction>(V);
1510   if (!I) return 0;        // Only analyze instructions.
1511   
1512   bool MadeChange = false;
1513   APInt UndefElts2(VWidth, 0);
1514   Value *TmpV;
1515   switch (I->getOpcode()) {
1516   default: break;
1517     
1518   case Instruction::InsertElement: {
1519     // If this is a variable index, we don't know which element it overwrites.
1520     // demand exactly the same input as we produce.
1521     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1522     if (Idx == 0) {
1523       // Note that we can't propagate undef elt info, because we don't know
1524       // which elt is getting updated.
1525       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1526                                         UndefElts2, Depth+1);
1527       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1528       break;
1529     }
1530     
1531     // If this is inserting an element that isn't demanded, remove this
1532     // insertelement.
1533     unsigned IdxNo = Idx->getZExtValue();
1534     if (IdxNo >= VWidth || !DemandedElts[IdxNo])
1535       return AddSoonDeadInstToWorklist(*I, 0);
1536     
1537     // Otherwise, the element inserted overwrites whatever was there, so the
1538     // input demanded set is simpler than the output set.
1539     APInt DemandedElts2 = DemandedElts;
1540     DemandedElts2.clear(IdxNo);
1541     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1542                                       UndefElts, Depth+1);
1543     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1544
1545     // The inserted element is defined.
1546     UndefElts.clear(IdxNo);
1547     break;
1548   }
1549   case Instruction::ShuffleVector: {
1550     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1551     uint64_t LHSVWidth =
1552       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1553     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1554     for (unsigned i = 0; i < VWidth; i++) {
1555       if (DemandedElts[i]) {
1556         unsigned MaskVal = Shuffle->getMaskValue(i);
1557         if (MaskVal != -1u) {
1558           assert(MaskVal < LHSVWidth * 2 &&
1559                  "shufflevector mask index out of range!");
1560           if (MaskVal < LHSVWidth)
1561             LeftDemanded.set(MaskVal);
1562           else
1563             RightDemanded.set(MaskVal - LHSVWidth);
1564         }
1565       }
1566     }
1567
1568     APInt UndefElts4(LHSVWidth, 0);
1569     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1570                                       UndefElts4, Depth+1);
1571     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1572
1573     APInt UndefElts3(LHSVWidth, 0);
1574     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1575                                       UndefElts3, Depth+1);
1576     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1577
1578     bool NewUndefElts = false;
1579     for (unsigned i = 0; i < VWidth; i++) {
1580       unsigned MaskVal = Shuffle->getMaskValue(i);
1581       if (MaskVal == -1u) {
1582         UndefElts.set(i);
1583       } else if (MaskVal < LHSVWidth) {
1584         if (UndefElts4[MaskVal]) {
1585           NewUndefElts = true;
1586           UndefElts.set(i);
1587         }
1588       } else {
1589         if (UndefElts3[MaskVal - LHSVWidth]) {
1590           NewUndefElts = true;
1591           UndefElts.set(i);
1592         }
1593       }
1594     }
1595
1596     if (NewUndefElts) {
1597       // Add additional discovered undefs.
1598       std::vector<Constant*> Elts;
1599       for (unsigned i = 0; i < VWidth; ++i) {
1600         if (UndefElts[i])
1601           Elts.push_back(Context->getUndef(Type::Int32Ty));
1602         else
1603           Elts.push_back(Context->getConstantInt(Type::Int32Ty,
1604                                           Shuffle->getMaskValue(i)));
1605       }
1606       I->setOperand(2, Context->getConstantVector(Elts));
1607       MadeChange = true;
1608     }
1609     break;
1610   }
1611   case Instruction::BitCast: {
1612     // Vector->vector casts only.
1613     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1614     if (!VTy) break;
1615     unsigned InVWidth = VTy->getNumElements();
1616     APInt InputDemandedElts(InVWidth, 0);
1617     unsigned Ratio;
1618
1619     if (VWidth == InVWidth) {
1620       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1621       // elements as are demanded of us.
1622       Ratio = 1;
1623       InputDemandedElts = DemandedElts;
1624     } else if (VWidth > InVWidth) {
1625       // Untested so far.
1626       break;
1627       
1628       // If there are more elements in the result than there are in the source,
1629       // then an input element is live if any of the corresponding output
1630       // elements are live.
1631       Ratio = VWidth/InVWidth;
1632       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1633         if (DemandedElts[OutIdx])
1634           InputDemandedElts.set(OutIdx/Ratio);
1635       }
1636     } else {
1637       // Untested so far.
1638       break;
1639       
1640       // If there are more elements in the source than there are in the result,
1641       // then an input element is live if the corresponding output element is
1642       // live.
1643       Ratio = InVWidth/VWidth;
1644       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1645         if (DemandedElts[InIdx/Ratio])
1646           InputDemandedElts.set(InIdx);
1647     }
1648     
1649     // div/rem demand all inputs, because they don't want divide by zero.
1650     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1651                                       UndefElts2, Depth+1);
1652     if (TmpV) {
1653       I->setOperand(0, TmpV);
1654       MadeChange = true;
1655     }
1656     
1657     UndefElts = UndefElts2;
1658     if (VWidth > InVWidth) {
1659       llvm_unreachable("Unimp");
1660       // If there are more elements in the result than there are in the source,
1661       // then an output element is undef if the corresponding input element is
1662       // undef.
1663       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1664         if (UndefElts2[OutIdx/Ratio])
1665           UndefElts.set(OutIdx);
1666     } else if (VWidth < InVWidth) {
1667       llvm_unreachable("Unimp");
1668       // If there are more elements in the source than there are in the result,
1669       // then a result element is undef if all of the corresponding input
1670       // elements are undef.
1671       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1672       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1673         if (!UndefElts2[InIdx])            // Not undef?
1674           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1675     }
1676     break;
1677   }
1678   case Instruction::And:
1679   case Instruction::Or:
1680   case Instruction::Xor:
1681   case Instruction::Add:
1682   case Instruction::Sub:
1683   case Instruction::Mul:
1684     // div/rem demand all inputs, because they don't want divide by zero.
1685     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1686                                       UndefElts, Depth+1);
1687     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1688     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1689                                       UndefElts2, Depth+1);
1690     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1691       
1692     // Output elements are undefined if both are undefined.  Consider things
1693     // like undef&0.  The result is known zero, not undef.
1694     UndefElts &= UndefElts2;
1695     break;
1696     
1697   case Instruction::Call: {
1698     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1699     if (!II) break;
1700     switch (II->getIntrinsicID()) {
1701     default: break;
1702       
1703     // Binary vector operations that work column-wise.  A dest element is a
1704     // function of the corresponding input elements from the two inputs.
1705     case Intrinsic::x86_sse_sub_ss:
1706     case Intrinsic::x86_sse_mul_ss:
1707     case Intrinsic::x86_sse_min_ss:
1708     case Intrinsic::x86_sse_max_ss:
1709     case Intrinsic::x86_sse2_sub_sd:
1710     case Intrinsic::x86_sse2_mul_sd:
1711     case Intrinsic::x86_sse2_min_sd:
1712     case Intrinsic::x86_sse2_max_sd:
1713       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1714                                         UndefElts, Depth+1);
1715       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1716       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1717                                         UndefElts2, Depth+1);
1718       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1719
1720       // If only the low elt is demanded and this is a scalarizable intrinsic,
1721       // scalarize it now.
1722       if (DemandedElts == 1) {
1723         switch (II->getIntrinsicID()) {
1724         default: break;
1725         case Intrinsic::x86_sse_sub_ss:
1726         case Intrinsic::x86_sse_mul_ss:
1727         case Intrinsic::x86_sse2_sub_sd:
1728         case Intrinsic::x86_sse2_mul_sd:
1729           // TODO: Lower MIN/MAX/ABS/etc
1730           Value *LHS = II->getOperand(1);
1731           Value *RHS = II->getOperand(2);
1732           // Extract the element as scalars.
1733           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 
1734             Context->getConstantInt(Type::Int32Ty, 0U, false), "tmp"), *II);
1735           RHS = InsertNewInstBefore(new ExtractElementInst(RHS,
1736             Context->getConstantInt(Type::Int32Ty, 0U, false), "tmp"), *II);
1737           
1738           switch (II->getIntrinsicID()) {
1739           default: llvm_unreachable("Case stmts out of sync!");
1740           case Intrinsic::x86_sse_sub_ss:
1741           case Intrinsic::x86_sse2_sub_sd:
1742             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1743                                                         II->getName()), *II);
1744             break;
1745           case Intrinsic::x86_sse_mul_ss:
1746           case Intrinsic::x86_sse2_mul_sd:
1747             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1748                                                          II->getName()), *II);
1749             break;
1750           }
1751           
1752           Instruction *New =
1753             InsertElementInst::Create(
1754               Context->getUndef(II->getType()), TmpV,
1755               Context->getConstantInt(Type::Int32Ty, 0U, false), II->getName());
1756           InsertNewInstBefore(New, *II);
1757           AddSoonDeadInstToWorklist(*II, 0);
1758           return New;
1759         }            
1760       }
1761         
1762       // Output elements are undefined if both are undefined.  Consider things
1763       // like undef&0.  The result is known zero, not undef.
1764       UndefElts &= UndefElts2;
1765       break;
1766     }
1767     break;
1768   }
1769   }
1770   return MadeChange ? I : 0;
1771 }
1772
1773
1774 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1775 /// function is designed to check a chain of associative operators for a
1776 /// potential to apply a certain optimization.  Since the optimization may be
1777 /// applicable if the expression was reassociated, this checks the chain, then
1778 /// reassociates the expression as necessary to expose the optimization
1779 /// opportunity.  This makes use of a special Functor, which must define
1780 /// 'shouldApply' and 'apply' methods.
1781 ///
1782 template<typename Functor>
1783 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F,
1784                                    LLVMContext *Context) {
1785   unsigned Opcode = Root.getOpcode();
1786   Value *LHS = Root.getOperand(0);
1787
1788   // Quick check, see if the immediate LHS matches...
1789   if (F.shouldApply(LHS))
1790     return F.apply(Root);
1791
1792   // Otherwise, if the LHS is not of the same opcode as the root, return.
1793   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1794   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1795     // Should we apply this transform to the RHS?
1796     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1797
1798     // If not to the RHS, check to see if we should apply to the LHS...
1799     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1800       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1801       ShouldApply = true;
1802     }
1803
1804     // If the functor wants to apply the optimization to the RHS of LHSI,
1805     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1806     if (ShouldApply) {
1807       // Now all of the instructions are in the current basic block, go ahead
1808       // and perform the reassociation.
1809       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1810
1811       // First move the selected RHS to the LHS of the root...
1812       Root.setOperand(0, LHSI->getOperand(1));
1813
1814       // Make what used to be the LHS of the root be the user of the root...
1815       Value *ExtraOperand = TmpLHSI->getOperand(1);
1816       if (&Root == TmpLHSI) {
1817         Root.replaceAllUsesWith(Context->getNullValue(TmpLHSI->getType()));
1818         return 0;
1819       }
1820       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1821       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1822       BasicBlock::iterator ARI = &Root; ++ARI;
1823       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1824       ARI = Root;
1825
1826       // Now propagate the ExtraOperand down the chain of instructions until we
1827       // get to LHSI.
1828       while (TmpLHSI != LHSI) {
1829         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1830         // Move the instruction to immediately before the chain we are
1831         // constructing to avoid breaking dominance properties.
1832         NextLHSI->moveBefore(ARI);
1833         ARI = NextLHSI;
1834
1835         Value *NextOp = NextLHSI->getOperand(1);
1836         NextLHSI->setOperand(1, ExtraOperand);
1837         TmpLHSI = NextLHSI;
1838         ExtraOperand = NextOp;
1839       }
1840
1841       // Now that the instructions are reassociated, have the functor perform
1842       // the transformation...
1843       return F.apply(Root);
1844     }
1845
1846     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1847   }
1848   return 0;
1849 }
1850
1851 namespace {
1852
1853 // AddRHS - Implements: X + X --> X << 1
1854 struct AddRHS {
1855   Value *RHS;
1856   LLVMContext *Context;
1857   AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
1858   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1859   Instruction *apply(BinaryOperator &Add) const {
1860     return BinaryOperator::CreateShl(Add.getOperand(0),
1861                                      Context->getConstantInt(Add.getType(), 1));
1862   }
1863 };
1864
1865 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1866 //                 iff C1&C2 == 0
1867 struct AddMaskingAnd {
1868   Constant *C2;
1869   LLVMContext *Context;
1870   AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
1871   bool shouldApply(Value *LHS) const {
1872     ConstantInt *C1;
1873     return match(LHS, m_And(m_Value(), m_ConstantInt(C1)), *Context) &&
1874            Context->getConstantExprAnd(C1, C2)->isNullValue();
1875   }
1876   Instruction *apply(BinaryOperator &Add) const {
1877     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1878   }
1879 };
1880
1881 }
1882
1883 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1884                                              InstCombiner *IC) {
1885   LLVMContext *Context = IC->getContext();
1886   
1887   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1888     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1889   }
1890
1891   // Figure out if the constant is the left or the right argument.
1892   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1893   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1894
1895   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1896     if (ConstIsRHS)
1897       return Context->getConstantExpr(I.getOpcode(), SOC, ConstOperand);
1898     return Context->getConstantExpr(I.getOpcode(), ConstOperand, SOC);
1899   }
1900
1901   Value *Op0 = SO, *Op1 = ConstOperand;
1902   if (!ConstIsRHS)
1903     std::swap(Op0, Op1);
1904   Instruction *New;
1905   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1906     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1907   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1908     New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1909                           Op0, Op1, SO->getName()+".cmp");
1910   else {
1911     llvm_unreachable("Unknown binary instruction type!");
1912   }
1913   return IC->InsertNewInstBefore(New, I);
1914 }
1915
1916 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1917 // constant as the other operand, try to fold the binary operator into the
1918 // select arguments.  This also works for Cast instructions, which obviously do
1919 // not have a second operand.
1920 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1921                                      InstCombiner *IC) {
1922   // Don't modify shared select instructions
1923   if (!SI->hasOneUse()) return 0;
1924   Value *TV = SI->getOperand(1);
1925   Value *FV = SI->getOperand(2);
1926
1927   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1928     // Bool selects with constant operands can be folded to logical ops.
1929     if (SI->getType() == Type::Int1Ty) return 0;
1930
1931     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1932     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1933
1934     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1935                               SelectFalseVal);
1936   }
1937   return 0;
1938 }
1939
1940
1941 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1942 /// node as operand #0, see if we can fold the instruction into the PHI (which
1943 /// is only possible if all operands to the PHI are constants).
1944 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1945   PHINode *PN = cast<PHINode>(I.getOperand(0));
1946   unsigned NumPHIValues = PN->getNumIncomingValues();
1947   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1948
1949   // Check to see if all of the operands of the PHI are constants.  If there is
1950   // one non-constant value, remember the BB it is.  If there is more than one
1951   // or if *it* is a PHI, bail out.
1952   BasicBlock *NonConstBB = 0;
1953   for (unsigned i = 0; i != NumPHIValues; ++i)
1954     if (!isa<Constant>(PN->getIncomingValue(i))) {
1955       if (NonConstBB) return 0;  // More than one non-const value.
1956       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1957       NonConstBB = PN->getIncomingBlock(i);
1958       
1959       // If the incoming non-constant value is in I's block, we have an infinite
1960       // loop.
1961       if (NonConstBB == I.getParent())
1962         return 0;
1963     }
1964   
1965   // If there is exactly one non-constant value, we can insert a copy of the
1966   // operation in that block.  However, if this is a critical edge, we would be
1967   // inserting the computation one some other paths (e.g. inside a loop).  Only
1968   // do this if the pred block is unconditionally branching into the phi block.
1969   if (NonConstBB) {
1970     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1971     if (!BI || !BI->isUnconditional()) return 0;
1972   }
1973
1974   // Okay, we can do the transformation: create the new PHI node.
1975   PHINode *NewPN = PHINode::Create(I.getType(), "");
1976   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1977   InsertNewInstBefore(NewPN, *PN);
1978   NewPN->takeName(PN);
1979
1980   // Next, add all of the operands to the PHI.
1981   if (I.getNumOperands() == 2) {
1982     Constant *C = cast<Constant>(I.getOperand(1));
1983     for (unsigned i = 0; i != NumPHIValues; ++i) {
1984       Value *InV = 0;
1985       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1986         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1987           InV = Context->getConstantExprCompare(CI->getPredicate(), InC, C);
1988         else
1989           InV = Context->getConstantExpr(I.getOpcode(), InC, C);
1990       } else {
1991         assert(PN->getIncomingBlock(i) == NonConstBB);
1992         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1993           InV = BinaryOperator::Create(BO->getOpcode(),
1994                                        PN->getIncomingValue(i), C, "phitmp",
1995                                        NonConstBB->getTerminator());
1996         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1997           InV = CmpInst::Create(*Context, CI->getOpcode(), 
1998                                 CI->getPredicate(),
1999                                 PN->getIncomingValue(i), C, "phitmp",
2000                                 NonConstBB->getTerminator());
2001         else
2002           llvm_unreachable("Unknown binop!");
2003         
2004         AddToWorkList(cast<Instruction>(InV));
2005       }
2006       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2007     }
2008   } else { 
2009     CastInst *CI = cast<CastInst>(&I);
2010     const Type *RetTy = CI->getType();
2011     for (unsigned i = 0; i != NumPHIValues; ++i) {
2012       Value *InV;
2013       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2014         InV = Context->getConstantExprCast(CI->getOpcode(), InC, RetTy);
2015       } else {
2016         assert(PN->getIncomingBlock(i) == NonConstBB);
2017         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2018                                I.getType(), "phitmp", 
2019                                NonConstBB->getTerminator());
2020         AddToWorkList(cast<Instruction>(InV));
2021       }
2022       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2023     }
2024   }
2025   return ReplaceInstUsesWith(I, NewPN);
2026 }
2027
2028
2029 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2030 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2031 /// This basically requires proving that the add in the original type would not
2032 /// overflow to change the sign bit or have a carry out.
2033 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2034   // There are different heuristics we can use for this.  Here are some simple
2035   // ones.
2036   
2037   // Add has the property that adding any two 2's complement numbers can only 
2038   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2039   // have at least two sign bits, we know that the addition of the two values will
2040   // sign extend fine.
2041   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2042     return true;
2043   
2044   
2045   // If one of the operands only has one non-zero bit, and if the other operand
2046   // has a known-zero bit in a more significant place than it (not including the
2047   // sign bit) the ripple may go up to and fill the zero, but won't change the
2048   // sign.  For example, (X & ~4) + 1.
2049   
2050   // TODO: Implement.
2051   
2052   return false;
2053 }
2054
2055
2056 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2057   bool Changed = SimplifyCommutative(I);
2058   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2059
2060   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2061     // X + undef -> undef
2062     if (isa<UndefValue>(RHS))
2063       return ReplaceInstUsesWith(I, RHS);
2064
2065     // X + 0 --> X
2066     if (RHSC->isNullValue())
2067       return ReplaceInstUsesWith(I, LHS);
2068
2069     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2070       // X + (signbit) --> X ^ signbit
2071       const APInt& Val = CI->getValue();
2072       uint32_t BitWidth = Val.getBitWidth();
2073       if (Val == APInt::getSignBit(BitWidth))
2074         return BinaryOperator::CreateXor(LHS, RHS);
2075       
2076       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2077       // (X & 254)+1 -> (X&254)|1
2078       if (SimplifyDemandedInstructionBits(I))
2079         return &I;
2080
2081       // zext(bool) + C -> bool ? C + 1 : C
2082       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2083         if (ZI->getSrcTy() == Type::Int1Ty)
2084           return SelectInst::Create(ZI->getOperand(0), AddOne(CI, Context), CI);
2085     }
2086
2087     if (isa<PHINode>(LHS))
2088       if (Instruction *NV = FoldOpIntoPhi(I))
2089         return NV;
2090     
2091     ConstantInt *XorRHS = 0;
2092     Value *XorLHS = 0;
2093     if (isa<ConstantInt>(RHSC) &&
2094         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)), *Context)) {
2095       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2096       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2097       
2098       uint32_t Size = TySizeBits / 2;
2099       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2100       APInt CFF80Val(-C0080Val);
2101       do {
2102         if (TySizeBits > Size) {
2103           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2104           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2105           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2106               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2107             // This is a sign extend if the top bits are known zero.
2108             if (!MaskedValueIsZero(XorLHS, 
2109                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2110               Size = 0;  // Not a sign ext, but can't be any others either.
2111             break;
2112           }
2113         }
2114         Size >>= 1;
2115         C0080Val = APIntOps::lshr(C0080Val, Size);
2116         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2117       } while (Size >= 1);
2118       
2119       // FIXME: This shouldn't be necessary. When the backends can handle types
2120       // with funny bit widths then this switch statement should be removed. It
2121       // is just here to get the size of the "middle" type back up to something
2122       // that the back ends can handle.
2123       const Type *MiddleType = 0;
2124       switch (Size) {
2125         default: break;
2126         case 32: MiddleType = Type::Int32Ty; break;
2127         case 16: MiddleType = Type::Int16Ty; break;
2128         case  8: MiddleType = Type::Int8Ty; break;
2129       }
2130       if (MiddleType) {
2131         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2132         InsertNewInstBefore(NewTrunc, I);
2133         return new SExtInst(NewTrunc, I.getType(), I.getName());
2134       }
2135     }
2136   }
2137
2138   if (I.getType() == Type::Int1Ty)
2139     return BinaryOperator::CreateXor(LHS, RHS);
2140
2141   // X + X --> X << 1
2142   if (I.getType()->isInteger()) {
2143     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2144       return Result;
2145
2146     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2147       if (RHSI->getOpcode() == Instruction::Sub)
2148         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2149           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2150     }
2151     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2152       if (LHSI->getOpcode() == Instruction::Sub)
2153         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2154           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2155     }
2156   }
2157
2158   // -A + B  -->  B - A
2159   // -A + -B  -->  -(A + B)
2160   if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
2161     if (LHS->getType()->isIntOrIntVector()) {
2162       if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
2163         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2164         InsertNewInstBefore(NewAdd, I);
2165         return BinaryOperator::CreateNeg(*Context, NewAdd);
2166       }
2167     }
2168     
2169     return BinaryOperator::CreateSub(RHS, LHSV);
2170   }
2171
2172   // A + -B  -->  A - B
2173   if (!isa<Constant>(RHS))
2174     if (Value *V = dyn_castNegVal(RHS, Context))
2175       return BinaryOperator::CreateSub(LHS, V);
2176
2177
2178   ConstantInt *C2;
2179   if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
2180     if (X == RHS)   // X*C + X --> X * (C+1)
2181       return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
2182
2183     // X*C1 + X*C2 --> X * (C1+C2)
2184     ConstantInt *C1;
2185     if (X == dyn_castFoldableMul(RHS, C1, Context))
2186       return BinaryOperator::CreateMul(X, Context->getConstantExprAdd(C1, C2));
2187   }
2188
2189   // X + X*C --> X * (C+1)
2190   if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2191     return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
2192
2193   // X + ~X --> -1   since   ~X = -X-1
2194   if (dyn_castNotVal(LHS, Context) == RHS ||
2195       dyn_castNotVal(RHS, Context) == LHS)
2196     return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
2197   
2198
2199   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2200   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)), *Context))
2201     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
2202       return R;
2203   
2204   // A+B --> A|B iff A and B have no bits set in common.
2205   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2206     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2207     APInt LHSKnownOne(IT->getBitWidth(), 0);
2208     APInt LHSKnownZero(IT->getBitWidth(), 0);
2209     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2210     if (LHSKnownZero != 0) {
2211       APInt RHSKnownOne(IT->getBitWidth(), 0);
2212       APInt RHSKnownZero(IT->getBitWidth(), 0);
2213       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2214       
2215       // No bits in common -> bitwise or.
2216       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2217         return BinaryOperator::CreateOr(LHS, RHS);
2218     }
2219   }
2220
2221   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2222   if (I.getType()->isIntOrIntVector()) {
2223     Value *W, *X, *Y, *Z;
2224     if (match(LHS, m_Mul(m_Value(W), m_Value(X)), *Context) &&
2225         match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
2226       if (W != Y) {
2227         if (W == Z) {
2228           std::swap(Y, Z);
2229         } else if (Y == X) {
2230           std::swap(W, X);
2231         } else if (X == Z) {
2232           std::swap(Y, Z);
2233           std::swap(W, X);
2234         }
2235       }
2236
2237       if (W == Y) {
2238         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2239                                                             LHS->getName()), I);
2240         return BinaryOperator::CreateMul(W, NewAdd);
2241       }
2242     }
2243   }
2244
2245   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2246     Value *X = 0;
2247     if (match(LHS, m_Not(m_Value(X)), *Context))    // ~X + C --> (C-1) - X
2248       return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
2249
2250     // (X & FF00) + xx00  -> (X+xx00) & FF00
2251     if (LHS->hasOneUse() &&
2252         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
2253       Constant *Anded = Context->getConstantExprAnd(CRHS, C2);
2254       if (Anded == CRHS) {
2255         // See if all bits from the first bit set in the Add RHS up are included
2256         // in the mask.  First, get the rightmost bit.
2257         const APInt& AddRHSV = CRHS->getValue();
2258
2259         // Form a mask of all bits from the lowest bit added through the top.
2260         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2261
2262         // See if the and mask includes all of these bits.
2263         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2264
2265         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2266           // Okay, the xform is safe.  Insert the new add pronto.
2267           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2268                                                             LHS->getName()), I);
2269           return BinaryOperator::CreateAnd(NewAdd, C2);
2270         }
2271       }
2272     }
2273
2274     // Try to fold constant add into select arguments.
2275     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2276       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2277         return R;
2278   }
2279
2280   // add (select X 0 (sub n A)) A  -->  select X A n
2281   {
2282     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2283     Value *A = RHS;
2284     if (!SI) {
2285       SI = dyn_cast<SelectInst>(RHS);
2286       A = LHS;
2287     }
2288     if (SI && SI->hasOneUse()) {
2289       Value *TV = SI->getTrueValue();
2290       Value *FV = SI->getFalseValue();
2291       Value *N;
2292
2293       // Can we fold the add into the argument of the select?
2294       // We check both true and false select arguments for a matching subtract.
2295       if (match(FV, m_Zero(), *Context) &&
2296           match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2297         // Fold the add into the true select value.
2298         return SelectInst::Create(SI->getCondition(), N, A);
2299       if (match(TV, m_Zero(), *Context) &&
2300           match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2301         // Fold the add into the false select value.
2302         return SelectInst::Create(SI->getCondition(), A, N);
2303     }
2304   }
2305
2306   // Check for (add (sext x), y), see if we can merge this into an
2307   // integer add followed by a sext.
2308   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2309     // (add (sext x), cst) --> (sext (add x, cst'))
2310     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2311       Constant *CI = 
2312         Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
2313       if (LHSConv->hasOneUse() &&
2314           Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
2315           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2316         // Insert the new, smaller add.
2317         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2318                                                         CI, "addconv");
2319         InsertNewInstBefore(NewAdd, I);
2320         return new SExtInst(NewAdd, I.getType());
2321       }
2322     }
2323     
2324     // (add (sext x), (sext y)) --> (sext (add int x, y))
2325     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2326       // Only do this if x/y have the same type, if at last one of them has a
2327       // single use (so we don't increase the number of sexts), and if the
2328       // integer add will not overflow.
2329       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2330           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2331           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2332                                    RHSConv->getOperand(0))) {
2333         // Insert the new integer add.
2334         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2335                                                         RHSConv->getOperand(0),
2336                                                         "addconv");
2337         InsertNewInstBefore(NewAdd, I);
2338         return new SExtInst(NewAdd, I.getType());
2339       }
2340     }
2341   }
2342
2343   return Changed ? &I : 0;
2344 }
2345
2346 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2347   bool Changed = SimplifyCommutative(I);
2348   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2349
2350   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2351     // X + 0 --> X
2352     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2353       if (CFP->isExactlyValue(Context->getConstantFPNegativeZero
2354                               (I.getType())->getValueAPF()))
2355         return ReplaceInstUsesWith(I, LHS);
2356     }
2357
2358     if (isa<PHINode>(LHS))
2359       if (Instruction *NV = FoldOpIntoPhi(I))
2360         return NV;
2361   }
2362
2363   // -A + B  -->  B - A
2364   // -A + -B  -->  -(A + B)
2365   if (Value *LHSV = dyn_castFNegVal(LHS, Context))
2366     return BinaryOperator::CreateFSub(RHS, LHSV);
2367
2368   // A + -B  -->  A - B
2369   if (!isa<Constant>(RHS))
2370     if (Value *V = dyn_castFNegVal(RHS, Context))
2371       return BinaryOperator::CreateFSub(LHS, V);
2372
2373   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2374   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2375     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2376       return ReplaceInstUsesWith(I, LHS);
2377
2378   // Check for (add double (sitofp x), y), see if we can merge this into an
2379   // integer add followed by a promotion.
2380   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2381     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2382     // ... if the constant fits in the integer value.  This is useful for things
2383     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2384     // requires a constant pool load, and generally allows the add to be better
2385     // instcombined.
2386     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2387       Constant *CI = 
2388       Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
2389       if (LHSConv->hasOneUse() &&
2390           Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
2391           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2392         // Insert the new integer add.
2393         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2394                                                         CI, "addconv");
2395         InsertNewInstBefore(NewAdd, I);
2396         return new SIToFPInst(NewAdd, I.getType());
2397       }
2398     }
2399     
2400     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2401     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2402       // Only do this if x/y have the same type, if at last one of them has a
2403       // single use (so we don't increase the number of int->fp conversions),
2404       // and if the integer add will not overflow.
2405       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2406           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2407           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2408                                    RHSConv->getOperand(0))) {
2409         // Insert the new integer add.
2410         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2411                                                         RHSConv->getOperand(0),
2412                                                         "addconv");
2413         InsertNewInstBefore(NewAdd, I);
2414         return new SIToFPInst(NewAdd, I.getType());
2415       }
2416     }
2417   }
2418   
2419   return Changed ? &I : 0;
2420 }
2421
2422 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2423   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2424
2425   if (Op0 == Op1)                        // sub X, X  -> 0
2426     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2427
2428   // If this is a 'B = x-(-A)', change to B = x+A...
2429   if (Value *V = dyn_castNegVal(Op1, Context))
2430     return BinaryOperator::CreateAdd(Op0, V);
2431
2432   if (isa<UndefValue>(Op0))
2433     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2434   if (isa<UndefValue>(Op1))
2435     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2436
2437   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2438     // Replace (-1 - A) with (~A)...
2439     if (C->isAllOnesValue())
2440       return BinaryOperator::CreateNot(*Context, Op1);
2441
2442     // C - ~X == X + (1+C)
2443     Value *X = 0;
2444     if (match(Op1, m_Not(m_Value(X)), *Context))
2445       return BinaryOperator::CreateAdd(X, AddOne(C, Context));
2446
2447     // -(X >>u 31) -> (X >>s 31)
2448     // -(X >>s 31) -> (X >>u 31)
2449     if (C->isZero()) {
2450       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2451         if (SI->getOpcode() == Instruction::LShr) {
2452           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2453             // Check to see if we are shifting out everything but the sign bit.
2454             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2455                 SI->getType()->getPrimitiveSizeInBits()-1) {
2456               // Ok, the transformation is safe.  Insert AShr.
2457               return BinaryOperator::Create(Instruction::AShr, 
2458                                           SI->getOperand(0), CU, SI->getName());
2459             }
2460           }
2461         }
2462         else if (SI->getOpcode() == Instruction::AShr) {
2463           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2464             // Check to see if we are shifting out everything but the sign bit.
2465             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2466                 SI->getType()->getPrimitiveSizeInBits()-1) {
2467               // Ok, the transformation is safe.  Insert LShr. 
2468               return BinaryOperator::CreateLShr(
2469                                           SI->getOperand(0), CU, SI->getName());
2470             }
2471           }
2472         }
2473       }
2474     }
2475
2476     // Try to fold constant sub into select arguments.
2477     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2478       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2479         return R;
2480
2481     // C - zext(bool) -> bool ? C - 1 : C
2482     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2483       if (ZI->getSrcTy() == Type::Int1Ty)
2484         return SelectInst::Create(ZI->getOperand(0), SubOne(C, Context), C);
2485   }
2486
2487   if (I.getType() == Type::Int1Ty)
2488     return BinaryOperator::CreateXor(Op0, Op1);
2489
2490   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2491     if (Op1I->getOpcode() == Instruction::Add) {
2492       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2493         return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(1),
2494                                          I.getName());
2495       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2496         return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(0), 
2497                                          I.getName());
2498       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2499         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2500           // C1-(X+C2) --> (C1-C2)-X
2501           return BinaryOperator::CreateSub(
2502             Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
2503       }
2504     }
2505
2506     if (Op1I->hasOneUse()) {
2507       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2508       // is not used by anyone else...
2509       //
2510       if (Op1I->getOpcode() == Instruction::Sub) {
2511         // Swap the two operands of the subexpr...
2512         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2513         Op1I->setOperand(0, IIOp1);
2514         Op1I->setOperand(1, IIOp0);
2515
2516         // Create the new top level add instruction...
2517         return BinaryOperator::CreateAdd(Op0, Op1);
2518       }
2519
2520       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2521       //
2522       if (Op1I->getOpcode() == Instruction::And &&
2523           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2524         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2525
2526         Value *NewNot =
2527           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, 
2528                                                         OtherOp, "B.not"), I);
2529         return BinaryOperator::CreateAnd(Op0, NewNot);
2530       }
2531
2532       // 0 - (X sdiv C)  -> (X sdiv -C)
2533       if (Op1I->getOpcode() == Instruction::SDiv)
2534         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2535           if (CSI->isZero())
2536             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2537               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2538                                           Context->getConstantExprNeg(DivRHS));
2539
2540       // X - X*C --> X * (1-C)
2541       ConstantInt *C2 = 0;
2542       if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2543         Constant *CP1 = 
2544           Context->getConstantExprSub(Context->getConstantInt(I.getType(), 1),
2545                                              C2);
2546         return BinaryOperator::CreateMul(Op0, CP1);
2547       }
2548     }
2549   }
2550
2551   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2552     if (Op0I->getOpcode() == Instruction::Add) {
2553       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2554         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2555       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2556         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2557     } else if (Op0I->getOpcode() == Instruction::Sub) {
2558       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2559         return BinaryOperator::CreateNeg(*Context, Op0I->getOperand(1),
2560                                          I.getName());
2561     }
2562   }
2563
2564   ConstantInt *C1;
2565   if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
2566     if (X == Op1)  // X*C - X --> X * (C-1)
2567       return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
2568
2569     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2570     if (X == dyn_castFoldableMul(Op1, C2, Context))
2571       return BinaryOperator::CreateMul(X, Context->getConstantExprSub(C1, C2));
2572   }
2573   return 0;
2574 }
2575
2576 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2577   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2578
2579   // If this is a 'B = x-(-A)', change to B = x+A...
2580   if (Value *V = dyn_castFNegVal(Op1, Context))
2581     return BinaryOperator::CreateFAdd(Op0, V);
2582
2583   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2584     if (Op1I->getOpcode() == Instruction::FAdd) {
2585       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2586         return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(1),
2587                                           I.getName());
2588       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2589         return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(0),
2590                                           I.getName());
2591     }
2592   }
2593
2594   return 0;
2595 }
2596
2597 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2598 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2599 /// TrueIfSigned if the result of the comparison is true when the input value is
2600 /// signed.
2601 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2602                            bool &TrueIfSigned) {
2603   switch (pred) {
2604   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2605     TrueIfSigned = true;
2606     return RHS->isZero();
2607   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2608     TrueIfSigned = true;
2609     return RHS->isAllOnesValue();
2610   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2611     TrueIfSigned = false;
2612     return RHS->isAllOnesValue();
2613   case ICmpInst::ICMP_UGT:
2614     // True if LHS u> RHS and RHS == high-bit-mask - 1
2615     TrueIfSigned = true;
2616     return RHS->getValue() ==
2617       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2618   case ICmpInst::ICMP_UGE: 
2619     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2620     TrueIfSigned = true;
2621     return RHS->getValue().isSignBit();
2622   default:
2623     return false;
2624   }
2625 }
2626
2627 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2628   bool Changed = SimplifyCommutative(I);
2629   Value *Op0 = I.getOperand(0);
2630
2631   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2632     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2633
2634   // Simplify mul instructions with a constant RHS...
2635   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2636     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2637
2638       // ((X << C1)*C2) == (X * (C2 << C1))
2639       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2640         if (SI->getOpcode() == Instruction::Shl)
2641           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2642             return BinaryOperator::CreateMul(SI->getOperand(0),
2643                                         Context->getConstantExprShl(CI, ShOp));
2644
2645       if (CI->isZero())
2646         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2647       if (CI->equalsInt(1))                  // X * 1  == X
2648         return ReplaceInstUsesWith(I, Op0);
2649       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2650         return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2651
2652       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2653       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2654         return BinaryOperator::CreateShl(Op0,
2655                  Context->getConstantInt(Op0->getType(), Val.logBase2()));
2656       }
2657     } else if (isa<VectorType>(Op1->getType())) {
2658       if (Op1->isNullValue())
2659         return ReplaceInstUsesWith(I, Op1);
2660
2661       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2662         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2663           return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2664
2665         // As above, vector X*splat(1.0) -> X in all defined cases.
2666         if (Constant *Splat = Op1V->getSplatValue()) {
2667           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2668             if (CI->equalsInt(1))
2669               return ReplaceInstUsesWith(I, Op0);
2670         }
2671       }
2672     }
2673     
2674     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2675       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2676           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2677         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2678         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2679                                                      Op1, "tmp");
2680         InsertNewInstBefore(Add, I);
2681         Value *C1C2 = Context->getConstantExprMul(Op1, 
2682                                            cast<Constant>(Op0I->getOperand(1)));
2683         return BinaryOperator::CreateAdd(Add, C1C2);
2684         
2685       }
2686
2687     // Try to fold constant mul into select arguments.
2688     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2689       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2690         return R;
2691
2692     if (isa<PHINode>(Op0))
2693       if (Instruction *NV = FoldOpIntoPhi(I))
2694         return NV;
2695   }
2696
2697   if (Value *Op0v = dyn_castNegVal(Op0, Context))     // -X * -Y = X*Y
2698     if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
2699       return BinaryOperator::CreateMul(Op0v, Op1v);
2700
2701   // (X / Y) *  Y = X - (X % Y)
2702   // (X / Y) * -Y = (X % Y) - X
2703   {
2704     Value *Op1 = I.getOperand(1);
2705     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2706     if (!BO ||
2707         (BO->getOpcode() != Instruction::UDiv && 
2708          BO->getOpcode() != Instruction::SDiv)) {
2709       Op1 = Op0;
2710       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2711     }
2712     Value *Neg = dyn_castNegVal(Op1, Context);
2713     if (BO && BO->hasOneUse() &&
2714         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2715         (BO->getOpcode() == Instruction::UDiv ||
2716          BO->getOpcode() == Instruction::SDiv)) {
2717       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2718
2719       Instruction *Rem;
2720       if (BO->getOpcode() == Instruction::UDiv)
2721         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2722       else
2723         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2724
2725       InsertNewInstBefore(Rem, I);
2726       Rem->takeName(BO);
2727
2728       if (Op1BO == Op1)
2729         return BinaryOperator::CreateSub(Op0BO, Rem);
2730       else
2731         return BinaryOperator::CreateSub(Rem, Op0BO);
2732     }
2733   }
2734
2735   if (I.getType() == Type::Int1Ty)
2736     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2737
2738   // If one of the operands of the multiply is a cast from a boolean value, then
2739   // we know the bool is either zero or one, so this is a 'masking' multiply.
2740   // See if we can simplify things based on how the boolean was originally
2741   // formed.
2742   CastInst *BoolCast = 0;
2743   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2744     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2745       BoolCast = CI;
2746   if (!BoolCast)
2747     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2748       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2749         BoolCast = CI;
2750   if (BoolCast) {
2751     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2752       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2753       const Type *SCOpTy = SCIOp0->getType();
2754       bool TIS = false;
2755       
2756       // If the icmp is true iff the sign bit of X is set, then convert this
2757       // multiply into a shift/and combination.
2758       if (isa<ConstantInt>(SCIOp1) &&
2759           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2760           TIS) {
2761         // Shift the X value right to turn it into "all signbits".
2762         Constant *Amt = Context->getConstantInt(SCIOp0->getType(),
2763                                           SCOpTy->getPrimitiveSizeInBits()-1);
2764         Value *V =
2765           InsertNewInstBefore(
2766             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2767                                             BoolCast->getOperand(0)->getName()+
2768                                             ".mask"), I);
2769
2770         // If the multiply type is not the same as the source type, sign extend
2771         // or truncate to the multiply type.
2772         if (I.getType() != V->getType()) {
2773           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2774           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2775           Instruction::CastOps opcode = 
2776             (SrcBits == DstBits ? Instruction::BitCast : 
2777              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2778           V = InsertCastBefore(opcode, V, I.getType(), I);
2779         }
2780
2781         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2782         return BinaryOperator::CreateAnd(V, OtherOp);
2783       }
2784     }
2785   }
2786
2787   return Changed ? &I : 0;
2788 }
2789
2790 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2791   bool Changed = SimplifyCommutative(I);
2792   Value *Op0 = I.getOperand(0);
2793
2794   // Simplify mul instructions with a constant RHS...
2795   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2796     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2797       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2798       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2799       if (Op1F->isExactlyValue(1.0))
2800         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2801     } else if (isa<VectorType>(Op1->getType())) {
2802       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2803         // As above, vector X*splat(1.0) -> X in all defined cases.
2804         if (Constant *Splat = Op1V->getSplatValue()) {
2805           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2806             if (F->isExactlyValue(1.0))
2807               return ReplaceInstUsesWith(I, Op0);
2808         }
2809       }
2810     }
2811
2812     // Try to fold constant mul into select arguments.
2813     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2814       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2815         return R;
2816
2817     if (isa<PHINode>(Op0))
2818       if (Instruction *NV = FoldOpIntoPhi(I))
2819         return NV;
2820   }
2821
2822   if (Value *Op0v = dyn_castFNegVal(Op0, Context))     // -X * -Y = X*Y
2823     if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
2824       return BinaryOperator::CreateFMul(Op0v, Op1v);
2825
2826   return Changed ? &I : 0;
2827 }
2828
2829 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2830 /// instruction.
2831 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2832   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2833   
2834   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2835   int NonNullOperand = -1;
2836   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2837     if (ST->isNullValue())
2838       NonNullOperand = 2;
2839   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2840   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2841     if (ST->isNullValue())
2842       NonNullOperand = 1;
2843   
2844   if (NonNullOperand == -1)
2845     return false;
2846   
2847   Value *SelectCond = SI->getOperand(0);
2848   
2849   // Change the div/rem to use 'Y' instead of the select.
2850   I.setOperand(1, SI->getOperand(NonNullOperand));
2851   
2852   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2853   // problem.  However, the select, or the condition of the select may have
2854   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2855   // propagate the known value for the select into other uses of it, and
2856   // propagate a known value of the condition into its other users.
2857   
2858   // If the select and condition only have a single use, don't bother with this,
2859   // early exit.
2860   if (SI->use_empty() && SelectCond->hasOneUse())
2861     return true;
2862   
2863   // Scan the current block backward, looking for other uses of SI.
2864   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2865   
2866   while (BBI != BBFront) {
2867     --BBI;
2868     // If we found a call to a function, we can't assume it will return, so
2869     // information from below it cannot be propagated above it.
2870     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2871       break;
2872     
2873     // Replace uses of the select or its condition with the known values.
2874     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2875          I != E; ++I) {
2876       if (*I == SI) {
2877         *I = SI->getOperand(NonNullOperand);
2878         AddToWorkList(BBI);
2879       } else if (*I == SelectCond) {
2880         *I = NonNullOperand == 1 ? Context->getTrue() :
2881                                    Context->getFalse();
2882         AddToWorkList(BBI);
2883       }
2884     }
2885     
2886     // If we past the instruction, quit looking for it.
2887     if (&*BBI == SI)
2888       SI = 0;
2889     if (&*BBI == SelectCond)
2890       SelectCond = 0;
2891     
2892     // If we ran out of things to eliminate, break out of the loop.
2893     if (SelectCond == 0 && SI == 0)
2894       break;
2895     
2896   }
2897   return true;
2898 }
2899
2900
2901 /// This function implements the transforms on div instructions that work
2902 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2903 /// used by the visitors to those instructions.
2904 /// @brief Transforms common to all three div instructions
2905 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2906   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2907
2908   // undef / X -> 0        for integer.
2909   // undef / X -> undef    for FP (the undef could be a snan).
2910   if (isa<UndefValue>(Op0)) {
2911     if (Op0->getType()->isFPOrFPVector())
2912       return ReplaceInstUsesWith(I, Op0);
2913     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2914   }
2915
2916   // X / undef -> undef
2917   if (isa<UndefValue>(Op1))
2918     return ReplaceInstUsesWith(I, Op1);
2919
2920   return 0;
2921 }
2922
2923 /// This function implements the transforms common to both integer division
2924 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2925 /// division instructions.
2926 /// @brief Common integer divide transforms
2927 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2928   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2929
2930   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2931   if (Op0 == Op1) {
2932     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2933       Constant *CI = Context->getConstantInt(Ty->getElementType(), 1);
2934       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2935       return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
2936     }
2937
2938     Constant *CI = Context->getConstantInt(I.getType(), 1);
2939     return ReplaceInstUsesWith(I, CI);
2940   }
2941   
2942   if (Instruction *Common = commonDivTransforms(I))
2943     return Common;
2944   
2945   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2946   // This does not apply for fdiv.
2947   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2948     return &I;
2949
2950   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2951     // div X, 1 == X
2952     if (RHS->equalsInt(1))
2953       return ReplaceInstUsesWith(I, Op0);
2954
2955     // (X / C1) / C2  -> X / (C1*C2)
2956     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2957       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2958         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2959           if (MultiplyOverflows(RHS, LHSRHS,
2960                                 I.getOpcode()==Instruction::SDiv, Context))
2961             return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2962           else 
2963             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2964                                       Context->getConstantExprMul(RHS, LHSRHS));
2965         }
2966
2967     if (!RHS->isZero()) { // avoid X udiv 0
2968       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2969         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2970           return R;
2971       if (isa<PHINode>(Op0))
2972         if (Instruction *NV = FoldOpIntoPhi(I))
2973           return NV;
2974     }
2975   }
2976
2977   // 0 / X == 0, we don't need to preserve faults!
2978   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2979     if (LHS->equalsInt(0))
2980       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2981
2982   // It can't be division by zero, hence it must be division by one.
2983   if (I.getType() == Type::Int1Ty)
2984     return ReplaceInstUsesWith(I, Op0);
2985
2986   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2987     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2988       // div X, 1 == X
2989       if (X->isOne())
2990         return ReplaceInstUsesWith(I, Op0);
2991   }
2992
2993   return 0;
2994 }
2995
2996 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2997   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2998
2999   // Handle the integer div common cases
3000   if (Instruction *Common = commonIDivTransforms(I))
3001     return Common;
3002
3003   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3004     // X udiv C^2 -> X >> C
3005     // Check to see if this is an unsigned division with an exact power of 2,
3006     // if so, convert to a right shift.
3007     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3008       return BinaryOperator::CreateLShr(Op0, 
3009             Context->getConstantInt(Op0->getType(), C->getValue().logBase2()));
3010
3011     // X udiv C, where C >= signbit
3012     if (C->getValue().isNegative()) {
3013       Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3014                                                     ICmpInst::ICMP_ULT, Op0, C),
3015                                       I);
3016       return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3017                                 Context->getConstantInt(I.getType(), 1));
3018     }
3019   }
3020
3021   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3022   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3023     if (RHSI->getOpcode() == Instruction::Shl &&
3024         isa<ConstantInt>(RHSI->getOperand(0))) {
3025       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3026       if (C1.isPowerOf2()) {
3027         Value *N = RHSI->getOperand(1);
3028         const Type *NTy = N->getType();
3029         if (uint32_t C2 = C1.logBase2()) {
3030           Constant *C2V = Context->getConstantInt(NTy, C2);
3031           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3032         }
3033         return BinaryOperator::CreateLShr(Op0, N);
3034       }
3035     }
3036   }
3037   
3038   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3039   // where C1&C2 are powers of two.
3040   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3041     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3042       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3043         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3044         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3045           // Compute the shift amounts
3046           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3047           // Construct the "on true" case of the select
3048           Constant *TC = Context->getConstantInt(Op0->getType(), TSA);
3049           Instruction *TSI = BinaryOperator::CreateLShr(
3050                                                  Op0, TC, SI->getName()+".t");
3051           TSI = InsertNewInstBefore(TSI, I);
3052   
3053           // Construct the "on false" case of the select
3054           Constant *FC = Context->getConstantInt(Op0->getType(), FSA); 
3055           Instruction *FSI = BinaryOperator::CreateLShr(
3056                                                  Op0, FC, SI->getName()+".f");
3057           FSI = InsertNewInstBefore(FSI, I);
3058
3059           // construct the select instruction and return it.
3060           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3061         }
3062       }
3063   return 0;
3064 }
3065
3066 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3067   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3068
3069   // Handle the integer div common cases
3070   if (Instruction *Common = commonIDivTransforms(I))
3071     return Common;
3072
3073   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3074     // sdiv X, -1 == -X
3075     if (RHS->isAllOnesValue())
3076       return BinaryOperator::CreateNeg(*Context, Op0);
3077   }
3078
3079   // If the sign bits of both operands are zero (i.e. we can prove they are
3080   // unsigned inputs), turn this into a udiv.
3081   if (I.getType()->isInteger()) {
3082     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3083     if (MaskedValueIsZero(Op0, Mask)) {
3084       if (MaskedValueIsZero(Op1, Mask)) {
3085         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3086         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3087       }
3088       ConstantInt *ShiftedInt;
3089       if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value()), *Context) &&
3090           ShiftedInt->getValue().isPowerOf2()) {
3091         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3092         // Safe because the only negative value (1 << Y) can take on is
3093         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3094         // the sign bit set.
3095         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3096       }
3097     }
3098   }
3099   
3100   return 0;
3101 }
3102
3103 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3104   return commonDivTransforms(I);
3105 }
3106
3107 /// This function implements the transforms on rem instructions that work
3108 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3109 /// is used by the visitors to those instructions.
3110 /// @brief Transforms common to all three rem instructions
3111 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3112   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3113
3114   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3115     if (I.getType()->isFPOrFPVector())
3116       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3117     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3118   }
3119   if (isa<UndefValue>(Op1))
3120     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3121
3122   // Handle cases involving: rem X, (select Cond, Y, Z)
3123   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3124     return &I;
3125
3126   return 0;
3127 }
3128
3129 /// This function implements the transforms common to both integer remainder
3130 /// instructions (urem and srem). It is called by the visitors to those integer
3131 /// remainder instructions.
3132 /// @brief Common integer remainder transforms
3133 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3134   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3135
3136   if (Instruction *common = commonRemTransforms(I))
3137     return common;
3138
3139   // 0 % X == 0 for integer, we don't need to preserve faults!
3140   if (Constant *LHS = dyn_cast<Constant>(Op0))
3141     if (LHS->isNullValue())
3142       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3143
3144   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3145     // X % 0 == undef, we don't need to preserve faults!
3146     if (RHS->equalsInt(0))
3147       return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
3148     
3149     if (RHS->equalsInt(1))  // X % 1 == 0
3150       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3151
3152     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3153       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3154         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3155           return R;
3156       } else if (isa<PHINode>(Op0I)) {
3157         if (Instruction *NV = FoldOpIntoPhi(I))
3158           return NV;
3159       }
3160
3161       // See if we can fold away this rem instruction.
3162       if (SimplifyDemandedInstructionBits(I))
3163         return &I;
3164     }
3165   }
3166
3167   return 0;
3168 }
3169
3170 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3171   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3172
3173   if (Instruction *common = commonIRemTransforms(I))
3174     return common;
3175   
3176   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3177     // X urem C^2 -> X and C
3178     // Check to see if this is an unsigned remainder with an exact power of 2,
3179     // if so, convert to a bitwise and.
3180     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3181       if (C->getValue().isPowerOf2())
3182         return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
3183   }
3184
3185   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3186     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3187     if (RHSI->getOpcode() == Instruction::Shl &&
3188         isa<ConstantInt>(RHSI->getOperand(0))) {
3189       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3190         Constant *N1 = Context->getAllOnesValue(I.getType());
3191         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3192                                                                    "tmp"), I);
3193         return BinaryOperator::CreateAnd(Op0, Add);
3194       }
3195     }
3196   }
3197
3198   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3199   // where C1&C2 are powers of two.
3200   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3201     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3202       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3203         // STO == 0 and SFO == 0 handled above.
3204         if ((STO->getValue().isPowerOf2()) && 
3205             (SFO->getValue().isPowerOf2())) {
3206           Value *TrueAnd = InsertNewInstBefore(
3207             BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3208                                       SI->getName()+".t"), I);
3209           Value *FalseAnd = InsertNewInstBefore(
3210             BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3211                                       SI->getName()+".f"), I);
3212           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3213         }
3214       }
3215   }
3216   
3217   return 0;
3218 }
3219
3220 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3221   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3222
3223   // Handle the integer rem common cases
3224   if (Instruction *common = commonIRemTransforms(I))
3225     return common;
3226   
3227   if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
3228     if (!isa<Constant>(RHSNeg) ||
3229         (isa<ConstantInt>(RHSNeg) &&
3230          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3231       // X % -Y -> X % Y
3232       AddUsesToWorkList(I);
3233       I.setOperand(1, RHSNeg);
3234       return &I;
3235     }
3236
3237   // If the sign bits of both operands are zero (i.e. we can prove they are
3238   // unsigned inputs), turn this into a urem.
3239   if (I.getType()->isInteger()) {
3240     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3241     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3242       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3243       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3244     }
3245   }
3246
3247   // If it's a constant vector, flip any negative values positive.
3248   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3249     unsigned VWidth = RHSV->getNumOperands();
3250
3251     bool hasNegative = false;
3252     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3253       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3254         if (RHS->getValue().isNegative())
3255           hasNegative = true;
3256
3257     if (hasNegative) {
3258       std::vector<Constant *> Elts(VWidth);
3259       for (unsigned i = 0; i != VWidth; ++i) {
3260         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3261           if (RHS->getValue().isNegative())
3262             Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
3263           else
3264             Elts[i] = RHS;
3265         }
3266       }
3267
3268       Constant *NewRHSV = Context->getConstantVector(Elts);
3269       if (NewRHSV != RHSV) {
3270         AddUsesToWorkList(I);
3271         I.setOperand(1, NewRHSV);
3272         return &I;
3273       }
3274     }
3275   }
3276
3277   return 0;
3278 }
3279
3280 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3281   return commonRemTransforms(I);
3282 }
3283
3284 // isOneBitSet - Return true if there is exactly one bit set in the specified
3285 // constant.
3286 static bool isOneBitSet(const ConstantInt *CI) {
3287   return CI->getValue().isPowerOf2();
3288 }
3289
3290 // isHighOnes - Return true if the constant is of the form 1+0+.
3291 // This is the same as lowones(~X).
3292 static bool isHighOnes(const ConstantInt *CI) {
3293   return (~CI->getValue() + 1).isPowerOf2();
3294 }
3295
3296 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3297 /// are carefully arranged to allow folding of expressions such as:
3298 ///
3299 ///      (A < B) | (A > B) --> (A != B)
3300 ///
3301 /// Note that this is only valid if the first and second predicates have the
3302 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3303 ///
3304 /// Three bits are used to represent the condition, as follows:
3305 ///   0  A > B
3306 ///   1  A == B
3307 ///   2  A < B
3308 ///
3309 /// <=>  Value  Definition
3310 /// 000     0   Always false
3311 /// 001     1   A >  B
3312 /// 010     2   A == B
3313 /// 011     3   A >= B
3314 /// 100     4   A <  B
3315 /// 101     5   A != B
3316 /// 110     6   A <= B
3317 /// 111     7   Always true
3318 ///  
3319 static unsigned getICmpCode(const ICmpInst *ICI) {
3320   switch (ICI->getPredicate()) {
3321     // False -> 0
3322   case ICmpInst::ICMP_UGT: return 1;  // 001
3323   case ICmpInst::ICMP_SGT: return 1;  // 001
3324   case ICmpInst::ICMP_EQ:  return 2;  // 010
3325   case ICmpInst::ICMP_UGE: return 3;  // 011
3326   case ICmpInst::ICMP_SGE: return 3;  // 011
3327   case ICmpInst::ICMP_ULT: return 4;  // 100
3328   case ICmpInst::ICMP_SLT: return 4;  // 100
3329   case ICmpInst::ICMP_NE:  return 5;  // 101
3330   case ICmpInst::ICMP_ULE: return 6;  // 110
3331   case ICmpInst::ICMP_SLE: return 6;  // 110
3332     // True -> 7
3333   default:
3334     llvm_unreachable("Invalid ICmp predicate!");
3335     return 0;
3336   }
3337 }
3338
3339 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3340 /// predicate into a three bit mask. It also returns whether it is an ordered
3341 /// predicate by reference.
3342 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3343   isOrdered = false;
3344   switch (CC) {
3345   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3346   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3347   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3348   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3349   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3350   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3351   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3352   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3353   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3354   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3355   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3356   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3357   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3358   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3359     // True -> 7
3360   default:
3361     // Not expecting FCMP_FALSE and FCMP_TRUE;
3362     llvm_unreachable("Unexpected FCmp predicate!");
3363     return 0;
3364   }
3365 }
3366
3367 /// getICmpValue - This is the complement of getICmpCode, which turns an
3368 /// opcode and two operands into either a constant true or false, or a brand 
3369 /// new ICmp instruction. The sign is passed in to determine which kind
3370 /// of predicate to use in the new icmp instruction.
3371 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3372                            LLVMContext *Context) {
3373   switch (code) {
3374   default: llvm_unreachable("Illegal ICmp code!");
3375   case  0: return Context->getFalse();
3376   case  1: 
3377     if (sign)
3378       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
3379     else
3380       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3381   case  2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ,  LHS, RHS);
3382   case  3: 
3383     if (sign)
3384       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
3385     else
3386       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
3387   case  4: 
3388     if (sign)
3389       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
3390     else
3391       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3392   case  5: return new ICmpInst(*Context, ICmpInst::ICMP_NE,  LHS, RHS);
3393   case  6: 
3394     if (sign)
3395       return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
3396     else
3397       return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
3398   case  7: return Context->getTrue();
3399   }
3400 }
3401
3402 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3403 /// opcode and two operands into either a FCmp instruction. isordered is passed
3404 /// in to determine which kind of predicate to use in the new fcmp instruction.
3405 static Value *getFCmpValue(bool isordered, unsigned code,
3406                            Value *LHS, Value *RHS, LLVMContext *Context) {
3407   switch (code) {
3408   default: llvm_unreachable("Illegal FCmp code!");
3409   case  0:
3410     if (isordered)
3411       return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
3412     else
3413       return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
3414   case  1: 
3415     if (isordered)
3416       return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
3417     else
3418       return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
3419   case  2: 
3420     if (isordered)
3421       return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
3422     else
3423       return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
3424   case  3: 
3425     if (isordered)
3426       return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
3427     else
3428       return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
3429   case  4: 
3430     if (isordered)
3431       return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
3432     else
3433       return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
3434   case  5: 
3435     if (isordered)
3436       return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
3437     else
3438       return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
3439   case  6: 
3440     if (isordered)
3441       return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
3442     else
3443       return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
3444   case  7: return Context->getTrue();
3445   }
3446 }
3447
3448 /// PredicatesFoldable - Return true if both predicates match sign or if at
3449 /// least one of them is an equality comparison (which is signless).
3450 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3451   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3452          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3453          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3454 }
3455
3456 namespace { 
3457 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3458 struct FoldICmpLogical {
3459   InstCombiner &IC;
3460   Value *LHS, *RHS;
3461   ICmpInst::Predicate pred;
3462   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3463     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3464       pred(ICI->getPredicate()) {}
3465   bool shouldApply(Value *V) const {
3466     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3467       if (PredicatesFoldable(pred, ICI->getPredicate()))
3468         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3469                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3470     return false;
3471   }
3472   Instruction *apply(Instruction &Log) const {
3473     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3474     if (ICI->getOperand(0) != LHS) {
3475       assert(ICI->getOperand(1) == LHS);
3476       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3477     }
3478
3479     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3480     unsigned LHSCode = getICmpCode(ICI);
3481     unsigned RHSCode = getICmpCode(RHSICI);
3482     unsigned Code;
3483     switch (Log.getOpcode()) {
3484     case Instruction::And: Code = LHSCode & RHSCode; break;
3485     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3486     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3487     default: llvm_unreachable("Illegal logical opcode!"); return 0;
3488     }
3489
3490     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3491                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3492       
3493     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3494     if (Instruction *I = dyn_cast<Instruction>(RV))
3495       return I;
3496     // Otherwise, it's a constant boolean value...
3497     return IC.ReplaceInstUsesWith(Log, RV);
3498   }
3499 };
3500 } // end anonymous namespace
3501
3502 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3503 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3504 // guaranteed to be a binary operator.
3505 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3506                                     ConstantInt *OpRHS,
3507                                     ConstantInt *AndRHS,
3508                                     BinaryOperator &TheAnd) {
3509   Value *X = Op->getOperand(0);
3510   Constant *Together = 0;
3511   if (!Op->isShift())
3512     Together = Context->getConstantExprAnd(AndRHS, OpRHS);
3513
3514   switch (Op->getOpcode()) {
3515   case Instruction::Xor:
3516     if (Op->hasOneUse()) {
3517       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3518       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3519       InsertNewInstBefore(And, TheAnd);
3520       And->takeName(Op);
3521       return BinaryOperator::CreateXor(And, Together);
3522     }
3523     break;
3524   case Instruction::Or:
3525     if (Together == AndRHS) // (X | C) & C --> C
3526       return ReplaceInstUsesWith(TheAnd, AndRHS);
3527
3528     if (Op->hasOneUse() && Together != OpRHS) {
3529       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3530       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3531       InsertNewInstBefore(Or, TheAnd);
3532       Or->takeName(Op);
3533       return BinaryOperator::CreateAnd(Or, AndRHS);
3534     }
3535     break;
3536   case Instruction::Add:
3537     if (Op->hasOneUse()) {
3538       // Adding a one to a single bit bit-field should be turned into an XOR
3539       // of the bit.  First thing to check is to see if this AND is with a
3540       // single bit constant.
3541       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3542
3543       // If there is only one bit set...
3544       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3545         // Ok, at this point, we know that we are masking the result of the
3546         // ADD down to exactly one bit.  If the constant we are adding has
3547         // no bits set below this bit, then we can eliminate the ADD.
3548         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3549
3550         // Check to see if any bits below the one bit set in AndRHSV are set.
3551         if ((AddRHS & (AndRHSV-1)) == 0) {
3552           // If not, the only thing that can effect the output of the AND is
3553           // the bit specified by AndRHSV.  If that bit is set, the effect of
3554           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3555           // no effect.
3556           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3557             TheAnd.setOperand(0, X);
3558             return &TheAnd;
3559           } else {
3560             // Pull the XOR out of the AND.
3561             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3562             InsertNewInstBefore(NewAnd, TheAnd);
3563             NewAnd->takeName(Op);
3564             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3565           }
3566         }
3567       }
3568     }
3569     break;
3570
3571   case Instruction::Shl: {
3572     // We know that the AND will not produce any of the bits shifted in, so if
3573     // the anded constant includes them, clear them now!
3574     //
3575     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3576     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3577     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3578     ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShlMask);
3579
3580     if (CI->getValue() == ShlMask) { 
3581     // Masking out bits that the shift already masks
3582       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3583     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3584       TheAnd.setOperand(1, CI);
3585       return &TheAnd;
3586     }
3587     break;
3588   }
3589   case Instruction::LShr:
3590   {
3591     // We know that the AND will not produce any of the bits shifted in, so if
3592     // the anded constant includes them, clear them now!  This only applies to
3593     // unsigned shifts, because a signed shr may bring in set bits!
3594     //
3595     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3596     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3597     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3598     ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3599
3600     if (CI->getValue() == ShrMask) {   
3601     // Masking out bits that the shift already masks.
3602       return ReplaceInstUsesWith(TheAnd, Op);
3603     } else if (CI != AndRHS) {
3604       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3605       return &TheAnd;
3606     }
3607     break;
3608   }
3609   case Instruction::AShr:
3610     // Signed shr.
3611     // See if this is shifting in some sign extension, then masking it out
3612     // with an and.
3613     if (Op->hasOneUse()) {
3614       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3615       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3616       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3617       Constant *C = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3618       if (C == AndRHS) {          // Masking out bits shifted in.
3619         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3620         // Make the argument unsigned.
3621         Value *ShVal = Op->getOperand(0);
3622         ShVal = InsertNewInstBefore(
3623             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3624                                    Op->getName()), TheAnd);
3625         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3626       }
3627     }
3628     break;
3629   }
3630   return 0;
3631 }
3632
3633
3634 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3635 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3636 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3637 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3638 /// insert new instructions.
3639 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3640                                            bool isSigned, bool Inside, 
3641                                            Instruction &IB) {
3642   assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ? 
3643             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3644          "Lo is not <= Hi in range emission code!");
3645     
3646   if (Inside) {
3647     if (Lo == Hi)  // Trivially false.
3648       return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
3649
3650     // V >= Min && V < Hi --> V < Hi
3651     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3652       ICmpInst::Predicate pred = (isSigned ? 
3653         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3654       return new ICmpInst(*Context, pred, V, Hi);
3655     }
3656
3657     // Emit V-Lo <u Hi-Lo
3658     Constant *NegLo = Context->getConstantExprNeg(Lo);
3659     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3660     InsertNewInstBefore(Add, IB);
3661     Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
3662     return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
3663   }
3664
3665   if (Lo == Hi)  // Trivially true.
3666     return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
3667
3668   // V < Min || V >= Hi -> V > Hi-1
3669   Hi = SubOne(cast<ConstantInt>(Hi), Context);
3670   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3671     ICmpInst::Predicate pred = (isSigned ? 
3672         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3673     return new ICmpInst(*Context, pred, V, Hi);
3674   }
3675
3676   // Emit V-Lo >u Hi-1-Lo
3677   // Note that Hi has already had one subtracted from it, above.
3678   ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
3679   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3680   InsertNewInstBefore(Add, IB);
3681   Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
3682   return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
3683 }
3684
3685 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3686 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3687 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3688 // not, since all 1s are not contiguous.
3689 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3690   const APInt& V = Val->getValue();
3691   uint32_t BitWidth = Val->getType()->getBitWidth();
3692   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3693
3694   // look for the first zero bit after the run of ones
3695   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3696   // look for the first non-zero bit
3697   ME = V.getActiveBits(); 
3698   return true;
3699 }
3700
3701 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3702 /// where isSub determines whether the operator is a sub.  If we can fold one of
3703 /// the following xforms:
3704 /// 
3705 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3706 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3707 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3708 ///
3709 /// return (A +/- B).
3710 ///
3711 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3712                                         ConstantInt *Mask, bool isSub,
3713                                         Instruction &I) {
3714   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3715   if (!LHSI || LHSI->getNumOperands() != 2 ||
3716       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3717
3718   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3719
3720   switch (LHSI->getOpcode()) {
3721   default: return 0;
3722   case Instruction::And:
3723     if (Context->getConstantExprAnd(N, Mask) == Mask) {
3724       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3725       if ((Mask->getValue().countLeadingZeros() + 
3726            Mask->getValue().countPopulation()) == 
3727           Mask->getValue().getBitWidth())
3728         break;
3729
3730       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3731       // part, we don't need any explicit masks to take them out of A.  If that
3732       // is all N is, ignore it.
3733       uint32_t MB = 0, ME = 0;
3734       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3735         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3736         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3737         if (MaskedValueIsZero(RHS, Mask))
3738           break;
3739       }
3740     }
3741     return 0;
3742   case Instruction::Or:
3743   case Instruction::Xor:
3744     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3745     if ((Mask->getValue().countLeadingZeros() + 
3746          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3747         && Context->getConstantExprAnd(N, Mask)->isNullValue())
3748       break;
3749     return 0;
3750   }
3751   
3752   Instruction *New;
3753   if (isSub)
3754     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3755   else
3756     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3757   return InsertNewInstBefore(New, I);
3758 }
3759
3760 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3761 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3762                                           ICmpInst *LHS, ICmpInst *RHS) {
3763   Value *Val, *Val2;
3764   ConstantInt *LHSCst, *RHSCst;
3765   ICmpInst::Predicate LHSCC, RHSCC;
3766   
3767   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3768   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3769                          m_ConstantInt(LHSCst)), *Context) ||
3770       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3771                          m_ConstantInt(RHSCst)), *Context))
3772     return 0;
3773   
3774   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3775   // where C is a power of 2
3776   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3777       LHSCst->getValue().isPowerOf2()) {
3778     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3779     InsertNewInstBefore(NewOr, I);
3780     return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
3781   }
3782   
3783   // From here on, we only handle:
3784   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3785   if (Val != Val2) return 0;
3786   
3787   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3788   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3789       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3790       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3791       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3792     return 0;
3793   
3794   // We can't fold (ugt x, C) & (sgt x, C2).
3795   if (!PredicatesFoldable(LHSCC, RHSCC))
3796     return 0;
3797     
3798   // Ensure that the larger constant is on the RHS.
3799   bool ShouldSwap;
3800   if (ICmpInst::isSignedPredicate(LHSCC) ||
3801       (ICmpInst::isEquality(LHSCC) && 
3802        ICmpInst::isSignedPredicate(RHSCC)))
3803     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3804   else
3805     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3806     
3807   if (ShouldSwap) {
3808     std::swap(LHS, RHS);
3809     std::swap(LHSCst, RHSCst);
3810     std::swap(LHSCC, RHSCC);
3811   }
3812
3813   // At this point, we know we have have two icmp instructions
3814   // comparing a value against two constants and and'ing the result
3815   // together.  Because of the above check, we know that we only have
3816   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3817   // (from the FoldICmpLogical check above), that the two constants 
3818   // are not equal and that the larger constant is on the RHS
3819   assert(LHSCst != RHSCst && "Compares not folded above?");
3820
3821   switch (LHSCC) {
3822   default: llvm_unreachable("Unknown integer condition code!");
3823   case ICmpInst::ICMP_EQ:
3824     switch (RHSCC) {
3825     default: llvm_unreachable("Unknown integer condition code!");
3826     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3827     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3828     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3829       return ReplaceInstUsesWith(I, Context->getFalse());
3830     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3831     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3832     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3833       return ReplaceInstUsesWith(I, LHS);
3834     }
3835   case ICmpInst::ICMP_NE:
3836     switch (RHSCC) {
3837     default: llvm_unreachable("Unknown integer condition code!");
3838     case ICmpInst::ICMP_ULT:
3839       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
3840         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
3841       break;                        // (X != 13 & X u< 15) -> no change
3842     case ICmpInst::ICMP_SLT:
3843       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
3844         return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
3845       break;                        // (X != 13 & X s< 15) -> no change
3846     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3847     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3848     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3849       return ReplaceInstUsesWith(I, RHS);
3850     case ICmpInst::ICMP_NE:
3851       if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3852         Constant *AddCST = Context->getConstantExprNeg(LHSCst);
3853         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3854                                                      Val->getName()+".off");
3855         InsertNewInstBefore(Add, I);
3856         return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
3857                             Context->getConstantInt(Add->getType(), 1));
3858       }
3859       break;                        // (X != 13 & X != 15) -> no change
3860     }
3861     break;
3862   case ICmpInst::ICMP_ULT:
3863     switch (RHSCC) {
3864     default: llvm_unreachable("Unknown integer condition code!");
3865     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3866     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3867       return ReplaceInstUsesWith(I, Context->getFalse());
3868     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3869       break;
3870     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3871     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3872       return ReplaceInstUsesWith(I, LHS);
3873     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3874       break;
3875     }
3876     break;
3877   case ICmpInst::ICMP_SLT:
3878     switch (RHSCC) {
3879     default: llvm_unreachable("Unknown integer condition code!");
3880     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3881     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3882       return ReplaceInstUsesWith(I, Context->getFalse());
3883     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3884       break;
3885     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3886     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3887       return ReplaceInstUsesWith(I, LHS);
3888     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3889       break;
3890     }
3891     break;
3892   case ICmpInst::ICMP_UGT:
3893     switch (RHSCC) {
3894     default: llvm_unreachable("Unknown integer condition code!");
3895     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3896     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3897       return ReplaceInstUsesWith(I, RHS);
3898     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3899       break;
3900     case ICmpInst::ICMP_NE:
3901       if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
3902         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3903       break;                        // (X u> 13 & X != 15) -> no change
3904     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3905       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3906                              RHSCst, false, true, I);
3907     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3908       break;
3909     }
3910     break;
3911   case ICmpInst::ICMP_SGT:
3912     switch (RHSCC) {
3913     default: llvm_unreachable("Unknown integer condition code!");
3914     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3915     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3916       return ReplaceInstUsesWith(I, RHS);
3917     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3918       break;
3919     case ICmpInst::ICMP_NE:
3920       if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
3921         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3922       break;                        // (X s> 13 & X != 15) -> no change
3923     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3924       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3925                              RHSCst, true, true, I);
3926     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3927       break;
3928     }
3929     break;
3930   }
3931  
3932   return 0;
3933 }
3934
3935
3936 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3937   bool Changed = SimplifyCommutative(I);
3938   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3939
3940   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3941     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3942
3943   // and X, X = X
3944   if (Op0 == Op1)
3945     return ReplaceInstUsesWith(I, Op1);
3946
3947   // See if we can simplify any instructions used by the instruction whose sole 
3948   // purpose is to compute bits we don't care about.
3949   if (SimplifyDemandedInstructionBits(I))
3950     return &I;
3951   if (isa<VectorType>(I.getType())) {
3952     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3953       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3954         return ReplaceInstUsesWith(I, I.getOperand(0));
3955     } else if (isa<ConstantAggregateZero>(Op1)) {
3956       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3957     }
3958   }
3959
3960   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3961     const APInt& AndRHSMask = AndRHS->getValue();
3962     APInt NotAndRHS(~AndRHSMask);
3963
3964     // Optimize a variety of ((val OP C1) & C2) combinations...
3965     if (isa<BinaryOperator>(Op0)) {
3966       Instruction *Op0I = cast<Instruction>(Op0);
3967       Value *Op0LHS = Op0I->getOperand(0);
3968       Value *Op0RHS = Op0I->getOperand(1);
3969       switch (Op0I->getOpcode()) {
3970       case Instruction::Xor:
3971       case Instruction::Or:
3972         // If the mask is only needed on one incoming arm, push it up.
3973         if (Op0I->hasOneUse()) {
3974           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3975             // Not masking anything out for the LHS, move to RHS.
3976             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3977                                                    Op0RHS->getName()+".masked");
3978             InsertNewInstBefore(NewRHS, I);
3979             return BinaryOperator::Create(
3980                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3981           }
3982           if (!isa<Constant>(Op0RHS) &&
3983               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3984             // Not masking anything out for the RHS, move to LHS.
3985             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3986                                                    Op0LHS->getName()+".masked");
3987             InsertNewInstBefore(NewLHS, I);
3988             return BinaryOperator::Create(
3989                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3990           }
3991         }
3992
3993         break;
3994       case Instruction::Add:
3995         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3996         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3997         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3998         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3999           return BinaryOperator::CreateAnd(V, AndRHS);
4000         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4001           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4002         break;
4003
4004       case Instruction::Sub:
4005         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4006         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4007         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4008         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4009           return BinaryOperator::CreateAnd(V, AndRHS);
4010
4011         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4012         // has 1's for all bits that the subtraction with A might affect.
4013         if (Op0I->hasOneUse()) {
4014           uint32_t BitWidth = AndRHSMask.getBitWidth();
4015           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4016           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4017
4018           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4019           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4020               MaskedValueIsZero(Op0LHS, Mask)) {
4021             Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
4022             InsertNewInstBefore(NewNeg, I);
4023             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4024           }
4025         }
4026         break;
4027
4028       case Instruction::Shl:
4029       case Instruction::LShr:
4030         // (1 << x) & 1 --> zext(x == 0)
4031         // (1 >> x) & 1 --> zext(x == 0)
4032         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4033           Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4034                                     Op0RHS, Context->getNullValue(I.getType()));
4035           InsertNewInstBefore(NewICmp, I);
4036           return new ZExtInst(NewICmp, I.getType());
4037         }
4038         break;
4039       }
4040
4041       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4042         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4043           return Res;
4044     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4045       // If this is an integer truncation or change from signed-to-unsigned, and
4046       // if the source is an and/or with immediate, transform it.  This
4047       // frequently occurs for bitfield accesses.
4048       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4049         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4050             CastOp->getNumOperands() == 2)
4051           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4052             if (CastOp->getOpcode() == Instruction::And) {
4053               // Change: and (cast (and X, C1) to T), C2
4054               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4055               // This will fold the two constants together, which may allow 
4056               // other simplifications.
4057               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4058                 CastOp->getOperand(0), I.getType(), 
4059                 CastOp->getName()+".shrunk");
4060               NewCast = InsertNewInstBefore(NewCast, I);
4061               // trunc_or_bitcast(C1)&C2
4062               Constant *C3 =
4063                       Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4064               C3 = Context->getConstantExprAnd(C3, AndRHS);
4065               return BinaryOperator::CreateAnd(NewCast, C3);
4066             } else if (CastOp->getOpcode() == Instruction::Or) {
4067               // Change: and (cast (or X, C1) to T), C2
4068               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4069               Constant *C3 =
4070                       Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4071               if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4072                 // trunc(C1)&C2
4073                 return ReplaceInstUsesWith(I, AndRHS);
4074             }
4075           }
4076       }
4077     }
4078
4079     // Try to fold constant and into select arguments.
4080     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4081       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4082         return R;
4083     if (isa<PHINode>(Op0))
4084       if (Instruction *NV = FoldOpIntoPhi(I))
4085         return NV;
4086   }
4087
4088   Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4089   Value *Op1NotVal = dyn_castNotVal(Op1, Context);
4090
4091   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4092     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
4093
4094   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4095   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4096     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4097                                                I.getName()+".demorgan");
4098     InsertNewInstBefore(Or, I);
4099     return BinaryOperator::CreateNot(*Context, Or);
4100   }
4101   
4102   {
4103     Value *A = 0, *B = 0, *C = 0, *D = 0;
4104     if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
4105       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4106         return ReplaceInstUsesWith(I, Op1);
4107     
4108       // (A|B) & ~(A&B) -> A^B
4109       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4110         if ((A == C && B == D) || (A == D && B == C))
4111           return BinaryOperator::CreateXor(A, B);
4112       }
4113     }
4114     
4115     if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
4116       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4117         return ReplaceInstUsesWith(I, Op0);
4118
4119       // ~(A&B) & (A|B) -> A^B
4120       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4121         if ((A == C && B == D) || (A == D && B == C))
4122           return BinaryOperator::CreateXor(A, B);
4123       }
4124     }
4125     
4126     if (Op0->hasOneUse() &&
4127         match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4128       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4129         I.swapOperands();     // Simplify below
4130         std::swap(Op0, Op1);
4131       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4132         cast<BinaryOperator>(Op0)->swapOperands();
4133         I.swapOperands();     // Simplify below
4134         std::swap(Op0, Op1);
4135       }
4136     }
4137
4138     if (Op1->hasOneUse() &&
4139         match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4140       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4141         cast<BinaryOperator>(Op1)->swapOperands();
4142         std::swap(A, B);
4143       }
4144       if (A == Op0) {                                // A&(A^B) -> A & ~B
4145         Instruction *NotB = BinaryOperator::CreateNot(*Context, B, "tmp");
4146         InsertNewInstBefore(NotB, I);
4147         return BinaryOperator::CreateAnd(A, NotB);
4148       }
4149     }
4150
4151     // (A&((~A)|B)) -> A&B
4152     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4153         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
4154       return BinaryOperator::CreateAnd(A, Op1);
4155     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4156         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
4157       return BinaryOperator::CreateAnd(A, Op0);
4158   }
4159   
4160   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4161     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4162     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4163       return R;
4164
4165     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4166       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4167         return Res;
4168   }
4169
4170   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4171   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4172     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4173       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4174         const Type *SrcTy = Op0C->getOperand(0)->getType();
4175         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4176             // Only do this if the casts both really cause code to be generated.
4177             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4178                               I.getType(), TD) &&
4179             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4180                               I.getType(), TD)) {
4181           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4182                                                          Op1C->getOperand(0),
4183                                                          I.getName());
4184           InsertNewInstBefore(NewOp, I);
4185           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4186         }
4187       }
4188     
4189   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4190   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4191     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4192       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4193           SI0->getOperand(1) == SI1->getOperand(1) &&
4194           (SI0->hasOneUse() || SI1->hasOneUse())) {
4195         Instruction *NewOp =
4196           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4197                                                         SI1->getOperand(0),
4198                                                         SI0->getName()), I);
4199         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4200                                       SI1->getOperand(1));
4201       }
4202   }
4203
4204   // If and'ing two fcmp, try combine them into one.
4205   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4206     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4207       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4208           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4209         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4210         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4211           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4212             // If either of the constants are nans, then the whole thing returns
4213             // false.
4214             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4215               return ReplaceInstUsesWith(I, Context->getFalse());
4216             return new FCmpInst(*Context, FCmpInst::FCMP_ORD, 
4217                                 LHS->getOperand(0), RHS->getOperand(0));
4218           }
4219       } else {
4220         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4221         FCmpInst::Predicate Op0CC, Op1CC;
4222         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4223                   m_Value(Op0RHS)), *Context) &&
4224             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4225                   m_Value(Op1RHS)), *Context)) {
4226           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4227             // Swap RHS operands to match LHS.
4228             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4229             std::swap(Op1LHS, Op1RHS);
4230           }
4231           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4232             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4233             if (Op0CC == Op1CC)
4234               return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4235                                   Op0LHS, Op0RHS);
4236             else if (Op0CC == FCmpInst::FCMP_FALSE ||
4237                      Op1CC == FCmpInst::FCMP_FALSE)
4238               return ReplaceInstUsesWith(I, Context->getFalse());
4239             else if (Op0CC == FCmpInst::FCMP_TRUE)
4240               return ReplaceInstUsesWith(I, Op1);
4241             else if (Op1CC == FCmpInst::FCMP_TRUE)
4242               return ReplaceInstUsesWith(I, Op0);
4243             bool Op0Ordered;
4244             bool Op1Ordered;
4245             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4246             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4247             if (Op1Pred == 0) {
4248               std::swap(Op0, Op1);
4249               std::swap(Op0Pred, Op1Pred);
4250               std::swap(Op0Ordered, Op1Ordered);
4251             }
4252             if (Op0Pred == 0) {
4253               // uno && ueq -> uno && (uno || eq) -> ueq
4254               // ord && olt -> ord && (ord && lt) -> olt
4255               if (Op0Ordered == Op1Ordered)
4256                 return ReplaceInstUsesWith(I, Op1);
4257               // uno && oeq -> uno && (ord && eq) -> false
4258               // uno && ord -> false
4259               if (!Op0Ordered)
4260                 return ReplaceInstUsesWith(I, Context->getFalse());
4261               // ord && ueq -> ord && (uno || eq) -> oeq
4262               return cast<Instruction>(getFCmpValue(true, Op1Pred,
4263                                                     Op0LHS, Op0RHS, Context));
4264             }
4265           }
4266         }
4267       }
4268     }
4269   }
4270
4271   return Changed ? &I : 0;
4272 }
4273
4274 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4275 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4276 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4277 /// the expression came from the corresponding "byte swapped" byte in some other
4278 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4279 /// we know that the expression deposits the low byte of %X into the high byte
4280 /// of the bswap result and that all other bytes are zero.  This expression is
4281 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4282 /// match.
4283 ///
4284 /// This function returns true if the match was unsuccessful and false if so.
4285 /// On entry to the function the "OverallLeftShift" is a signed integer value
4286 /// indicating the number of bytes that the subexpression is later shifted.  For
4287 /// example, if the expression is later right shifted by 16 bits, the
4288 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4289 /// byte of ByteValues is actually being set.
4290 ///
4291 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4292 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4293 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4294 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4295 /// always in the local (OverallLeftShift) coordinate space.
4296 ///
4297 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4298                               SmallVector<Value*, 8> &ByteValues) {
4299   if (Instruction *I = dyn_cast<Instruction>(V)) {
4300     // If this is an or instruction, it may be an inner node of the bswap.
4301     if (I->getOpcode() == Instruction::Or) {
4302       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4303                                ByteValues) ||
4304              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4305                                ByteValues);
4306     }
4307   
4308     // If this is a logical shift by a constant multiple of 8, recurse with
4309     // OverallLeftShift and ByteMask adjusted.
4310     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4311       unsigned ShAmt = 
4312         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4313       // Ensure the shift amount is defined and of a byte value.
4314       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4315         return true;
4316
4317       unsigned ByteShift = ShAmt >> 3;
4318       if (I->getOpcode() == Instruction::Shl) {
4319         // X << 2 -> collect(X, +2)
4320         OverallLeftShift += ByteShift;
4321         ByteMask >>= ByteShift;
4322       } else {
4323         // X >>u 2 -> collect(X, -2)
4324         OverallLeftShift -= ByteShift;
4325         ByteMask <<= ByteShift;
4326         ByteMask &= (~0U >> (32-ByteValues.size()));
4327       }
4328
4329       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4330       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4331
4332       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4333                                ByteValues);
4334     }
4335
4336     // If this is a logical 'and' with a mask that clears bytes, clear the
4337     // corresponding bytes in ByteMask.
4338     if (I->getOpcode() == Instruction::And &&
4339         isa<ConstantInt>(I->getOperand(1))) {
4340       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4341       unsigned NumBytes = ByteValues.size();
4342       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4343       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4344       
4345       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4346         // If this byte is masked out by a later operation, we don't care what
4347         // the and mask is.
4348         if ((ByteMask & (1 << i)) == 0)
4349           continue;
4350         
4351         // If the AndMask is all zeros for this byte, clear the bit.
4352         APInt MaskB = AndMask & Byte;
4353         if (MaskB == 0) {
4354           ByteMask &= ~(1U << i);
4355           continue;
4356         }
4357         
4358         // If the AndMask is not all ones for this byte, it's not a bytezap.
4359         if (MaskB != Byte)
4360           return true;
4361
4362         // Otherwise, this byte is kept.
4363       }
4364
4365       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4366                                ByteValues);
4367     }
4368   }
4369   
4370   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4371   // the input value to the bswap.  Some observations: 1) if more than one byte
4372   // is demanded from this input, then it could not be successfully assembled
4373   // into a byteswap.  At least one of the two bytes would not be aligned with
4374   // their ultimate destination.
4375   if (!isPowerOf2_32(ByteMask)) return true;
4376   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4377   
4378   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4379   // is demanded, it needs to go into byte 0 of the result.  This means that the
4380   // byte needs to be shifted until it lands in the right byte bucket.  The
4381   // shift amount depends on the position: if the byte is coming from the high
4382   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4383   // low part, it must be shifted left.
4384   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4385   if (InputByteNo < ByteValues.size()/2) {
4386     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4387       return true;
4388   } else {
4389     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4390       return true;
4391   }
4392   
4393   // If the destination byte value is already defined, the values are or'd
4394   // together, which isn't a bswap (unless it's an or of the same bits).
4395   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4396     return true;
4397   ByteValues[DestByteNo] = V;
4398   return false;
4399 }
4400
4401 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4402 /// If so, insert the new bswap intrinsic and return it.
4403 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4404   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4405   if (!ITy || ITy->getBitWidth() % 16 || 
4406       // ByteMask only allows up to 32-byte values.
4407       ITy->getBitWidth() > 32*8) 
4408     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4409   
4410   /// ByteValues - For each byte of the result, we keep track of which value
4411   /// defines each byte.
4412   SmallVector<Value*, 8> ByteValues;
4413   ByteValues.resize(ITy->getBitWidth()/8);
4414     
4415   // Try to find all the pieces corresponding to the bswap.
4416   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4417   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4418     return 0;
4419   
4420   // Check to see if all of the bytes come from the same value.
4421   Value *V = ByteValues[0];
4422   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4423   
4424   // Check to make sure that all of the bytes come from the same value.
4425   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4426     if (ByteValues[i] != V)
4427       return 0;
4428   const Type *Tys[] = { ITy };
4429   Module *M = I.getParent()->getParent()->getParent();
4430   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4431   return CallInst::Create(F, V);
4432 }
4433
4434 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4435 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4436 /// we can simplify this expression to "cond ? C : D or B".
4437 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4438                                          Value *C, Value *D,
4439                                          LLVMContext *Context) {
4440   // If A is not a select of -1/0, this cannot match.
4441   Value *Cond = 0;
4442   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
4443     return 0;
4444
4445   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4446   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4447     return SelectInst::Create(Cond, C, B);
4448   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4449     return SelectInst::Create(Cond, C, B);
4450   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4451   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4452     return SelectInst::Create(Cond, C, D);
4453   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4454     return SelectInst::Create(Cond, C, D);
4455   return 0;
4456 }
4457
4458 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4459 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4460                                          ICmpInst *LHS, ICmpInst *RHS) {
4461   Value *Val, *Val2;
4462   ConstantInt *LHSCst, *RHSCst;
4463   ICmpInst::Predicate LHSCC, RHSCC;
4464   
4465   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4466   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4467              m_ConstantInt(LHSCst)), *Context) ||
4468       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4469              m_ConstantInt(RHSCst)), *Context))
4470     return 0;
4471   
4472   // From here on, we only handle:
4473   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4474   if (Val != Val2) return 0;
4475   
4476   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4477   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4478       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4479       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4480       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4481     return 0;
4482   
4483   // We can't fold (ugt x, C) | (sgt x, C2).
4484   if (!PredicatesFoldable(LHSCC, RHSCC))
4485     return 0;
4486   
4487   // Ensure that the larger constant is on the RHS.
4488   bool ShouldSwap;
4489   if (ICmpInst::isSignedPredicate(LHSCC) ||
4490       (ICmpInst::isEquality(LHSCC) && 
4491        ICmpInst::isSignedPredicate(RHSCC)))
4492     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4493   else
4494     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4495   
4496   if (ShouldSwap) {
4497     std::swap(LHS, RHS);
4498     std::swap(LHSCst, RHSCst);
4499     std::swap(LHSCC, RHSCC);
4500   }
4501   
4502   // At this point, we know we have have two icmp instructions
4503   // comparing a value against two constants and or'ing the result
4504   // together.  Because of the above check, we know that we only have
4505   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4506   // FoldICmpLogical check above), that the two constants are not
4507   // equal.
4508   assert(LHSCst != RHSCst && "Compares not folded above?");
4509
4510   switch (LHSCC) {
4511   default: llvm_unreachable("Unknown integer condition code!");
4512   case ICmpInst::ICMP_EQ:
4513     switch (RHSCC) {
4514     default: llvm_unreachable("Unknown integer condition code!");
4515     case ICmpInst::ICMP_EQ:
4516       if (LHSCst == SubOne(RHSCst, Context)) {
4517         // (X == 13 | X == 14) -> X-13 <u 2
4518         Constant *AddCST = Context->getConstantExprNeg(LHSCst);
4519         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4520                                                      Val->getName()+".off");
4521         InsertNewInstBefore(Add, I);
4522         AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
4523         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
4524       }
4525       break;                         // (X == 13 | X == 15) -> no change
4526     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4527     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4528       break;
4529     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4530     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4531     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4532       return ReplaceInstUsesWith(I, RHS);
4533     }
4534     break;
4535   case ICmpInst::ICMP_NE:
4536     switch (RHSCC) {
4537     default: llvm_unreachable("Unknown integer condition code!");
4538     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4539     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4540     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4541       return ReplaceInstUsesWith(I, LHS);
4542     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4543     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4544     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4545       return ReplaceInstUsesWith(I, Context->getTrue());
4546     }
4547     break;
4548   case ICmpInst::ICMP_ULT:
4549     switch (RHSCC) {
4550     default: llvm_unreachable("Unknown integer condition code!");
4551     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4552       break;
4553     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4554       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4555       // this can cause overflow.
4556       if (RHSCst->isMaxValue(false))
4557         return ReplaceInstUsesWith(I, LHS);
4558       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4559                              false, false, I);
4560     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4561       break;
4562     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4563     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4564       return ReplaceInstUsesWith(I, RHS);
4565     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4566       break;
4567     }
4568     break;
4569   case ICmpInst::ICMP_SLT:
4570     switch (RHSCC) {
4571     default: llvm_unreachable("Unknown integer condition code!");
4572     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4573       break;
4574     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4575       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4576       // this can cause overflow.
4577       if (RHSCst->isMaxValue(true))
4578         return ReplaceInstUsesWith(I, LHS);
4579       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4580                              true, false, I);
4581     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4582       break;
4583     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4584     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4585       return ReplaceInstUsesWith(I, RHS);
4586     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4587       break;
4588     }
4589     break;
4590   case ICmpInst::ICMP_UGT:
4591     switch (RHSCC) {
4592     default: llvm_unreachable("Unknown integer condition code!");
4593     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4594     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4595       return ReplaceInstUsesWith(I, LHS);
4596     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4597       break;
4598     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4599     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4600       return ReplaceInstUsesWith(I, Context->getTrue());
4601     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4602       break;
4603     }
4604     break;
4605   case ICmpInst::ICMP_SGT:
4606     switch (RHSCC) {
4607     default: llvm_unreachable("Unknown integer condition code!");
4608     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4609     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4610       return ReplaceInstUsesWith(I, LHS);
4611     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4612       break;
4613     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4614     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4615       return ReplaceInstUsesWith(I, Context->getTrue());
4616     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4617       break;
4618     }
4619     break;
4620   }
4621   return 0;
4622 }
4623
4624 /// FoldOrWithConstants - This helper function folds:
4625 ///
4626 ///     ((A | B) & C1) | (B & C2)
4627 ///
4628 /// into:
4629 /// 
4630 ///     (A & C1) | B
4631 ///
4632 /// when the XOR of the two constants is "all ones" (-1).
4633 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4634                                                Value *A, Value *B, Value *C) {
4635   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4636   if (!CI1) return 0;
4637
4638   Value *V1 = 0;
4639   ConstantInt *CI2 = 0;
4640   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
4641
4642   APInt Xor = CI1->getValue() ^ CI2->getValue();
4643   if (!Xor.isAllOnesValue()) return 0;
4644
4645   if (V1 == A || V1 == B) {
4646     Instruction *NewOp =
4647       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4648     return BinaryOperator::CreateOr(NewOp, V1);
4649   }
4650
4651   return 0;
4652 }
4653
4654 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4655   bool Changed = SimplifyCommutative(I);
4656   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4657
4658   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4659     return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4660
4661   // or X, X = X
4662   if (Op0 == Op1)
4663     return ReplaceInstUsesWith(I, Op0);
4664
4665   // See if we can simplify any instructions used by the instruction whose sole 
4666   // purpose is to compute bits we don't care about.
4667   if (SimplifyDemandedInstructionBits(I))
4668     return &I;
4669   if (isa<VectorType>(I.getType())) {
4670     if (isa<ConstantAggregateZero>(Op1)) {
4671       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4672     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4673       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4674         return ReplaceInstUsesWith(I, I.getOperand(1));
4675     }
4676   }
4677
4678   // or X, -1 == -1
4679   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4680     ConstantInt *C1 = 0; Value *X = 0;
4681     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4682     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) && 
4683         isOnlyUse(Op0)) {
4684       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4685       InsertNewInstBefore(Or, I);
4686       Or->takeName(Op0);
4687       return BinaryOperator::CreateAnd(Or, 
4688                Context->getConstantInt(RHS->getValue() | C1->getValue()));
4689     }
4690
4691     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4692     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) && 
4693         isOnlyUse(Op0)) {
4694       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4695       InsertNewInstBefore(Or, I);
4696       Or->takeName(Op0);
4697       return BinaryOperator::CreateXor(Or,
4698                  Context->getConstantInt(C1->getValue() & ~RHS->getValue()));
4699     }
4700
4701     // Try to fold constant and into select arguments.
4702     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4703       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4704         return R;
4705     if (isa<PHINode>(Op0))
4706       if (Instruction *NV = FoldOpIntoPhi(I))
4707         return NV;
4708   }
4709
4710   Value *A = 0, *B = 0;
4711   ConstantInt *C1 = 0, *C2 = 0;
4712
4713   if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
4714     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4715       return ReplaceInstUsesWith(I, Op1);
4716   if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
4717     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4718       return ReplaceInstUsesWith(I, Op0);
4719
4720   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4721   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4722   if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4723       match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4724       (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4725        match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
4726     if (Instruction *BSwap = MatchBSwap(I))
4727       return BSwap;
4728   }
4729   
4730   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4731   if (Op0->hasOneUse() &&
4732       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4733       MaskedValueIsZero(Op1, C1->getValue())) {
4734     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4735     InsertNewInstBefore(NOr, I);
4736     NOr->takeName(Op0);
4737     return BinaryOperator::CreateXor(NOr, C1);
4738   }
4739
4740   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4741   if (Op1->hasOneUse() &&
4742       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4743       MaskedValueIsZero(Op0, C1->getValue())) {
4744     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4745     InsertNewInstBefore(NOr, I);
4746     NOr->takeName(Op0);
4747     return BinaryOperator::CreateXor(NOr, C1);
4748   }
4749
4750   // (A & C)|(B & D)
4751   Value *C = 0, *D = 0;
4752   if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4753       match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
4754     Value *V1 = 0, *V2 = 0, *V3 = 0;
4755     C1 = dyn_cast<ConstantInt>(C);
4756     C2 = dyn_cast<ConstantInt>(D);
4757     if (C1 && C2) {  // (A & C1)|(B & C2)
4758       // If we have: ((V + N) & C1) | (V & C2)
4759       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4760       // replace with V+N.
4761       if (C1->getValue() == ~C2->getValue()) {
4762         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4763             match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4764           // Add commutes, try both ways.
4765           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4766             return ReplaceInstUsesWith(I, A);
4767           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4768             return ReplaceInstUsesWith(I, A);
4769         }
4770         // Or commutes, try both ways.
4771         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4772             match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4773           // Add commutes, try both ways.
4774           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4775             return ReplaceInstUsesWith(I, B);
4776           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4777             return ReplaceInstUsesWith(I, B);
4778         }
4779       }
4780       V1 = 0; V2 = 0; V3 = 0;
4781     }
4782     
4783     // Check to see if we have any common things being and'ed.  If so, find the
4784     // terms for V1 & (V2|V3).
4785     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4786       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4787         V1 = A, V2 = C, V3 = D;
4788       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4789         V1 = A, V2 = B, V3 = C;
4790       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4791         V1 = C, V2 = A, V3 = D;
4792       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4793         V1 = C, V2 = A, V3 = B;
4794       
4795       if (V1) {
4796         Value *Or =
4797           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4798         return BinaryOperator::CreateAnd(V1, Or);
4799       }
4800     }
4801
4802     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4803     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4804       return Match;
4805     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4806       return Match;
4807     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4808       return Match;
4809     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4810       return Match;
4811
4812     // ((A&~B)|(~A&B)) -> A^B
4813     if ((match(C, m_Not(m_Specific(D)), *Context) &&
4814          match(B, m_Not(m_Specific(A)), *Context)))
4815       return BinaryOperator::CreateXor(A, D);
4816     // ((~B&A)|(~A&B)) -> A^B
4817     if ((match(A, m_Not(m_Specific(D)), *Context) &&
4818          match(B, m_Not(m_Specific(C)), *Context)))
4819       return BinaryOperator::CreateXor(C, D);
4820     // ((A&~B)|(B&~A)) -> A^B
4821     if ((match(C, m_Not(m_Specific(B)), *Context) &&
4822          match(D, m_Not(m_Specific(A)), *Context)))
4823       return BinaryOperator::CreateXor(A, B);
4824     // ((~B&A)|(B&~A)) -> A^B
4825     if ((match(A, m_Not(m_Specific(B)), *Context) &&
4826          match(D, m_Not(m_Specific(C)), *Context)))
4827       return BinaryOperator::CreateXor(C, B);
4828   }
4829   
4830   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4831   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4832     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4833       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4834           SI0->getOperand(1) == SI1->getOperand(1) &&
4835           (SI0->hasOneUse() || SI1->hasOneUse())) {
4836         Instruction *NewOp =
4837         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4838                                                      SI1->getOperand(0),
4839                                                      SI0->getName()), I);
4840         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4841                                       SI1->getOperand(1));
4842       }
4843   }
4844
4845   // ((A|B)&1)|(B&-2) -> (A&1) | B
4846   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4847       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4848     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4849     if (Ret) return Ret;
4850   }
4851   // (B&-2)|((A|B)&1) -> (A&1) | B
4852   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4853       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4854     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4855     if (Ret) return Ret;
4856   }
4857
4858   if (match(Op0, m_Not(m_Value(A)), *Context)) {   // ~A | Op1
4859     if (A == Op1)   // ~A | A == -1
4860       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4861   } else {
4862     A = 0;
4863   }
4864   // Note, A is still live here!
4865   if (match(Op1, m_Not(m_Value(B)), *Context)) {   // Op0 | ~B
4866     if (Op0 == B)
4867       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4868
4869     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4870     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4871       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4872                                               I.getName()+".demorgan"), I);
4873       return BinaryOperator::CreateNot(*Context, And);
4874     }
4875   }
4876
4877   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4878   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4879     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4880       return R;
4881
4882     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4883       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4884         return Res;
4885   }
4886     
4887   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4888   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4889     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4890       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4891         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4892             !isa<ICmpInst>(Op1C->getOperand(0))) {
4893           const Type *SrcTy = Op0C->getOperand(0)->getType();
4894           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4895               // Only do this if the casts both really cause code to be
4896               // generated.
4897               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4898                                 I.getType(), TD) &&
4899               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4900                                 I.getType(), TD)) {
4901             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4902                                                           Op1C->getOperand(0),
4903                                                           I.getName());
4904             InsertNewInstBefore(NewOp, I);
4905             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4906           }
4907         }
4908       }
4909   }
4910   
4911     
4912   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4913   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4914     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4915       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4916           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4917           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4918         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4919           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4920             // If either of the constants are nans, then the whole thing returns
4921             // true.
4922             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4923               return ReplaceInstUsesWith(I, Context->getTrue());
4924             
4925             // Otherwise, no need to compare the two constants, compare the
4926             // rest.
4927             return new FCmpInst(*Context, FCmpInst::FCMP_UNO, 
4928                                 LHS->getOperand(0), RHS->getOperand(0));
4929           }
4930       } else {
4931         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4932         FCmpInst::Predicate Op0CC, Op1CC;
4933         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4934                   m_Value(Op0RHS)), *Context) &&
4935             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4936                   m_Value(Op1RHS)), *Context)) {
4937           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4938             // Swap RHS operands to match LHS.
4939             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4940             std::swap(Op1LHS, Op1RHS);
4941           }
4942           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4943             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4944             if (Op0CC == Op1CC)
4945               return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4946                                   Op0LHS, Op0RHS);
4947             else if (Op0CC == FCmpInst::FCMP_TRUE ||
4948                      Op1CC == FCmpInst::FCMP_TRUE)
4949               return ReplaceInstUsesWith(I, Context->getTrue());
4950             else if (Op0CC == FCmpInst::FCMP_FALSE)
4951               return ReplaceInstUsesWith(I, Op1);
4952             else if (Op1CC == FCmpInst::FCMP_FALSE)
4953               return ReplaceInstUsesWith(I, Op0);
4954             bool Op0Ordered;
4955             bool Op1Ordered;
4956             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4957             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4958             if (Op0Ordered == Op1Ordered) {
4959               // If both are ordered or unordered, return a new fcmp with
4960               // or'ed predicates.
4961               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4962                                        Op0LHS, Op0RHS, Context);
4963               if (Instruction *I = dyn_cast<Instruction>(RV))
4964                 return I;
4965               // Otherwise, it's a constant boolean value...
4966               return ReplaceInstUsesWith(I, RV);
4967             }
4968           }
4969         }
4970       }
4971     }
4972   }
4973
4974   return Changed ? &I : 0;
4975 }
4976
4977 namespace {
4978
4979 // XorSelf - Implements: X ^ X --> 0
4980 struct XorSelf {
4981   Value *RHS;
4982   XorSelf(Value *rhs) : RHS(rhs) {}
4983   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4984   Instruction *apply(BinaryOperator &Xor) const {
4985     return &Xor;
4986   }
4987 };
4988
4989 }
4990
4991 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4992   bool Changed = SimplifyCommutative(I);
4993   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4994
4995   if (isa<UndefValue>(Op1)) {
4996     if (isa<UndefValue>(Op0))
4997       // Handle undef ^ undef -> 0 special case. This is a common
4998       // idiom (misuse).
4999       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5000     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5001   }
5002
5003   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5004   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
5005     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5006     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5007   }
5008   
5009   // See if we can simplify any instructions used by the instruction whose sole 
5010   // purpose is to compute bits we don't care about.
5011   if (SimplifyDemandedInstructionBits(I))
5012     return &I;
5013   if (isa<VectorType>(I.getType()))
5014     if (isa<ConstantAggregateZero>(Op1))
5015       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5016
5017   // Is this a ~ operation?
5018   if (Value *NotOp = dyn_castNotVal(&I, Context)) {
5019     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5020     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5021     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5022       if (Op0I->getOpcode() == Instruction::And || 
5023           Op0I->getOpcode() == Instruction::Or) {
5024         if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5025         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
5026           Instruction *NotY =
5027             BinaryOperator::CreateNot(*Context, Op0I->getOperand(1),
5028                                       Op0I->getOperand(1)->getName()+".not");
5029           InsertNewInstBefore(NotY, I);
5030           if (Op0I->getOpcode() == Instruction::And)
5031             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5032           else
5033             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5034         }
5035       }
5036     }
5037   }
5038   
5039   
5040   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5041     if (RHS == Context->getTrue() && Op0->hasOneUse()) {
5042       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5043       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5044         return new ICmpInst(*Context, ICI->getInversePredicate(),
5045                             ICI->getOperand(0), ICI->getOperand(1));
5046
5047       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5048         return new FCmpInst(*Context, FCI->getInversePredicate(),
5049                             FCI->getOperand(0), FCI->getOperand(1));
5050     }
5051
5052     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5053     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5054       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5055         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5056           Instruction::CastOps Opcode = Op0C->getOpcode();
5057           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5058             if (RHS == Context->getConstantExprCast(Opcode, 
5059                                              Context->getTrue(),
5060                                              Op0C->getDestTy())) {
5061               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5062                                      *Context,
5063                                      CI->getOpcode(), CI->getInversePredicate(),
5064                                      CI->getOperand(0), CI->getOperand(1)), I);
5065               NewCI->takeName(CI);
5066               return CastInst::Create(Opcode, NewCI, Op0C->getType());
5067             }
5068           }
5069         }
5070       }
5071     }
5072
5073     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5074       // ~(c-X) == X-c-1 == X+(-c-1)
5075       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5076         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5077           Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5078           Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
5079                                       Context->getConstantInt(I.getType(), 1));
5080           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5081         }
5082           
5083       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5084         if (Op0I->getOpcode() == Instruction::Add) {
5085           // ~(X-c) --> (-c-1)-X
5086           if (RHS->isAllOnesValue()) {
5087             Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
5088             return BinaryOperator::CreateSub(
5089                            Context->getConstantExprSub(NegOp0CI,
5090                                       Context->getConstantInt(I.getType(), 1)),
5091                                       Op0I->getOperand(0));
5092           } else if (RHS->getValue().isSignBit()) {
5093             // (X + C) ^ signbit -> (X + C + signbit)
5094             Constant *C =
5095                    Context->getConstantInt(RHS->getValue() + Op0CI->getValue());
5096             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5097
5098           }
5099         } else if (Op0I->getOpcode() == Instruction::Or) {
5100           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5101           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5102             Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
5103             // Anything in both C1 and C2 is known to be zero, remove it from
5104             // NewRHS.
5105             Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5106             NewRHS = Context->getConstantExprAnd(NewRHS, 
5107                                        Context->getConstantExprNot(CommonBits));
5108             AddToWorkList(Op0I);
5109             I.setOperand(0, Op0I->getOperand(0));
5110             I.setOperand(1, NewRHS);
5111             return &I;
5112           }
5113         }
5114       }
5115     }
5116
5117     // Try to fold constant and into select arguments.
5118     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5119       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5120         return R;
5121     if (isa<PHINode>(Op0))
5122       if (Instruction *NV = FoldOpIntoPhi(I))
5123         return NV;
5124   }
5125
5126   if (Value *X = dyn_castNotVal(Op0, Context))   // ~A ^ A == -1
5127     if (X == Op1)
5128       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5129
5130   if (Value *X = dyn_castNotVal(Op1, Context))   // A ^ ~A == -1
5131     if (X == Op0)
5132       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5133
5134   
5135   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5136   if (Op1I) {
5137     Value *A, *B;
5138     if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
5139       if (A == Op0) {              // B^(B|A) == (A|B)^B
5140         Op1I->swapOperands();
5141         I.swapOperands();
5142         std::swap(Op0, Op1);
5143       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5144         I.swapOperands();     // Simplified below.
5145         std::swap(Op0, Op1);
5146       }
5147     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
5148       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5149     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
5150       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5151     } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) && 
5152                Op1I->hasOneUse()){
5153       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5154         Op1I->swapOperands();
5155         std::swap(A, B);
5156       }
5157       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5158         I.swapOperands();     // Simplified below.
5159         std::swap(Op0, Op1);
5160       }
5161     }
5162   }
5163   
5164   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5165   if (Op0I) {
5166     Value *A, *B;
5167     if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5168         Op0I->hasOneUse()) {
5169       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5170         std::swap(A, B);
5171       if (B == Op1) {                                // (A|B)^B == A & ~B
5172         Instruction *NotB =
5173           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, 
5174                                                         Op1, "tmp"), I);
5175         return BinaryOperator::CreateAnd(A, NotB);
5176       }
5177     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
5178       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5179     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
5180       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5181     } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) && 
5182                Op0I->hasOneUse()){
5183       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5184         std::swap(A, B);
5185       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5186           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5187         Instruction *N =
5188           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, A, "tmp"), I);
5189         return BinaryOperator::CreateAnd(N, Op1);
5190       }
5191     }
5192   }
5193   
5194   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5195   if (Op0I && Op1I && Op0I->isShift() && 
5196       Op0I->getOpcode() == Op1I->getOpcode() && 
5197       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5198       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5199     Instruction *NewOp =
5200       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5201                                                     Op1I->getOperand(0),
5202                                                     Op0I->getName()), I);
5203     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5204                                   Op1I->getOperand(1));
5205   }
5206     
5207   if (Op0I && Op1I) {
5208     Value *A, *B, *C, *D;
5209     // (A & B)^(A | B) -> A ^ B
5210     if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5211         match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
5212       if ((A == C && B == D) || (A == D && B == C)) 
5213         return BinaryOperator::CreateXor(A, B);
5214     }
5215     // (A | B)^(A & B) -> A ^ B
5216     if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5217         match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5218       if ((A == C && B == D) || (A == D && B == C)) 
5219         return BinaryOperator::CreateXor(A, B);
5220     }
5221     
5222     // (A & B)^(C & D)
5223     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5224         match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5225         match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5226       // (X & Y)^(X & Y) -> (Y^Z) & X
5227       Value *X = 0, *Y = 0, *Z = 0;
5228       if (A == C)
5229         X = A, Y = B, Z = D;
5230       else if (A == D)
5231         X = A, Y = B, Z = C;
5232       else if (B == C)
5233         X = B, Y = A, Z = D;
5234       else if (B == D)
5235         X = B, Y = A, Z = C;
5236       
5237       if (X) {
5238         Instruction *NewOp =
5239         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5240         return BinaryOperator::CreateAnd(NewOp, X);
5241       }
5242     }
5243   }
5244     
5245   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5246   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5247     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
5248       return R;
5249
5250   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5251   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5252     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5253       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5254         const Type *SrcTy = Op0C->getOperand(0)->getType();
5255         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5256             // Only do this if the casts both really cause code to be generated.
5257             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5258                               I.getType(), TD) &&
5259             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5260                               I.getType(), TD)) {
5261           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5262                                                          Op1C->getOperand(0),
5263                                                          I.getName());
5264           InsertNewInstBefore(NewOp, I);
5265           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5266         }
5267       }
5268   }
5269
5270   return Changed ? &I : 0;
5271 }
5272
5273 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5274                                    LLVMContext *Context) {
5275   return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
5276 }
5277
5278 static bool HasAddOverflow(ConstantInt *Result,
5279                            ConstantInt *In1, ConstantInt *In2,
5280                            bool IsSigned) {
5281   if (IsSigned)
5282     if (In2->getValue().isNegative())
5283       return Result->getValue().sgt(In1->getValue());
5284     else
5285       return Result->getValue().slt(In1->getValue());
5286   else
5287     return Result->getValue().ult(In1->getValue());
5288 }
5289
5290 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5291 /// overflowed for this type.
5292 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5293                             Constant *In2, LLVMContext *Context,
5294                             bool IsSigned = false) {
5295   Result = Context->getConstantExprAdd(In1, In2);
5296
5297   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5298     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5299       Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5300       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5301                          ExtractElement(In1, Idx, Context),
5302                          ExtractElement(In2, Idx, Context),
5303                          IsSigned))
5304         return true;
5305     }
5306     return false;
5307   }
5308
5309   return HasAddOverflow(cast<ConstantInt>(Result),
5310                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5311                         IsSigned);
5312 }
5313
5314 static bool HasSubOverflow(ConstantInt *Result,
5315                            ConstantInt *In1, ConstantInt *In2,
5316                            bool IsSigned) {
5317   if (IsSigned)
5318     if (In2->getValue().isNegative())
5319       return Result->getValue().slt(In1->getValue());
5320     else
5321       return Result->getValue().sgt(In1->getValue());
5322   else
5323     return Result->getValue().ugt(In1->getValue());
5324 }
5325
5326 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5327 /// overflowed for this type.
5328 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5329                             Constant *In2, LLVMContext *Context,
5330                             bool IsSigned = false) {
5331   Result = Context->getConstantExprSub(In1, In2);
5332
5333   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5334     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5335       Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5336       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5337                          ExtractElement(In1, Idx, Context),
5338                          ExtractElement(In2, Idx, Context),
5339                          IsSigned))
5340         return true;
5341     }
5342     return false;
5343   }
5344
5345   return HasSubOverflow(cast<ConstantInt>(Result),
5346                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5347                         IsSigned);
5348 }
5349
5350 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5351 /// code necessary to compute the offset from the base pointer (without adding
5352 /// in the base pointer).  Return the result as a signed integer of intptr size.
5353 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5354   TargetData &TD = *IC.getTargetData();
5355   gep_type_iterator GTI = gep_type_begin(GEP);
5356   const Type *IntPtrTy = TD.getIntPtrType();
5357   LLVMContext *Context = IC.getContext();
5358   Value *Result = Context->getNullValue(IntPtrTy);
5359
5360   // Build a mask for high order bits.
5361   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5362   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5363
5364   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5365        ++i, ++GTI) {
5366     Value *Op = *i;
5367     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5368     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5369       if (OpC->isZero()) continue;
5370       
5371       // Handle a struct index, which adds its field offset to the pointer.
5372       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5373         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5374         
5375         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5376           Result = 
5377              Context->getConstantInt(RC->getValue() + APInt(IntPtrWidth, Size));
5378         else
5379           Result = IC.InsertNewInstBefore(
5380                    BinaryOperator::CreateAdd(Result,
5381                                         Context->getConstantInt(IntPtrTy, Size),
5382                                              GEP->getName()+".offs"), I);
5383         continue;
5384       }
5385       
5386       Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5387       Constant *OC =
5388               Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5389       Scale = Context->getConstantExprMul(OC, Scale);
5390       if (Constant *RC = dyn_cast<Constant>(Result))
5391         Result = Context->getConstantExprAdd(RC, Scale);
5392       else {
5393         // Emit an add instruction.
5394         Result = IC.InsertNewInstBefore(
5395            BinaryOperator::CreateAdd(Result, Scale,
5396                                      GEP->getName()+".offs"), I);
5397       }
5398       continue;
5399     }
5400     // Convert to correct type.
5401     if (Op->getType() != IntPtrTy) {
5402       if (Constant *OpC = dyn_cast<Constant>(Op))
5403         Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
5404       else
5405         Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5406                                                                 true,
5407                                                       Op->getName()+".c"), I);
5408     }
5409     if (Size != 1) {
5410       Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5411       if (Constant *OpC = dyn_cast<Constant>(Op))
5412         Op = Context->getConstantExprMul(OpC, Scale);
5413       else    // We'll let instcombine(mul) convert this to a shl if possible.
5414         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5415                                                   GEP->getName()+".idx"), I);
5416     }
5417
5418     // Emit an add instruction.
5419     if (isa<Constant>(Op) && isa<Constant>(Result))
5420       Result = Context->getConstantExprAdd(cast<Constant>(Op),
5421                                     cast<Constant>(Result));
5422     else
5423       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5424                                                   GEP->getName()+".offs"), I);
5425   }
5426   return Result;
5427 }
5428
5429
5430 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5431 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
5432 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
5433 /// be complex, and scales are involved.  The above expression would also be
5434 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5435 /// This later form is less amenable to optimization though, and we are allowed
5436 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5437 ///
5438 /// If we can't emit an optimized form for this expression, this returns null.
5439 /// 
5440 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5441                                           InstCombiner &IC) {
5442   TargetData &TD = *IC.getTargetData();
5443   gep_type_iterator GTI = gep_type_begin(GEP);
5444
5445   // Check to see if this gep only has a single variable index.  If so, and if
5446   // any constant indices are a multiple of its scale, then we can compute this
5447   // in terms of the scale of the variable index.  For example, if the GEP
5448   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5449   // because the expression will cross zero at the same point.
5450   unsigned i, e = GEP->getNumOperands();
5451   int64_t Offset = 0;
5452   for (i = 1; i != e; ++i, ++GTI) {
5453     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5454       // Compute the aggregate offset of constant indices.
5455       if (CI->isZero()) continue;
5456
5457       // Handle a struct index, which adds its field offset to the pointer.
5458       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5459         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5460       } else {
5461         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5462         Offset += Size*CI->getSExtValue();
5463       }
5464     } else {
5465       // Found our variable index.
5466       break;
5467     }
5468   }
5469   
5470   // If there are no variable indices, we must have a constant offset, just
5471   // evaluate it the general way.
5472   if (i == e) return 0;
5473   
5474   Value *VariableIdx = GEP->getOperand(i);
5475   // Determine the scale factor of the variable element.  For example, this is
5476   // 4 if the variable index is into an array of i32.
5477   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5478   
5479   // Verify that there are no other variable indices.  If so, emit the hard way.
5480   for (++i, ++GTI; i != e; ++i, ++GTI) {
5481     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5482     if (!CI) return 0;
5483    
5484     // Compute the aggregate offset of constant indices.
5485     if (CI->isZero()) continue;
5486     
5487     // Handle a struct index, which adds its field offset to the pointer.
5488     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5489       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5490     } else {
5491       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5492       Offset += Size*CI->getSExtValue();
5493     }
5494   }
5495   
5496   // Okay, we know we have a single variable index, which must be a
5497   // pointer/array/vector index.  If there is no offset, life is simple, return
5498   // the index.
5499   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5500   if (Offset == 0) {
5501     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5502     // we don't need to bother extending: the extension won't affect where the
5503     // computation crosses zero.
5504     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5505       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5506                                   VariableIdx->getNameStart(), &I);
5507     return VariableIdx;
5508   }
5509   
5510   // Otherwise, there is an index.  The computation we will do will be modulo
5511   // the pointer size, so get it.
5512   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5513   
5514   Offset &= PtrSizeMask;
5515   VariableScale &= PtrSizeMask;
5516
5517   // To do this transformation, any constant index must be a multiple of the
5518   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5519   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5520   // multiple of the variable scale.
5521   int64_t NewOffs = Offset / (int64_t)VariableScale;
5522   if (Offset != NewOffs*(int64_t)VariableScale)
5523     return 0;
5524
5525   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5526   const Type *IntPtrTy = TD.getIntPtrType();
5527   if (VariableIdx->getType() != IntPtrTy)
5528     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5529                                               true /*SExt*/, 
5530                                               VariableIdx->getNameStart(), &I);
5531   Constant *OffsetVal = IC.getContext()->getConstantInt(IntPtrTy, NewOffs);
5532   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5533 }
5534
5535
5536 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5537 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5538 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5539                                        ICmpInst::Predicate Cond,
5540                                        Instruction &I) {
5541   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5542
5543   // Look through bitcasts.
5544   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5545     RHS = BCI->getOperand(0);
5546
5547   Value *PtrBase = GEPLHS->getOperand(0);
5548   if (TD && PtrBase == RHS) {
5549     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5550     // This transformation (ignoring the base and scales) is valid because we
5551     // know pointers can't overflow.  See if we can output an optimized form.
5552     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5553     
5554     // If not, synthesize the offset the hard way.
5555     if (Offset == 0)
5556       Offset = EmitGEPOffset(GEPLHS, I, *this);
5557     return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
5558                         Context->getNullValue(Offset->getType()));
5559   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5560     // If the base pointers are different, but the indices are the same, just
5561     // compare the base pointer.
5562     if (PtrBase != GEPRHS->getOperand(0)) {
5563       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5564       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5565                         GEPRHS->getOperand(0)->getType();
5566       if (IndicesTheSame)
5567         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5568           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5569             IndicesTheSame = false;
5570             break;
5571           }
5572
5573       // If all indices are the same, just compare the base pointers.
5574       if (IndicesTheSame)
5575         return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), 
5576                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5577
5578       // Otherwise, the base pointers are different and the indices are
5579       // different, bail out.
5580       return 0;
5581     }
5582
5583     // If one of the GEPs has all zero indices, recurse.
5584     bool AllZeros = true;
5585     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5586       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5587           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5588         AllZeros = false;
5589         break;
5590       }
5591     if (AllZeros)
5592       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5593                           ICmpInst::getSwappedPredicate(Cond), I);
5594
5595     // If the other GEP has all zero indices, recurse.
5596     AllZeros = true;
5597     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5598       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5599           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5600         AllZeros = false;
5601         break;
5602       }
5603     if (AllZeros)
5604       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5605
5606     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5607       // If the GEPs only differ by one index, compare it.
5608       unsigned NumDifferences = 0;  // Keep track of # differences.
5609       unsigned DiffOperand = 0;     // The operand that differs.
5610       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5611         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5612           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5613                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5614             // Irreconcilable differences.
5615             NumDifferences = 2;
5616             break;
5617           } else {
5618             if (NumDifferences++) break;
5619             DiffOperand = i;
5620           }
5621         }
5622
5623       if (NumDifferences == 0)   // SAME GEP?
5624         return ReplaceInstUsesWith(I, // No comparison is needed here.
5625                                    Context->getConstantInt(Type::Int1Ty,
5626                                              ICmpInst::isTrueWhenEqual(Cond)));
5627
5628       else if (NumDifferences == 1) {
5629         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5630         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5631         // Make sure we do a signed comparison here.
5632         return new ICmpInst(*Context,
5633                             ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5634       }
5635     }
5636
5637     // Only lower this if the icmp is the only user of the GEP or if we expect
5638     // the result to fold to a constant!
5639     if (TD &&
5640         (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5641         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5642       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5643       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5644       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5645       return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
5646     }
5647   }
5648   return 0;
5649 }
5650
5651 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5652 ///
5653 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5654                                                 Instruction *LHSI,
5655                                                 Constant *RHSC) {
5656   if (!isa<ConstantFP>(RHSC)) return 0;
5657   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5658   
5659   // Get the width of the mantissa.  We don't want to hack on conversions that
5660   // might lose information from the integer, e.g. "i64 -> float"
5661   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5662   if (MantissaWidth == -1) return 0;  // Unknown.
5663   
5664   // Check to see that the input is converted from an integer type that is small
5665   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5666   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5667   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5668   
5669   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5670   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5671   if (LHSUnsigned)
5672     ++InputSize;
5673   
5674   // If the conversion would lose info, don't hack on this.
5675   if ((int)InputSize > MantissaWidth)
5676     return 0;
5677   
5678   // Otherwise, we can potentially simplify the comparison.  We know that it
5679   // will always come through as an integer value and we know the constant is
5680   // not a NAN (it would have been previously simplified).
5681   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5682   
5683   ICmpInst::Predicate Pred;
5684   switch (I.getPredicate()) {
5685   default: llvm_unreachable("Unexpected predicate!");
5686   case FCmpInst::FCMP_UEQ:
5687   case FCmpInst::FCMP_OEQ:
5688     Pred = ICmpInst::ICMP_EQ;
5689     break;
5690   case FCmpInst::FCMP_UGT:
5691   case FCmpInst::FCMP_OGT:
5692     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5693     break;
5694   case FCmpInst::FCMP_UGE:
5695   case FCmpInst::FCMP_OGE:
5696     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5697     break;
5698   case FCmpInst::FCMP_ULT:
5699   case FCmpInst::FCMP_OLT:
5700     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5701     break;
5702   case FCmpInst::FCMP_ULE:
5703   case FCmpInst::FCMP_OLE:
5704     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5705     break;
5706   case FCmpInst::FCMP_UNE:
5707   case FCmpInst::FCMP_ONE:
5708     Pred = ICmpInst::ICMP_NE;
5709     break;
5710   case FCmpInst::FCMP_ORD:
5711     return ReplaceInstUsesWith(I, Context->getTrue());
5712   case FCmpInst::FCMP_UNO:
5713     return ReplaceInstUsesWith(I, Context->getFalse());
5714   }
5715   
5716   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5717   
5718   // Now we know that the APFloat is a normal number, zero or inf.
5719   
5720   // See if the FP constant is too large for the integer.  For example,
5721   // comparing an i8 to 300.0.
5722   unsigned IntWidth = IntTy->getScalarSizeInBits();
5723   
5724   if (!LHSUnsigned) {
5725     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5726     // and large values.
5727     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5728     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5729                           APFloat::rmNearestTiesToEven);
5730     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5731       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5732           Pred == ICmpInst::ICMP_SLE)
5733         return ReplaceInstUsesWith(I, Context->getTrue());
5734       return ReplaceInstUsesWith(I, Context->getFalse());
5735     }
5736   } else {
5737     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5738     // +INF and large values.
5739     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5740     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5741                           APFloat::rmNearestTiesToEven);
5742     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5743       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5744           Pred == ICmpInst::ICMP_ULE)
5745         return ReplaceInstUsesWith(I, Context->getTrue());
5746       return ReplaceInstUsesWith(I, Context->getFalse());
5747     }
5748   }
5749   
5750   if (!LHSUnsigned) {
5751     // See if the RHS value is < SignedMin.
5752     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5753     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5754                           APFloat::rmNearestTiesToEven);
5755     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5756       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5757           Pred == ICmpInst::ICMP_SGE)
5758         return ReplaceInstUsesWith(I, Context->getTrue());
5759       return ReplaceInstUsesWith(I, Context->getFalse());
5760     }
5761   }
5762
5763   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5764   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5765   // casting the FP value to the integer value and back, checking for equality.
5766   // Don't do this for zero, because -0.0 is not fractional.
5767   Constant *RHSInt = LHSUnsigned
5768     ? Context->getConstantExprFPToUI(RHSC, IntTy)
5769     : Context->getConstantExprFPToSI(RHSC, IntTy);
5770   if (!RHS.isZero()) {
5771     bool Equal = LHSUnsigned
5772       ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5773       : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
5774     if (!Equal) {
5775       // If we had a comparison against a fractional value, we have to adjust
5776       // the compare predicate and sometimes the value.  RHSC is rounded towards
5777       // zero at this point.
5778       switch (Pred) {
5779       default: llvm_unreachable("Unexpected integer comparison!");
5780       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5781         return ReplaceInstUsesWith(I, Context->getTrue());
5782       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5783         return ReplaceInstUsesWith(I, Context->getFalse());
5784       case ICmpInst::ICMP_ULE:
5785         // (float)int <= 4.4   --> int <= 4
5786         // (float)int <= -4.4  --> false
5787         if (RHS.isNegative())
5788           return ReplaceInstUsesWith(I, Context->getFalse());
5789         break;
5790       case ICmpInst::ICMP_SLE:
5791         // (float)int <= 4.4   --> int <= 4
5792         // (float)int <= -4.4  --> int < -4
5793         if (RHS.isNegative())
5794           Pred = ICmpInst::ICMP_SLT;
5795         break;
5796       case ICmpInst::ICMP_ULT:
5797         // (float)int < -4.4   --> false
5798         // (float)int < 4.4    --> int <= 4
5799         if (RHS.isNegative())
5800           return ReplaceInstUsesWith(I, Context->getFalse());
5801         Pred = ICmpInst::ICMP_ULE;
5802         break;
5803       case ICmpInst::ICMP_SLT:
5804         // (float)int < -4.4   --> int < -4
5805         // (float)int < 4.4    --> int <= 4
5806         if (!RHS.isNegative())
5807           Pred = ICmpInst::ICMP_SLE;
5808         break;
5809       case ICmpInst::ICMP_UGT:
5810         // (float)int > 4.4    --> int > 4
5811         // (float)int > -4.4   --> true
5812         if (RHS.isNegative())
5813           return ReplaceInstUsesWith(I, Context->getTrue());
5814         break;
5815       case ICmpInst::ICMP_SGT:
5816         // (float)int > 4.4    --> int > 4
5817         // (float)int > -4.4   --> int >= -4
5818         if (RHS.isNegative())
5819           Pred = ICmpInst::ICMP_SGE;
5820         break;
5821       case ICmpInst::ICMP_UGE:
5822         // (float)int >= -4.4   --> true
5823         // (float)int >= 4.4    --> int > 4
5824         if (!RHS.isNegative())
5825           return ReplaceInstUsesWith(I, Context->getTrue());
5826         Pred = ICmpInst::ICMP_UGT;
5827         break;
5828       case ICmpInst::ICMP_SGE:
5829         // (float)int >= -4.4   --> int >= -4
5830         // (float)int >= 4.4    --> int > 4
5831         if (!RHS.isNegative())
5832           Pred = ICmpInst::ICMP_SGT;
5833         break;
5834       }
5835     }
5836   }
5837
5838   // Lower this FP comparison into an appropriate integer version of the
5839   // comparison.
5840   return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
5841 }
5842
5843 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5844   bool Changed = SimplifyCompare(I);
5845   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5846
5847   // Fold trivial predicates.
5848   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5849     return ReplaceInstUsesWith(I, Context->getFalse());
5850   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5851     return ReplaceInstUsesWith(I, Context->getTrue());
5852   
5853   // Simplify 'fcmp pred X, X'
5854   if (Op0 == Op1) {
5855     switch (I.getPredicate()) {
5856     default: llvm_unreachable("Unknown predicate!");
5857     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5858     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5859     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5860       return ReplaceInstUsesWith(I, Context->getTrue());
5861     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5862     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5863     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5864       return ReplaceInstUsesWith(I, Context->getFalse());
5865       
5866     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5867     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5868     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5869     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5870       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5871       I.setPredicate(FCmpInst::FCMP_UNO);
5872       I.setOperand(1, Context->getNullValue(Op0->getType()));
5873       return &I;
5874       
5875     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5876     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5877     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5878     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5879       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5880       I.setPredicate(FCmpInst::FCMP_ORD);
5881       I.setOperand(1, Context->getNullValue(Op0->getType()));
5882       return &I;
5883     }
5884   }
5885     
5886   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5887     return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5888
5889   // Handle fcmp with constant RHS
5890   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5891     // If the constant is a nan, see if we can fold the comparison based on it.
5892     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5893       if (CFP->getValueAPF().isNaN()) {
5894         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5895           return ReplaceInstUsesWith(I, Context->getFalse());
5896         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5897                "Comparison must be either ordered or unordered!");
5898         // True if unordered.
5899         return ReplaceInstUsesWith(I, Context->getTrue());
5900       }
5901     }
5902     
5903     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5904       switch (LHSI->getOpcode()) {
5905       case Instruction::PHI:
5906         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5907         // block.  If in the same block, we're encouraging jump threading.  If
5908         // not, we are just pessimizing the code by making an i1 phi.
5909         if (LHSI->getParent() == I.getParent())
5910           if (Instruction *NV = FoldOpIntoPhi(I))
5911             return NV;
5912         break;
5913       case Instruction::SIToFP:
5914       case Instruction::UIToFP:
5915         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5916           return NV;
5917         break;
5918       case Instruction::Select:
5919         // If either operand of the select is a constant, we can fold the
5920         // comparison into the select arms, which will cause one to be
5921         // constant folded and the select turned into a bitwise or.
5922         Value *Op1 = 0, *Op2 = 0;
5923         if (LHSI->hasOneUse()) {
5924           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5925             // Fold the known value into the constant operand.
5926             Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5927             // Insert a new FCmp of the other select operand.
5928             Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5929                                                       LHSI->getOperand(2), RHSC,
5930                                                       I.getName()), I);
5931           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5932             // Fold the known value into the constant operand.
5933             Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5934             // Insert a new FCmp of the other select operand.
5935             Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5936                                                       LHSI->getOperand(1), RHSC,
5937                                                       I.getName()), I);
5938           }
5939         }
5940
5941         if (Op1)
5942           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5943         break;
5944       }
5945   }
5946
5947   return Changed ? &I : 0;
5948 }
5949
5950 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5951   bool Changed = SimplifyCompare(I);
5952   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5953   const Type *Ty = Op0->getType();
5954
5955   // icmp X, X
5956   if (Op0 == Op1)
5957     return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty, 
5958                                                    I.isTrueWhenEqual()));
5959
5960   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5961     return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5962   
5963   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5964   // addresses never equal each other!  We already know that Op0 != Op1.
5965   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5966        isa<ConstantPointerNull>(Op0)) &&
5967       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5968        isa<ConstantPointerNull>(Op1)))
5969     return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty, 
5970                                                    !I.isTrueWhenEqual()));
5971
5972   // icmp's with boolean values can always be turned into bitwise operations
5973   if (Ty == Type::Int1Ty) {
5974     switch (I.getPredicate()) {
5975     default: llvm_unreachable("Invalid icmp instruction!");
5976     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5977       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5978       InsertNewInstBefore(Xor, I);
5979       return BinaryOperator::CreateNot(*Context, Xor);
5980     }
5981     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5982       return BinaryOperator::CreateXor(Op0, Op1);
5983
5984     case ICmpInst::ICMP_UGT:
5985       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5986       // FALL THROUGH
5987     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5988       Instruction *Not = BinaryOperator::CreateNot(*Context,
5989                                                    Op0, I.getName()+"tmp");
5990       InsertNewInstBefore(Not, I);
5991       return BinaryOperator::CreateAnd(Not, Op1);
5992     }
5993     case ICmpInst::ICMP_SGT:
5994       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5995       // FALL THROUGH
5996     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5997       Instruction *Not = BinaryOperator::CreateNot(*Context, 
5998                                                    Op1, I.getName()+"tmp");
5999       InsertNewInstBefore(Not, I);
6000       return BinaryOperator::CreateAnd(Not, Op0);
6001     }
6002     case ICmpInst::ICMP_UGE:
6003       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6004       // FALL THROUGH
6005     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6006       Instruction *Not = BinaryOperator::CreateNot(*Context,
6007                                                    Op0, I.getName()+"tmp");
6008       InsertNewInstBefore(Not, I);
6009       return BinaryOperator::CreateOr(Not, Op1);
6010     }
6011     case ICmpInst::ICMP_SGE:
6012       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6013       // FALL THROUGH
6014     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6015       Instruction *Not = BinaryOperator::CreateNot(*Context,
6016                                                    Op1, I.getName()+"tmp");
6017       InsertNewInstBefore(Not, I);
6018       return BinaryOperator::CreateOr(Not, Op0);
6019     }
6020     }
6021   }
6022
6023   unsigned BitWidth = 0;
6024   if (TD)
6025     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6026   else if (Ty->isIntOrIntVector())
6027     BitWidth = Ty->getScalarSizeInBits();
6028
6029   bool isSignBit = false;
6030
6031   // See if we are doing a comparison with a constant.
6032   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6033     Value *A = 0, *B = 0;
6034     
6035     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6036     if (I.isEquality() && CI->isNullValue() &&
6037         match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
6038       // (icmp cond A B) if cond is equality
6039       return new ICmpInst(*Context, I.getPredicate(), A, B);
6040     }
6041     
6042     // If we have an icmp le or icmp ge instruction, turn it into the
6043     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6044     // them being folded in the code below.
6045     switch (I.getPredicate()) {
6046     default: break;
6047     case ICmpInst::ICMP_ULE:
6048       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
6049         return ReplaceInstUsesWith(I, Context->getTrue());
6050       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6051                           AddOne(CI, Context));
6052     case ICmpInst::ICMP_SLE:
6053       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
6054         return ReplaceInstUsesWith(I, Context->getTrue());
6055       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6056                           AddOne(CI, Context));
6057     case ICmpInst::ICMP_UGE:
6058       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
6059         return ReplaceInstUsesWith(I, Context->getTrue());
6060       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6061                           SubOne(CI, Context));
6062     case ICmpInst::ICMP_SGE:
6063       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
6064         return ReplaceInstUsesWith(I, Context->getTrue());
6065       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6066                           SubOne(CI, Context));
6067     }
6068     
6069     // If this comparison is a normal comparison, it demands all
6070     // bits, if it is a sign bit comparison, it only demands the sign bit.
6071     bool UnusedBit;
6072     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6073   }
6074
6075   // See if we can fold the comparison based on range information we can get
6076   // by checking whether bits are known to be zero or one in the input.
6077   if (BitWidth != 0) {
6078     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6079     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6080
6081     if (SimplifyDemandedBits(I.getOperandUse(0),
6082                              isSignBit ? APInt::getSignBit(BitWidth)
6083                                        : APInt::getAllOnesValue(BitWidth),
6084                              Op0KnownZero, Op0KnownOne, 0))
6085       return &I;
6086     if (SimplifyDemandedBits(I.getOperandUse(1),
6087                              APInt::getAllOnesValue(BitWidth),
6088                              Op1KnownZero, Op1KnownOne, 0))
6089       return &I;
6090
6091     // Given the known and unknown bits, compute a range that the LHS could be
6092     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6093     // EQ and NE we use unsigned values.
6094     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6095     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6096     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6097       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6098                                              Op0Min, Op0Max);
6099       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6100                                              Op1Min, Op1Max);
6101     } else {
6102       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6103                                                Op0Min, Op0Max);
6104       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6105                                                Op1Min, Op1Max);
6106     }
6107
6108     // If Min and Max are known to be the same, then SimplifyDemandedBits
6109     // figured out that the LHS is a constant.  Just constant fold this now so
6110     // that code below can assume that Min != Max.
6111     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6112       return new ICmpInst(*Context, I.getPredicate(),
6113                           Context->getConstantInt(Op0Min), Op1);
6114     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6115       return new ICmpInst(*Context, I.getPredicate(), Op0, 
6116                           Context->getConstantInt(Op1Min));
6117
6118     // Based on the range information we know about the LHS, see if we can
6119     // simplify this comparison.  For example, (x&4) < 8  is always true.
6120     switch (I.getPredicate()) {
6121     default: llvm_unreachable("Unknown icmp opcode!");
6122     case ICmpInst::ICMP_EQ:
6123       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6124         return ReplaceInstUsesWith(I, Context->getFalse());
6125       break;
6126     case ICmpInst::ICMP_NE:
6127       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6128         return ReplaceInstUsesWith(I, Context->getTrue());
6129       break;
6130     case ICmpInst::ICMP_ULT:
6131       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6132         return ReplaceInstUsesWith(I, Context->getTrue());
6133       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6134         return ReplaceInstUsesWith(I, Context->getFalse());
6135       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6136         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6137       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6138         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6139           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6140                               SubOne(CI, Context));
6141
6142         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6143         if (CI->isMinValue(true))
6144           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6145                            Context->getAllOnesValue(Op0->getType()));
6146       }
6147       break;
6148     case ICmpInst::ICMP_UGT:
6149       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6150         return ReplaceInstUsesWith(I, Context->getTrue());
6151       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6152         return ReplaceInstUsesWith(I, Context->getFalse());
6153
6154       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6155         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6156       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6157         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6158           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6159                               AddOne(CI, Context));
6160
6161         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6162         if (CI->isMaxValue(true))
6163           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6164                               Context->getNullValue(Op0->getType()));
6165       }
6166       break;
6167     case ICmpInst::ICMP_SLT:
6168       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6169         return ReplaceInstUsesWith(I, Context->getTrue());
6170       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6171         return ReplaceInstUsesWith(I, Context->getFalse());
6172       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6173         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6174       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6175         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6176           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6177                               SubOne(CI, Context));
6178       }
6179       break;
6180     case ICmpInst::ICMP_SGT:
6181       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6182         return ReplaceInstUsesWith(I, Context->getTrue());
6183       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6184         return ReplaceInstUsesWith(I, Context->getFalse());
6185
6186       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6187         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6188       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6189         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6190           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6191                               AddOne(CI, Context));
6192       }
6193       break;
6194     case ICmpInst::ICMP_SGE:
6195       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6196       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6197         return ReplaceInstUsesWith(I, Context->getTrue());
6198       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6199         return ReplaceInstUsesWith(I, Context->getFalse());
6200       break;
6201     case ICmpInst::ICMP_SLE:
6202       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6203       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6204         return ReplaceInstUsesWith(I, Context->getTrue());
6205       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6206         return ReplaceInstUsesWith(I, Context->getFalse());
6207       break;
6208     case ICmpInst::ICMP_UGE:
6209       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6210       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6211         return ReplaceInstUsesWith(I, Context->getTrue());
6212       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6213         return ReplaceInstUsesWith(I, Context->getFalse());
6214       break;
6215     case ICmpInst::ICMP_ULE:
6216       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6217       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6218         return ReplaceInstUsesWith(I, Context->getTrue());
6219       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6220         return ReplaceInstUsesWith(I, Context->getFalse());
6221       break;
6222     }
6223
6224     // Turn a signed comparison into an unsigned one if both operands
6225     // are known to have the same sign.
6226     if (I.isSignedPredicate() &&
6227         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6228          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6229       return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
6230   }
6231
6232   // Test if the ICmpInst instruction is used exclusively by a select as
6233   // part of a minimum or maximum operation. If so, refrain from doing
6234   // any other folding. This helps out other analyses which understand
6235   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6236   // and CodeGen. And in this case, at least one of the comparison
6237   // operands has at least one user besides the compare (the select),
6238   // which would often largely negate the benefit of folding anyway.
6239   if (I.hasOneUse())
6240     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6241       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6242           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6243         return 0;
6244
6245   // See if we are doing a comparison between a constant and an instruction that
6246   // can be folded into the comparison.
6247   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6248     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6249     // instruction, see if that instruction also has constants so that the 
6250     // instruction can be folded into the icmp 
6251     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6252       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6253         return Res;
6254   }
6255
6256   // Handle icmp with constant (but not simple integer constant) RHS
6257   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6258     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6259       switch (LHSI->getOpcode()) {
6260       case Instruction::GetElementPtr:
6261         if (RHSC->isNullValue()) {
6262           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6263           bool isAllZeros = true;
6264           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6265             if (!isa<Constant>(LHSI->getOperand(i)) ||
6266                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6267               isAllZeros = false;
6268               break;
6269             }
6270           if (isAllZeros)
6271             return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
6272                     Context->getNullValue(LHSI->getOperand(0)->getType()));
6273         }
6274         break;
6275
6276       case Instruction::PHI:
6277         // Only fold icmp into the PHI if the phi and fcmp are in the same
6278         // block.  If in the same block, we're encouraging jump threading.  If
6279         // not, we are just pessimizing the code by making an i1 phi.
6280         if (LHSI->getParent() == I.getParent())
6281           if (Instruction *NV = FoldOpIntoPhi(I))
6282             return NV;
6283         break;
6284       case Instruction::Select: {
6285         // If either operand of the select is a constant, we can fold the
6286         // comparison into the select arms, which will cause one to be
6287         // constant folded and the select turned into a bitwise or.
6288         Value *Op1 = 0, *Op2 = 0;
6289         if (LHSI->hasOneUse()) {
6290           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6291             // Fold the known value into the constant operand.
6292             Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6293             // Insert a new ICmp of the other select operand.
6294             Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6295                                                    LHSI->getOperand(2), RHSC,
6296                                                    I.getName()), I);
6297           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6298             // Fold the known value into the constant operand.
6299             Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6300             // Insert a new ICmp of the other select operand.
6301             Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6302                                                    LHSI->getOperand(1), RHSC,
6303                                                    I.getName()), I);
6304           }
6305         }
6306
6307         if (Op1)
6308           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6309         break;
6310       }
6311       case Instruction::Malloc:
6312         // If we have (malloc != null), and if the malloc has a single use, we
6313         // can assume it is successful and remove the malloc.
6314         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6315           AddToWorkList(LHSI);
6316           return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
6317                                                          !I.isTrueWhenEqual()));
6318         }
6319         break;
6320       }
6321   }
6322
6323   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6324   if (User *GEP = dyn_castGetElementPtr(Op0))
6325     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6326       return NI;
6327   if (User *GEP = dyn_castGetElementPtr(Op1))
6328     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6329                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6330       return NI;
6331
6332   // Test to see if the operands of the icmp are casted versions of other
6333   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6334   // now.
6335   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6336     if (isa<PointerType>(Op0->getType()) && 
6337         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6338       // We keep moving the cast from the left operand over to the right
6339       // operand, where it can often be eliminated completely.
6340       Op0 = CI->getOperand(0);
6341
6342       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6343       // so eliminate it as well.
6344       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6345         Op1 = CI2->getOperand(0);
6346
6347       // If Op1 is a constant, we can fold the cast into the constant.
6348       if (Op0->getType() != Op1->getType()) {
6349         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6350           Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
6351         } else {
6352           // Otherwise, cast the RHS right before the icmp
6353           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6354         }
6355       }
6356       return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
6357     }
6358   }
6359   
6360   if (isa<CastInst>(Op0)) {
6361     // Handle the special case of: icmp (cast bool to X), <cst>
6362     // This comes up when you have code like
6363     //   int X = A < B;
6364     //   if (X) ...
6365     // For generality, we handle any zero-extension of any operand comparison
6366     // with a constant or another cast from the same type.
6367     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6368       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6369         return R;
6370   }
6371   
6372   // See if it's the same type of instruction on the left and right.
6373   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6374     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6375       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6376           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6377         switch (Op0I->getOpcode()) {
6378         default: break;
6379         case Instruction::Add:
6380         case Instruction::Sub:
6381         case Instruction::Xor:
6382           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6383             return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
6384                                 Op1I->getOperand(0));
6385           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6386           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6387             if (CI->getValue().isSignBit()) {
6388               ICmpInst::Predicate Pred = I.isSignedPredicate()
6389                                              ? I.getUnsignedPredicate()
6390                                              : I.getSignedPredicate();
6391               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6392                                   Op1I->getOperand(0));
6393             }
6394             
6395             if (CI->getValue().isMaxSignedValue()) {
6396               ICmpInst::Predicate Pred = I.isSignedPredicate()
6397                                              ? I.getUnsignedPredicate()
6398                                              : I.getSignedPredicate();
6399               Pred = I.getSwappedPredicate(Pred);
6400               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6401                                   Op1I->getOperand(0));
6402             }
6403           }
6404           break;
6405         case Instruction::Mul:
6406           if (!I.isEquality())
6407             break;
6408
6409           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6410             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6411             // Mask = -1 >> count-trailing-zeros(Cst).
6412             if (!CI->isZero() && !CI->isOne()) {
6413               const APInt &AP = CI->getValue();
6414               ConstantInt *Mask = Context->getConstantInt(
6415                                       APInt::getLowBitsSet(AP.getBitWidth(),
6416                                                            AP.getBitWidth() -
6417                                                       AP.countTrailingZeros()));
6418               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6419                                                             Mask);
6420               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6421                                                             Mask);
6422               InsertNewInstBefore(And1, I);
6423               InsertNewInstBefore(And2, I);
6424               return new ICmpInst(*Context, I.getPredicate(), And1, And2);
6425             }
6426           }
6427           break;
6428         }
6429       }
6430     }
6431   }
6432   
6433   // ~x < ~y --> y < x
6434   { Value *A, *B;
6435     if (match(Op0, m_Not(m_Value(A)), *Context) &&
6436         match(Op1, m_Not(m_Value(B)), *Context))
6437       return new ICmpInst(*Context, I.getPredicate(), B, A);
6438   }
6439   
6440   if (I.isEquality()) {
6441     Value *A, *B, *C, *D;
6442     
6443     // -x == -y --> x == y
6444     if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6445         match(Op1, m_Neg(m_Value(B)), *Context))
6446       return new ICmpInst(*Context, I.getPredicate(), A, B);
6447     
6448     if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
6449       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6450         Value *OtherVal = A == Op1 ? B : A;
6451         return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6452                             Context->getNullValue(A->getType()));
6453       }
6454
6455       if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
6456         // A^c1 == C^c2 --> A == C^(c1^c2)
6457         ConstantInt *C1, *C2;
6458         if (match(B, m_ConstantInt(C1), *Context) &&
6459             match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
6460           Constant *NC = 
6461                        Context->getConstantInt(C1->getValue() ^ C2->getValue());
6462           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6463           return new ICmpInst(*Context, I.getPredicate(), A,
6464                               InsertNewInstBefore(Xor, I));
6465         }
6466         
6467         // A^B == A^D -> B == D
6468         if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6469         if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6470         if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6471         if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
6472       }
6473     }
6474     
6475     if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
6476         (A == Op0 || B == Op0)) {
6477       // A == (A^B)  ->  B == 0
6478       Value *OtherVal = A == Op0 ? B : A;
6479       return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6480                           Context->getNullValue(A->getType()));
6481     }
6482
6483     // (A-B) == A  ->  B == 0
6484     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
6485       return new ICmpInst(*Context, I.getPredicate(), B, 
6486                           Context->getNullValue(B->getType()));
6487
6488     // A == (A-B)  ->  B == 0
6489     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
6490       return new ICmpInst(*Context, I.getPredicate(), B,
6491                           Context->getNullValue(B->getType()));
6492     
6493     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6494     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6495         match(Op0, m_And(m_Value(A), m_Value(B)), *Context) && 
6496         match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
6497       Value *X = 0, *Y = 0, *Z = 0;
6498       
6499       if (A == C) {
6500         X = B; Y = D; Z = A;
6501       } else if (A == D) {
6502         X = B; Y = C; Z = A;
6503       } else if (B == C) {
6504         X = A; Y = D; Z = B;
6505       } else if (B == D) {
6506         X = A; Y = C; Z = B;
6507       }
6508       
6509       if (X) {   // Build (X^Y) & Z
6510         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6511         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6512         I.setOperand(0, Op1);
6513         I.setOperand(1, Context->getNullValue(Op1->getType()));
6514         return &I;
6515       }
6516     }
6517   }
6518   return Changed ? &I : 0;
6519 }
6520
6521
6522 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6523 /// and CmpRHS are both known to be integer constants.
6524 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6525                                           ConstantInt *DivRHS) {
6526   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6527   const APInt &CmpRHSV = CmpRHS->getValue();
6528   
6529   // FIXME: If the operand types don't match the type of the divide 
6530   // then don't attempt this transform. The code below doesn't have the
6531   // logic to deal with a signed divide and an unsigned compare (and
6532   // vice versa). This is because (x /s C1) <s C2  produces different 
6533   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6534   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6535   // work. :(  The if statement below tests that condition and bails 
6536   // if it finds it. 
6537   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6538   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6539     return 0;
6540   if (DivRHS->isZero())
6541     return 0; // The ProdOV computation fails on divide by zero.
6542   if (DivIsSigned && DivRHS->isAllOnesValue())
6543     return 0; // The overflow computation also screws up here
6544   if (DivRHS->isOne())
6545     return 0; // Not worth bothering, and eliminates some funny cases
6546               // with INT_MIN.
6547
6548   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6549   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6550   // C2 (CI). By solving for X we can turn this into a range check 
6551   // instead of computing a divide. 
6552   Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
6553
6554   // Determine if the product overflows by seeing if the product is
6555   // not equal to the divide. Make sure we do the same kind of divide
6556   // as in the LHS instruction that we're folding. 
6557   bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6558                  Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
6559
6560   // Get the ICmp opcode
6561   ICmpInst::Predicate Pred = ICI.getPredicate();
6562
6563   // Figure out the interval that is being checked.  For example, a comparison
6564   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6565   // Compute this interval based on the constants involved and the signedness of
6566   // the compare/divide.  This computes a half-open interval, keeping track of
6567   // whether either value in the interval overflows.  After analysis each
6568   // overflow variable is set to 0 if it's corresponding bound variable is valid
6569   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6570   int LoOverflow = 0, HiOverflow = 0;
6571   Constant *LoBound = 0, *HiBound = 0;
6572   
6573   if (!DivIsSigned) {  // udiv
6574     // e.g. X/5 op 3  --> [15, 20)
6575     LoBound = Prod;
6576     HiOverflow = LoOverflow = ProdOV;
6577     if (!HiOverflow)
6578       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6579   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6580     if (CmpRHSV == 0) {       // (X / pos) op 0
6581       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6582       LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS, 
6583                                                                     Context)));
6584       HiBound = DivRHS;
6585     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6586       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6587       HiOverflow = LoOverflow = ProdOV;
6588       if (!HiOverflow)
6589         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6590     } else {                       // (X / pos) op neg
6591       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6592       HiBound = AddOne(Prod, Context);
6593       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6594       if (!LoOverflow) {
6595         ConstantInt* DivNeg =
6596                          cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6597         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6598                                      true) ? -1 : 0;
6599        }
6600     }
6601   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6602     if (CmpRHSV == 0) {       // (X / neg) op 0
6603       // e.g. X/-5 op 0  --> [-4, 5)
6604       LoBound = AddOne(DivRHS, Context);
6605       HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6606       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6607         HiOverflow = 1;            // [INTMIN+1, overflow)
6608         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6609       }
6610     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6611       // e.g. X/-5 op 3  --> [-19, -14)
6612       HiBound = AddOne(Prod, Context);
6613       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6614       if (!LoOverflow)
6615         LoOverflow = AddWithOverflow(LoBound, HiBound,
6616                                      DivRHS, Context, true) ? -1 : 0;
6617     } else {                       // (X / neg) op neg
6618       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6619       LoOverflow = HiOverflow = ProdOV;
6620       if (!HiOverflow)
6621         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6622     }
6623     
6624     // Dividing by a negative swaps the condition.  LT <-> GT
6625     Pred = ICmpInst::getSwappedPredicate(Pred);
6626   }
6627
6628   Value *X = DivI->getOperand(0);
6629   switch (Pred) {
6630   default: llvm_unreachable("Unhandled icmp opcode!");
6631   case ICmpInst::ICMP_EQ:
6632     if (LoOverflow && HiOverflow)
6633       return ReplaceInstUsesWith(ICI, Context->getFalse());
6634     else if (HiOverflow)
6635       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6636                           ICmpInst::ICMP_UGE, X, LoBound);
6637     else if (LoOverflow)
6638       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6639                           ICmpInst::ICMP_ULT, X, HiBound);
6640     else
6641       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6642   case ICmpInst::ICMP_NE:
6643     if (LoOverflow && HiOverflow)
6644       return ReplaceInstUsesWith(ICI, Context->getTrue());
6645     else if (HiOverflow)
6646       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6647                           ICmpInst::ICMP_ULT, X, LoBound);
6648     else if (LoOverflow)
6649       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6650                           ICmpInst::ICMP_UGE, X, HiBound);
6651     else
6652       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6653   case ICmpInst::ICMP_ULT:
6654   case ICmpInst::ICMP_SLT:
6655     if (LoOverflow == +1)   // Low bound is greater than input range.
6656       return ReplaceInstUsesWith(ICI, Context->getTrue());
6657     if (LoOverflow == -1)   // Low bound is less than input range.
6658       return ReplaceInstUsesWith(ICI, Context->getFalse());
6659     return new ICmpInst(*Context, Pred, X, LoBound);
6660   case ICmpInst::ICMP_UGT:
6661   case ICmpInst::ICMP_SGT:
6662     if (HiOverflow == +1)       // High bound greater than input range.
6663       return ReplaceInstUsesWith(ICI, Context->getFalse());
6664     else if (HiOverflow == -1)  // High bound less than input range.
6665       return ReplaceInstUsesWith(ICI, Context->getTrue());
6666     if (Pred == ICmpInst::ICMP_UGT)
6667       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
6668     else
6669       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
6670   }
6671 }
6672
6673
6674 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6675 ///
6676 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6677                                                           Instruction *LHSI,
6678                                                           ConstantInt *RHS) {
6679   const APInt &RHSV = RHS->getValue();
6680   
6681   switch (LHSI->getOpcode()) {
6682   case Instruction::Trunc:
6683     if (ICI.isEquality() && LHSI->hasOneUse()) {
6684       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6685       // of the high bits truncated out of x are known.
6686       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6687              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6688       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6689       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6690       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6691       
6692       // If all the high bits are known, we can do this xform.
6693       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6694         // Pull in the high bits from known-ones set.
6695         APInt NewRHS(RHS->getValue());
6696         NewRHS.zext(SrcBits);
6697         NewRHS |= KnownOne;
6698         return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
6699                             Context->getConstantInt(NewRHS));
6700       }
6701     }
6702     break;
6703       
6704   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6705     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6706       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6707       // fold the xor.
6708       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6709           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6710         Value *CompareVal = LHSI->getOperand(0);
6711         
6712         // If the sign bit of the XorCST is not set, there is no change to
6713         // the operation, just stop using the Xor.
6714         if (!XorCST->getValue().isNegative()) {
6715           ICI.setOperand(0, CompareVal);
6716           AddToWorkList(LHSI);
6717           return &ICI;
6718         }
6719         
6720         // Was the old condition true if the operand is positive?
6721         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6722         
6723         // If so, the new one isn't.
6724         isTrueIfPositive ^= true;
6725         
6726         if (isTrueIfPositive)
6727           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
6728                               SubOne(RHS, Context));
6729         else
6730           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
6731                               AddOne(RHS, Context));
6732       }
6733
6734       if (LHSI->hasOneUse()) {
6735         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6736         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6737           const APInt &SignBit = XorCST->getValue();
6738           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6739                                          ? ICI.getUnsignedPredicate()
6740                                          : ICI.getSignedPredicate();
6741           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6742                               Context->getConstantInt(RHSV ^ SignBit));
6743         }
6744
6745         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6746         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6747           const APInt &NotSignBit = XorCST->getValue();
6748           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6749                                          ? ICI.getUnsignedPredicate()
6750                                          : ICI.getSignedPredicate();
6751           Pred = ICI.getSwappedPredicate(Pred);
6752           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6753                               Context->getConstantInt(RHSV ^ NotSignBit));
6754         }
6755       }
6756     }
6757     break;
6758   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6759     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6760         LHSI->getOperand(0)->hasOneUse()) {
6761       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6762       
6763       // If the LHS is an AND of a truncating cast, we can widen the
6764       // and/compare to be the input width without changing the value
6765       // produced, eliminating a cast.
6766       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6767         // We can do this transformation if either the AND constant does not
6768         // have its sign bit set or if it is an equality comparison. 
6769         // Extending a relational comparison when we're checking the sign
6770         // bit would not work.
6771         if (Cast->hasOneUse() &&
6772             (ICI.isEquality() ||
6773              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6774           uint32_t BitWidth = 
6775             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6776           APInt NewCST = AndCST->getValue();
6777           NewCST.zext(BitWidth);
6778           APInt NewCI = RHSV;
6779           NewCI.zext(BitWidth);
6780           Instruction *NewAnd = 
6781             BinaryOperator::CreateAnd(Cast->getOperand(0),
6782                                Context->getConstantInt(NewCST),LHSI->getName());
6783           InsertNewInstBefore(NewAnd, ICI);
6784           return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
6785                               Context->getConstantInt(NewCI));
6786         }
6787       }
6788       
6789       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6790       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6791       // happens a LOT in code produced by the C front-end, for bitfield
6792       // access.
6793       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6794       if (Shift && !Shift->isShift())
6795         Shift = 0;
6796       
6797       ConstantInt *ShAmt;
6798       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6799       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6800       const Type *AndTy = AndCST->getType();          // Type of the and.
6801       
6802       // We can fold this as long as we can't shift unknown bits
6803       // into the mask.  This can only happen with signed shift
6804       // rights, as they sign-extend.
6805       if (ShAmt) {
6806         bool CanFold = Shift->isLogicalShift();
6807         if (!CanFold) {
6808           // To test for the bad case of the signed shr, see if any
6809           // of the bits shifted in could be tested after the mask.
6810           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6811           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6812           
6813           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6814           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6815                AndCST->getValue()) == 0)
6816             CanFold = true;
6817         }
6818         
6819         if (CanFold) {
6820           Constant *NewCst;
6821           if (Shift->getOpcode() == Instruction::Shl)
6822             NewCst = Context->getConstantExprLShr(RHS, ShAmt);
6823           else
6824             NewCst = Context->getConstantExprShl(RHS, ShAmt);
6825           
6826           // Check to see if we are shifting out any of the bits being
6827           // compared.
6828           if (Context->getConstantExpr(Shift->getOpcode(),
6829                                        NewCst, ShAmt) != RHS) {
6830             // If we shifted bits out, the fold is not going to work out.
6831             // As a special case, check to see if this means that the
6832             // result is always true or false now.
6833             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6834               return ReplaceInstUsesWith(ICI, Context->getFalse());
6835             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6836               return ReplaceInstUsesWith(ICI, Context->getTrue());
6837           } else {
6838             ICI.setOperand(1, NewCst);
6839             Constant *NewAndCST;
6840             if (Shift->getOpcode() == Instruction::Shl)
6841               NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
6842             else
6843               NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
6844             LHSI->setOperand(1, NewAndCST);
6845             LHSI->setOperand(0, Shift->getOperand(0));
6846             AddToWorkList(Shift); // Shift is dead.
6847             AddUsesToWorkList(ICI);
6848             return &ICI;
6849           }
6850         }
6851       }
6852       
6853       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6854       // preferable because it allows the C<<Y expression to be hoisted out
6855       // of a loop if Y is invariant and X is not.
6856       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6857           ICI.isEquality() && !Shift->isArithmeticShift() &&
6858           !isa<Constant>(Shift->getOperand(0))) {
6859         // Compute C << Y.
6860         Value *NS;
6861         if (Shift->getOpcode() == Instruction::LShr) {
6862           NS = BinaryOperator::CreateShl(AndCST, 
6863                                          Shift->getOperand(1), "tmp");
6864         } else {
6865           // Insert a logical shift.
6866           NS = BinaryOperator::CreateLShr(AndCST,
6867                                           Shift->getOperand(1), "tmp");
6868         }
6869         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6870         
6871         // Compute X & (C << Y).
6872         Instruction *NewAnd = 
6873           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6874         InsertNewInstBefore(NewAnd, ICI);
6875         
6876         ICI.setOperand(0, NewAnd);
6877         return &ICI;
6878       }
6879     }
6880     break;
6881     
6882   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6883     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6884     if (!ShAmt) break;
6885     
6886     uint32_t TypeBits = RHSV.getBitWidth();
6887     
6888     // Check that the shift amount is in range.  If not, don't perform
6889     // undefined shifts.  When the shift is visited it will be
6890     // simplified.
6891     if (ShAmt->uge(TypeBits))
6892       break;
6893     
6894     if (ICI.isEquality()) {
6895       // If we are comparing against bits always shifted out, the
6896       // comparison cannot succeed.
6897       Constant *Comp =
6898         Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6899                                                                  ShAmt);
6900       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6901         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6902         Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
6903         return ReplaceInstUsesWith(ICI, Cst);
6904       }
6905       
6906       if (LHSI->hasOneUse()) {
6907         // Otherwise strength reduce the shift into an and.
6908         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6909         Constant *Mask =
6910           Context->getConstantInt(APInt::getLowBitsSet(TypeBits, 
6911                                                        TypeBits-ShAmtVal));
6912         
6913         Instruction *AndI =
6914           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6915                                     Mask, LHSI->getName()+".mask");
6916         Value *And = InsertNewInstBefore(AndI, ICI);
6917         return new ICmpInst(*Context, ICI.getPredicate(), And,
6918                             Context->getConstantInt(RHSV.lshr(ShAmtVal)));
6919       }
6920     }
6921     
6922     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6923     bool TrueIfSigned = false;
6924     if (LHSI->hasOneUse() &&
6925         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6926       // (X << 31) <s 0  --> (X&1) != 0
6927       Constant *Mask = Context->getConstantInt(APInt(TypeBits, 1) <<
6928                                            (TypeBits-ShAmt->getZExtValue()-1));
6929       Instruction *AndI =
6930         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6931                                   Mask, LHSI->getName()+".mask");
6932       Value *And = InsertNewInstBefore(AndI, ICI);
6933       
6934       return new ICmpInst(*Context,
6935                           TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6936                           And, Context->getNullValue(And->getType()));
6937     }
6938     break;
6939   }
6940     
6941   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6942   case Instruction::AShr: {
6943     // Only handle equality comparisons of shift-by-constant.
6944     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6945     if (!ShAmt || !ICI.isEquality()) break;
6946
6947     // Check that the shift amount is in range.  If not, don't perform
6948     // undefined shifts.  When the shift is visited it will be
6949     // simplified.
6950     uint32_t TypeBits = RHSV.getBitWidth();
6951     if (ShAmt->uge(TypeBits))
6952       break;
6953     
6954     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6955       
6956     // If we are comparing against bits always shifted out, the
6957     // comparison cannot succeed.
6958     APInt Comp = RHSV << ShAmtVal;
6959     if (LHSI->getOpcode() == Instruction::LShr)
6960       Comp = Comp.lshr(ShAmtVal);
6961     else
6962       Comp = Comp.ashr(ShAmtVal);
6963     
6964     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6965       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6966       Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
6967       return ReplaceInstUsesWith(ICI, Cst);
6968     }
6969     
6970     // Otherwise, check to see if the bits shifted out are known to be zero.
6971     // If so, we can compare against the unshifted value:
6972     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6973     if (LHSI->hasOneUse() &&
6974         MaskedValueIsZero(LHSI->getOperand(0), 
6975                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6976       return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
6977                           Context->getConstantExprShl(RHS, ShAmt));
6978     }
6979       
6980     if (LHSI->hasOneUse()) {
6981       // Otherwise strength reduce the shift into an and.
6982       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6983       Constant *Mask = Context->getConstantInt(Val);
6984       
6985       Instruction *AndI =
6986         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6987                                   Mask, LHSI->getName()+".mask");
6988       Value *And = InsertNewInstBefore(AndI, ICI);
6989       return new ICmpInst(*Context, ICI.getPredicate(), And,
6990                           Context->getConstantExprShl(RHS, ShAmt));
6991     }
6992     break;
6993   }
6994     
6995   case Instruction::SDiv:
6996   case Instruction::UDiv:
6997     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6998     // Fold this div into the comparison, producing a range check. 
6999     // Determine, based on the divide type, what the range is being 
7000     // checked.  If there is an overflow on the low or high side, remember 
7001     // it, otherwise compute the range [low, hi) bounding the new value.
7002     // See: InsertRangeTest above for the kinds of replacements possible.
7003     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7004       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7005                                           DivRHS))
7006         return R;
7007     break;
7008
7009   case Instruction::Add:
7010     // Fold: icmp pred (add, X, C1), C2
7011
7012     if (!ICI.isEquality()) {
7013       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7014       if (!LHSC) break;
7015       const APInt &LHSV = LHSC->getValue();
7016
7017       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7018                             .subtract(LHSV);
7019
7020       if (ICI.isSignedPredicate()) {
7021         if (CR.getLower().isSignBit()) {
7022           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7023                               Context->getConstantInt(CR.getUpper()));
7024         } else if (CR.getUpper().isSignBit()) {
7025           return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7026                               Context->getConstantInt(CR.getLower()));
7027         }
7028       } else {
7029         if (CR.getLower().isMinValue()) {
7030           return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7031                               Context->getConstantInt(CR.getUpper()));
7032         } else if (CR.getUpper().isMinValue()) {
7033           return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7034                               Context->getConstantInt(CR.getLower()));
7035         }
7036       }
7037     }
7038     break;
7039   }
7040   
7041   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7042   if (ICI.isEquality()) {
7043     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7044     
7045     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7046     // the second operand is a constant, simplify a bit.
7047     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7048       switch (BO->getOpcode()) {
7049       case Instruction::SRem:
7050         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7051         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7052           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7053           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7054             Instruction *NewRem =
7055               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
7056                                          BO->getName());
7057             InsertNewInstBefore(NewRem, ICI);
7058             return new ICmpInst(*Context, ICI.getPredicate(), NewRem, 
7059                                 Context->getNullValue(BO->getType()));
7060           }
7061         }
7062         break;
7063       case Instruction::Add:
7064         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7065         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7066           if (BO->hasOneUse())
7067             return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7068                                 Context->getConstantExprSub(RHS, BOp1C));
7069         } else if (RHSV == 0) {
7070           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7071           // efficiently invertible, or if the add has just this one use.
7072           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7073           
7074           if (Value *NegVal = dyn_castNegVal(BOp1, Context))
7075             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
7076           else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
7077             return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
7078           else if (BO->hasOneUse()) {
7079             Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
7080             InsertNewInstBefore(Neg, ICI);
7081             Neg->takeName(BO);
7082             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
7083           }
7084         }
7085         break;
7086       case Instruction::Xor:
7087         // For the xor case, we can xor two constants together, eliminating
7088         // the explicit xor.
7089         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7090           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0), 
7091                               Context->getConstantExprXor(RHS, BOC));
7092         
7093         // FALLTHROUGH
7094       case Instruction::Sub:
7095         // Replace (([sub|xor] A, B) != 0) with (A != B)
7096         if (RHSV == 0)
7097           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7098                               BO->getOperand(1));
7099         break;
7100         
7101       case Instruction::Or:
7102         // If bits are being or'd in that are not present in the constant we
7103         // are comparing against, then the comparison could never succeed!
7104         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7105           Constant *NotCI = Context->getConstantExprNot(RHS);
7106           if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7107             return ReplaceInstUsesWith(ICI,
7108                                        Context->getConstantInt(Type::Int1Ty, 
7109                                        isICMP_NE));
7110         }
7111         break;
7112         
7113       case Instruction::And:
7114         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7115           // If bits are being compared against that are and'd out, then the
7116           // comparison can never succeed!
7117           if ((RHSV & ~BOC->getValue()) != 0)
7118             return ReplaceInstUsesWith(ICI,
7119                                        Context->getConstantInt(Type::Int1Ty,
7120                                        isICMP_NE));
7121           
7122           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7123           if (RHS == BOC && RHSV.isPowerOf2())
7124             return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
7125                                 ICmpInst::ICMP_NE, LHSI,
7126                                 Context->getNullValue(RHS->getType()));
7127           
7128           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7129           if (BOC->getValue().isSignBit()) {
7130             Value *X = BO->getOperand(0);
7131             Constant *Zero = Context->getNullValue(X->getType());
7132             ICmpInst::Predicate pred = isICMP_NE ? 
7133               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7134             return new ICmpInst(*Context, pred, X, Zero);
7135           }
7136           
7137           // ((X & ~7) == 0) --> X < 8
7138           if (RHSV == 0 && isHighOnes(BOC)) {
7139             Value *X = BO->getOperand(0);
7140             Constant *NegX = Context->getConstantExprNeg(BOC);
7141             ICmpInst::Predicate pred = isICMP_NE ? 
7142               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7143             return new ICmpInst(*Context, pred, X, NegX);
7144           }
7145         }
7146       default: break;
7147       }
7148     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7149       // Handle icmp {eq|ne} <intrinsic>, intcst.
7150       if (II->getIntrinsicID() == Intrinsic::bswap) {
7151         AddToWorkList(II);
7152         ICI.setOperand(0, II->getOperand(1));
7153         ICI.setOperand(1, Context->getConstantInt(RHSV.byteSwap()));
7154         return &ICI;
7155       }
7156     }
7157   }
7158   return 0;
7159 }
7160
7161 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7162 /// We only handle extending casts so far.
7163 ///
7164 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7165   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7166   Value *LHSCIOp        = LHSCI->getOperand(0);
7167   const Type *SrcTy     = LHSCIOp->getType();
7168   const Type *DestTy    = LHSCI->getType();
7169   Value *RHSCIOp;
7170
7171   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7172   // integer type is the same size as the pointer type.
7173   if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7174       TD->getPointerSizeInBits() ==
7175          cast<IntegerType>(DestTy)->getBitWidth()) {
7176     Value *RHSOp = 0;
7177     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7178       RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
7179     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7180       RHSOp = RHSC->getOperand(0);
7181       // If the pointer types don't match, insert a bitcast.
7182       if (LHSCIOp->getType() != RHSOp->getType())
7183         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
7184     }
7185
7186     if (RHSOp)
7187       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
7188   }
7189   
7190   // The code below only handles extension cast instructions, so far.
7191   // Enforce this.
7192   if (LHSCI->getOpcode() != Instruction::ZExt &&
7193       LHSCI->getOpcode() != Instruction::SExt)
7194     return 0;
7195
7196   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7197   bool isSignedCmp = ICI.isSignedPredicate();
7198
7199   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7200     // Not an extension from the same type?
7201     RHSCIOp = CI->getOperand(0);
7202     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7203       return 0;
7204     
7205     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7206     // and the other is a zext), then we can't handle this.
7207     if (CI->getOpcode() != LHSCI->getOpcode())
7208       return 0;
7209
7210     // Deal with equality cases early.
7211     if (ICI.isEquality())
7212       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7213
7214     // A signed comparison of sign extended values simplifies into a
7215     // signed comparison.
7216     if (isSignedCmp && isSignedExt)
7217       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7218
7219     // The other three cases all fold into an unsigned comparison.
7220     return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7221   }
7222
7223   // If we aren't dealing with a constant on the RHS, exit early
7224   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7225   if (!CI)
7226     return 0;
7227
7228   // Compute the constant that would happen if we truncated to SrcTy then
7229   // reextended to DestTy.
7230   Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7231   Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7232                                                 Res1, DestTy);
7233
7234   // If the re-extended constant didn't change...
7235   if (Res2 == CI) {
7236     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7237     // For example, we might have:
7238     //    %A = sext i16 %X to i32
7239     //    %B = icmp ugt i32 %A, 1330
7240     // It is incorrect to transform this into 
7241     //    %B = icmp ugt i16 %X, 1330
7242     // because %A may have negative value. 
7243     //
7244     // However, we allow this when the compare is EQ/NE, because they are
7245     // signless.
7246     if (isSignedExt == isSignedCmp || ICI.isEquality())
7247       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
7248     return 0;
7249   }
7250
7251   // The re-extended constant changed so the constant cannot be represented 
7252   // in the shorter type. Consequently, we cannot emit a simple comparison.
7253
7254   // First, handle some easy cases. We know the result cannot be equal at this
7255   // point so handle the ICI.isEquality() cases
7256   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7257     return ReplaceInstUsesWith(ICI, Context->getFalse());
7258   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7259     return ReplaceInstUsesWith(ICI, Context->getTrue());
7260
7261   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7262   // should have been folded away previously and not enter in here.
7263   Value *Result;
7264   if (isSignedCmp) {
7265     // We're performing a signed comparison.
7266     if (cast<ConstantInt>(CI)->getValue().isNegative())
7267       Result = Context->getFalse();          // X < (small) --> false
7268     else
7269       Result = Context->getTrue();           // X < (large) --> true
7270   } else {
7271     // We're performing an unsigned comparison.
7272     if (isSignedExt) {
7273       // We're performing an unsigned comp with a sign extended value.
7274       // This is true if the input is >= 0. [aka >s -1]
7275       Constant *NegOne = Context->getAllOnesValue(SrcTy);
7276       Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT, 
7277                                    LHSCIOp, NegOne, ICI.getName()), ICI);
7278     } else {
7279       // Unsigned extend & unsigned compare -> always true.
7280       Result = Context->getTrue();
7281     }
7282   }
7283
7284   // Finally, return the value computed.
7285   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7286       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7287     return ReplaceInstUsesWith(ICI, Result);
7288
7289   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7290           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7291          "ICmp should be folded!");
7292   if (Constant *CI = dyn_cast<Constant>(Result))
7293     return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
7294   return BinaryOperator::CreateNot(*Context, Result);
7295 }
7296
7297 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7298   return commonShiftTransforms(I);
7299 }
7300
7301 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7302   return commonShiftTransforms(I);
7303 }
7304
7305 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7306   if (Instruction *R = commonShiftTransforms(I))
7307     return R;
7308   
7309   Value *Op0 = I.getOperand(0);
7310   
7311   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7312   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7313     if (CSI->isAllOnesValue())
7314       return ReplaceInstUsesWith(I, CSI);
7315
7316   // See if we can turn a signed shr into an unsigned shr.
7317   if (MaskedValueIsZero(Op0,
7318                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7319     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7320
7321   // Arithmetic shifting an all-sign-bit value is a no-op.
7322   unsigned NumSignBits = ComputeNumSignBits(Op0);
7323   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7324     return ReplaceInstUsesWith(I, Op0);
7325
7326   return 0;
7327 }
7328
7329 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7330   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7331   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7332
7333   // shl X, 0 == X and shr X, 0 == X
7334   // shl 0, X == 0 and shr 0, X == 0
7335   if (Op1 == Context->getNullValue(Op1->getType()) ||
7336       Op0 == Context->getNullValue(Op0->getType()))
7337     return ReplaceInstUsesWith(I, Op0);
7338   
7339   if (isa<UndefValue>(Op0)) {            
7340     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7341       return ReplaceInstUsesWith(I, Op0);
7342     else                                    // undef << X -> 0, undef >>u X -> 0
7343       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7344   }
7345   if (isa<UndefValue>(Op1)) {
7346     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7347       return ReplaceInstUsesWith(I, Op0);          
7348     else                                     // X << undef, X >>u undef -> 0
7349       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7350   }
7351
7352   // See if we can fold away this shift.
7353   if (SimplifyDemandedInstructionBits(I))
7354     return &I;
7355
7356   // Try to fold constant and into select arguments.
7357   if (isa<Constant>(Op0))
7358     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7359       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7360         return R;
7361
7362   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7363     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7364       return Res;
7365   return 0;
7366 }
7367
7368 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7369                                                BinaryOperator &I) {
7370   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7371
7372   // See if we can simplify any instructions used by the instruction whose sole 
7373   // purpose is to compute bits we don't care about.
7374   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7375   
7376   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7377   // a signed shift.
7378   //
7379   if (Op1->uge(TypeBits)) {
7380     if (I.getOpcode() != Instruction::AShr)
7381       return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
7382     else {
7383       I.setOperand(1, Context->getConstantInt(I.getType(), TypeBits-1));
7384       return &I;
7385     }
7386   }
7387   
7388   // ((X*C1) << C2) == (X * (C1 << C2))
7389   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7390     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7391       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7392         return BinaryOperator::CreateMul(BO->getOperand(0),
7393                                         Context->getConstantExprShl(BOOp, Op1));
7394   
7395   // Try to fold constant and into select arguments.
7396   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7397     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7398       return R;
7399   if (isa<PHINode>(Op0))
7400     if (Instruction *NV = FoldOpIntoPhi(I))
7401       return NV;
7402   
7403   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7404   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7405     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7406     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7407     // place.  Don't try to do this transformation in this case.  Also, we
7408     // require that the input operand is a shift-by-constant so that we have
7409     // confidence that the shifts will get folded together.  We could do this
7410     // xform in more cases, but it is unlikely to be profitable.
7411     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7412         isa<ConstantInt>(TrOp->getOperand(1))) {
7413       // Okay, we'll do this xform.  Make the shift of shift.
7414       Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
7415       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7416                                                 I.getName());
7417       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7418
7419       // For logical shifts, the truncation has the effect of making the high
7420       // part of the register be zeros.  Emulate this by inserting an AND to
7421       // clear the top bits as needed.  This 'and' will usually be zapped by
7422       // other xforms later if dead.
7423       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7424       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7425       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7426       
7427       // The mask we constructed says what the trunc would do if occurring
7428       // between the shifts.  We want to know the effect *after* the second
7429       // shift.  We know that it is a logical shift by a constant, so adjust the
7430       // mask as appropriate.
7431       if (I.getOpcode() == Instruction::Shl)
7432         MaskV <<= Op1->getZExtValue();
7433       else {
7434         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7435         MaskV = MaskV.lshr(Op1->getZExtValue());
7436       }
7437
7438       Instruction *And =
7439         BinaryOperator::CreateAnd(NSh, Context->getConstantInt(MaskV), 
7440                                   TI->getName());
7441       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7442
7443       // Return the value truncated to the interesting size.
7444       return new TruncInst(And, I.getType());
7445     }
7446   }
7447   
7448   if (Op0->hasOneUse()) {
7449     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7450       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7451       Value *V1, *V2;
7452       ConstantInt *CC;
7453       switch (Op0BO->getOpcode()) {
7454         default: break;
7455         case Instruction::Add:
7456         case Instruction::And:
7457         case Instruction::Or:
7458         case Instruction::Xor: {
7459           // These operators commute.
7460           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7461           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7462               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7463                     m_Specific(Op1)), *Context)){
7464             Instruction *YS = BinaryOperator::CreateShl(
7465                                             Op0BO->getOperand(0), Op1,
7466                                             Op0BO->getName());
7467             InsertNewInstBefore(YS, I); // (Y << C)
7468             Instruction *X = 
7469               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7470                                      Op0BO->getOperand(1)->getName());
7471             InsertNewInstBefore(X, I);  // (X + (Y << C))
7472             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7473             return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7474                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7475           }
7476           
7477           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7478           Value *Op0BOOp1 = Op0BO->getOperand(1);
7479           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7480               match(Op0BOOp1, 
7481                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7482                           m_ConstantInt(CC)), *Context) &&
7483               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7484             Instruction *YS = BinaryOperator::CreateShl(
7485                                                      Op0BO->getOperand(0), Op1,
7486                                                      Op0BO->getName());
7487             InsertNewInstBefore(YS, I); // (Y << C)
7488             Instruction *XM =
7489               BinaryOperator::CreateAnd(V1,
7490                                         Context->getConstantExprShl(CC, Op1),
7491                                         V1->getName()+".mask");
7492             InsertNewInstBefore(XM, I); // X & (CC << C)
7493             
7494             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7495           }
7496         }
7497           
7498         // FALL THROUGH.
7499         case Instruction::Sub: {
7500           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7501           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7502               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7503                     m_Specific(Op1)), *Context)){
7504             Instruction *YS = BinaryOperator::CreateShl(
7505                                                      Op0BO->getOperand(1), Op1,
7506                                                      Op0BO->getName());
7507             InsertNewInstBefore(YS, I); // (Y << C)
7508             Instruction *X =
7509               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7510                                      Op0BO->getOperand(0)->getName());
7511             InsertNewInstBefore(X, I);  // (X + (Y << C))
7512             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7513             return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7514                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7515           }
7516           
7517           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7518           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7519               match(Op0BO->getOperand(0),
7520                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7521                           m_ConstantInt(CC)), *Context) && V2 == Op1 &&
7522               cast<BinaryOperator>(Op0BO->getOperand(0))
7523                   ->getOperand(0)->hasOneUse()) {
7524             Instruction *YS = BinaryOperator::CreateShl(
7525                                                      Op0BO->getOperand(1), Op1,
7526                                                      Op0BO->getName());
7527             InsertNewInstBefore(YS, I); // (Y << C)
7528             Instruction *XM =
7529               BinaryOperator::CreateAnd(V1, 
7530                                         Context->getConstantExprShl(CC, Op1),
7531                                         V1->getName()+".mask");
7532             InsertNewInstBefore(XM, I); // X & (CC << C)
7533             
7534             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7535           }
7536           
7537           break;
7538         }
7539       }
7540       
7541       
7542       // If the operand is an bitwise operator with a constant RHS, and the
7543       // shift is the only use, we can pull it out of the shift.
7544       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7545         bool isValid = true;     // Valid only for And, Or, Xor
7546         bool highBitSet = false; // Transform if high bit of constant set?
7547         
7548         switch (Op0BO->getOpcode()) {
7549           default: isValid = false; break;   // Do not perform transform!
7550           case Instruction::Add:
7551             isValid = isLeftShift;
7552             break;
7553           case Instruction::Or:
7554           case Instruction::Xor:
7555             highBitSet = false;
7556             break;
7557           case Instruction::And:
7558             highBitSet = true;
7559             break;
7560         }
7561         
7562         // If this is a signed shift right, and the high bit is modified
7563         // by the logical operation, do not perform the transformation.
7564         // The highBitSet boolean indicates the value of the high bit of
7565         // the constant which would cause it to be modified for this
7566         // operation.
7567         //
7568         if (isValid && I.getOpcode() == Instruction::AShr)
7569           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7570         
7571         if (isValid) {
7572           Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
7573           
7574           Instruction *NewShift =
7575             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7576           InsertNewInstBefore(NewShift, I);
7577           NewShift->takeName(Op0BO);
7578           
7579           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7580                                         NewRHS);
7581         }
7582       }
7583     }
7584   }
7585   
7586   // Find out if this is a shift of a shift by a constant.
7587   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7588   if (ShiftOp && !ShiftOp->isShift())
7589     ShiftOp = 0;
7590   
7591   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7592     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7593     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7594     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7595     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7596     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7597     Value *X = ShiftOp->getOperand(0);
7598     
7599     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7600     
7601     const IntegerType *Ty = cast<IntegerType>(I.getType());
7602     
7603     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7604     if (I.getOpcode() == ShiftOp->getOpcode()) {
7605       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7606       // saturates.
7607       if (AmtSum >= TypeBits) {
7608         if (I.getOpcode() != Instruction::AShr)
7609           return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7610         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7611       }
7612       
7613       return BinaryOperator::Create(I.getOpcode(), X,
7614                                     Context->getConstantInt(Ty, AmtSum));
7615     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7616                I.getOpcode() == Instruction::AShr) {
7617       if (AmtSum >= TypeBits)
7618         return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7619       
7620       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7621       return BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, AmtSum));
7622     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7623                I.getOpcode() == Instruction::LShr) {
7624       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7625       if (AmtSum >= TypeBits)
7626         AmtSum = TypeBits-1;
7627       
7628       Instruction *Shift =
7629         BinaryOperator::CreateAShr(X, Context->getConstantInt(Ty, AmtSum));
7630       InsertNewInstBefore(Shift, I);
7631
7632       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7633       return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7634     }
7635     
7636     // Okay, if we get here, one shift must be left, and the other shift must be
7637     // right.  See if the amounts are equal.
7638     if (ShiftAmt1 == ShiftAmt2) {
7639       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7640       if (I.getOpcode() == Instruction::Shl) {
7641         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7642         return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7643       }
7644       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7645       if (I.getOpcode() == Instruction::LShr) {
7646         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7647         return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7648       }
7649       // We can simplify ((X << C) >>s C) into a trunc + sext.
7650       // NOTE: we could do this for any C, but that would make 'unusual' integer
7651       // types.  For now, just stick to ones well-supported by the code
7652       // generators.
7653       const Type *SExtType = 0;
7654       switch (Ty->getBitWidth() - ShiftAmt1) {
7655       case 1  :
7656       case 8  :
7657       case 16 :
7658       case 32 :
7659       case 64 :
7660       case 128:
7661         SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
7662         break;
7663       default: break;
7664       }
7665       if (SExtType) {
7666         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7667         InsertNewInstBefore(NewTrunc, I);
7668         return new SExtInst(NewTrunc, Ty);
7669       }
7670       // Otherwise, we can't handle it yet.
7671     } else if (ShiftAmt1 < ShiftAmt2) {
7672       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7673       
7674       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7675       if (I.getOpcode() == Instruction::Shl) {
7676         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7677                ShiftOp->getOpcode() == Instruction::AShr);
7678         Instruction *Shift =
7679           BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7680         InsertNewInstBefore(Shift, I);
7681         
7682         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7683         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7684       }
7685       
7686       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7687       if (I.getOpcode() == Instruction::LShr) {
7688         assert(ShiftOp->getOpcode() == Instruction::Shl);
7689         Instruction *Shift =
7690           BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, ShiftDiff));
7691         InsertNewInstBefore(Shift, I);
7692         
7693         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7694         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7695       }
7696       
7697       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7698     } else {
7699       assert(ShiftAmt2 < ShiftAmt1);
7700       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7701
7702       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7703       if (I.getOpcode() == Instruction::Shl) {
7704         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7705                ShiftOp->getOpcode() == Instruction::AShr);
7706         Instruction *Shift =
7707           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7708                                  Context->getConstantInt(Ty, ShiftDiff));
7709         InsertNewInstBefore(Shift, I);
7710         
7711         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7712         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7713       }
7714       
7715       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7716       if (I.getOpcode() == Instruction::LShr) {
7717         assert(ShiftOp->getOpcode() == Instruction::Shl);
7718         Instruction *Shift =
7719           BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7720         InsertNewInstBefore(Shift, I);
7721         
7722         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7723         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7724       }
7725       
7726       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7727     }
7728   }
7729   return 0;
7730 }
7731
7732
7733 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7734 /// expression.  If so, decompose it, returning some value X, such that Val is
7735 /// X*Scale+Offset.
7736 ///
7737 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7738                                         int &Offset, LLVMContext *Context) {
7739   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7740   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7741     Offset = CI->getZExtValue();
7742     Scale  = 0;
7743     return Context->getConstantInt(Type::Int32Ty, 0);
7744   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7745     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7746       if (I->getOpcode() == Instruction::Shl) {
7747         // This is a value scaled by '1 << the shift amt'.
7748         Scale = 1U << RHS->getZExtValue();
7749         Offset = 0;
7750         return I->getOperand(0);
7751       } else if (I->getOpcode() == Instruction::Mul) {
7752         // This value is scaled by 'RHS'.
7753         Scale = RHS->getZExtValue();
7754         Offset = 0;
7755         return I->getOperand(0);
7756       } else if (I->getOpcode() == Instruction::Add) {
7757         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7758         // where C1 is divisible by C2.
7759         unsigned SubScale;
7760         Value *SubVal = 
7761           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7762                                     Offset, Context);
7763         Offset += RHS->getZExtValue();
7764         Scale = SubScale;
7765         return SubVal;
7766       }
7767     }
7768   }
7769
7770   // Otherwise, we can't look past this.
7771   Scale = 1;
7772   Offset = 0;
7773   return Val;
7774 }
7775
7776
7777 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7778 /// try to eliminate the cast by moving the type information into the alloc.
7779 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7780                                                    AllocationInst &AI) {
7781   const PointerType *PTy = cast<PointerType>(CI.getType());
7782   
7783   // Remove any uses of AI that are dead.
7784   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7785   
7786   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7787     Instruction *User = cast<Instruction>(*UI++);
7788     if (isInstructionTriviallyDead(User)) {
7789       while (UI != E && *UI == User)
7790         ++UI; // If this instruction uses AI more than once, don't break UI.
7791       
7792       ++NumDeadInst;
7793       DOUT << "IC: DCE: " << *User;
7794       EraseInstFromFunction(*User);
7795     }
7796   }
7797
7798   // This requires TargetData to get the alloca alignment and size information.
7799   if (!TD) return 0;
7800
7801   // Get the type really allocated and the type casted to.
7802   const Type *AllocElTy = AI.getAllocatedType();
7803   const Type *CastElTy = PTy->getElementType();
7804   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7805
7806   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7807   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7808   if (CastElTyAlign < AllocElTyAlign) return 0;
7809
7810   // If the allocation has multiple uses, only promote it if we are strictly
7811   // increasing the alignment of the resultant allocation.  If we keep it the
7812   // same, we open the door to infinite loops of various kinds.  (A reference
7813   // from a dbg.declare doesn't count as a use for this purpose.)
7814   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7815       CastElTyAlign == AllocElTyAlign) return 0;
7816
7817   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7818   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7819   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7820
7821   // See if we can satisfy the modulus by pulling a scale out of the array
7822   // size argument.
7823   unsigned ArraySizeScale;
7824   int ArrayOffset;
7825   Value *NumElements = // See if the array size is a decomposable linear expr.
7826     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7827                               ArrayOffset, Context);
7828  
7829   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7830   // do the xform.
7831   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7832       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7833
7834   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7835   Value *Amt = 0;
7836   if (Scale == 1) {
7837     Amt = NumElements;
7838   } else {
7839     // If the allocation size is constant, form a constant mul expression
7840     Amt = Context->getConstantInt(Type::Int32Ty, Scale);
7841     if (isa<ConstantInt>(NumElements))
7842       Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
7843                                  cast<ConstantInt>(Amt));
7844     // otherwise multiply the amount and the number of elements
7845     else {
7846       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7847       Amt = InsertNewInstBefore(Tmp, AI);
7848     }
7849   }
7850   
7851   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7852     Value *Off = Context->getConstantInt(Type::Int32Ty, Offset, true);
7853     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7854     Amt = InsertNewInstBefore(Tmp, AI);
7855   }
7856   
7857   AllocationInst *New;
7858   if (isa<MallocInst>(AI))
7859     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7860   else
7861     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7862   InsertNewInstBefore(New, AI);
7863   New->takeName(&AI);
7864   
7865   // If the allocation has one real use plus a dbg.declare, just remove the
7866   // declare.
7867   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7868     EraseInstFromFunction(*DI);
7869   }
7870   // If the allocation has multiple real uses, insert a cast and change all
7871   // things that used it to use the new cast.  This will also hack on CI, but it
7872   // will die soon.
7873   else if (!AI.hasOneUse()) {
7874     AddUsesToWorkList(AI);
7875     // New is the allocation instruction, pointer typed. AI is the original
7876     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7877     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7878     InsertNewInstBefore(NewCast, AI);
7879     AI.replaceAllUsesWith(NewCast);
7880   }
7881   return ReplaceInstUsesWith(CI, New);
7882 }
7883
7884 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7885 /// and return it as type Ty without inserting any new casts and without
7886 /// changing the computed value.  This is used by code that tries to decide
7887 /// whether promoting or shrinking integer operations to wider or smaller types
7888 /// will allow us to eliminate a truncate or extend.
7889 ///
7890 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7891 /// extension operation if Ty is larger.
7892 ///
7893 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7894 /// should return true if trunc(V) can be computed by computing V in the smaller
7895 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7896 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7897 /// efficiently truncated.
7898 ///
7899 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7900 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7901 /// the final result.
7902 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7903                                               unsigned CastOpc,
7904                                               int &NumCastsRemoved){
7905   // We can always evaluate constants in another type.
7906   if (isa<Constant>(V))
7907     return true;
7908   
7909   Instruction *I = dyn_cast<Instruction>(V);
7910   if (!I) return false;
7911   
7912   const Type *OrigTy = V->getType();
7913   
7914   // If this is an extension or truncate, we can often eliminate it.
7915   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7916     // If this is a cast from the destination type, we can trivially eliminate
7917     // it, and this will remove a cast overall.
7918     if (I->getOperand(0)->getType() == Ty) {
7919       // If the first operand is itself a cast, and is eliminable, do not count
7920       // this as an eliminable cast.  We would prefer to eliminate those two
7921       // casts first.
7922       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7923         ++NumCastsRemoved;
7924       return true;
7925     }
7926   }
7927
7928   // We can't extend or shrink something that has multiple uses: doing so would
7929   // require duplicating the instruction in general, which isn't profitable.
7930   if (!I->hasOneUse()) return false;
7931
7932   unsigned Opc = I->getOpcode();
7933   switch (Opc) {
7934   case Instruction::Add:
7935   case Instruction::Sub:
7936   case Instruction::Mul:
7937   case Instruction::And:
7938   case Instruction::Or:
7939   case Instruction::Xor:
7940     // These operators can all arbitrarily be extended or truncated.
7941     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7942                                       NumCastsRemoved) &&
7943            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7944                                       NumCastsRemoved);
7945
7946   case Instruction::UDiv:
7947   case Instruction::URem: {
7948     // UDiv and URem can be truncated if all the truncated bits are zero.
7949     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7950     uint32_t BitWidth = Ty->getScalarSizeInBits();
7951     if (BitWidth < OrigBitWidth) {
7952       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7953       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7954           MaskedValueIsZero(I->getOperand(1), Mask)) {
7955         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7956                                           NumCastsRemoved) &&
7957                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7958                                           NumCastsRemoved);
7959       }
7960     }
7961     break;
7962   }
7963   case Instruction::Shl:
7964     // If we are truncating the result of this SHL, and if it's a shift of a
7965     // constant amount, we can always perform a SHL in a smaller type.
7966     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7967       uint32_t BitWidth = Ty->getScalarSizeInBits();
7968       if (BitWidth < OrigTy->getScalarSizeInBits() &&
7969           CI->getLimitedValue(BitWidth) < BitWidth)
7970         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7971                                           NumCastsRemoved);
7972     }
7973     break;
7974   case Instruction::LShr:
7975     // If this is a truncate of a logical shr, we can truncate it to a smaller
7976     // lshr iff we know that the bits we would otherwise be shifting in are
7977     // already zeros.
7978     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7979       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7980       uint32_t BitWidth = Ty->getScalarSizeInBits();
7981       if (BitWidth < OrigBitWidth &&
7982           MaskedValueIsZero(I->getOperand(0),
7983             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7984           CI->getLimitedValue(BitWidth) < BitWidth) {
7985         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7986                                           NumCastsRemoved);
7987       }
7988     }
7989     break;
7990   case Instruction::ZExt:
7991   case Instruction::SExt:
7992   case Instruction::Trunc:
7993     // If this is the same kind of case as our original (e.g. zext+zext), we
7994     // can safely replace it.  Note that replacing it does not reduce the number
7995     // of casts in the input.
7996     if (Opc == CastOpc)
7997       return true;
7998
7999     // sext (zext ty1), ty2 -> zext ty2
8000     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
8001       return true;
8002     break;
8003   case Instruction::Select: {
8004     SelectInst *SI = cast<SelectInst>(I);
8005     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8006                                       NumCastsRemoved) &&
8007            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8008                                       NumCastsRemoved);
8009   }
8010   case Instruction::PHI: {
8011     // We can change a phi if we can change all operands.
8012     PHINode *PN = cast<PHINode>(I);
8013     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8014       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8015                                       NumCastsRemoved))
8016         return false;
8017     return true;
8018   }
8019   default:
8020     // TODO: Can handle more cases here.
8021     break;
8022   }
8023   
8024   return false;
8025 }
8026
8027 /// EvaluateInDifferentType - Given an expression that 
8028 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8029 /// evaluate the expression.
8030 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
8031                                              bool isSigned) {
8032   if (Constant *C = dyn_cast<Constant>(V))
8033     return Context->getConstantExprIntegerCast(C, Ty,
8034                                                isSigned /*Sext or ZExt*/);
8035
8036   // Otherwise, it must be an instruction.
8037   Instruction *I = cast<Instruction>(V);
8038   Instruction *Res = 0;
8039   unsigned Opc = I->getOpcode();
8040   switch (Opc) {
8041   case Instruction::Add:
8042   case Instruction::Sub:
8043   case Instruction::Mul:
8044   case Instruction::And:
8045   case Instruction::Or:
8046   case Instruction::Xor:
8047   case Instruction::AShr:
8048   case Instruction::LShr:
8049   case Instruction::Shl:
8050   case Instruction::UDiv:
8051   case Instruction::URem: {
8052     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8053     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8054     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8055     break;
8056   }    
8057   case Instruction::Trunc:
8058   case Instruction::ZExt:
8059   case Instruction::SExt:
8060     // If the source type of the cast is the type we're trying for then we can
8061     // just return the source.  There's no need to insert it because it is not
8062     // new.
8063     if (I->getOperand(0)->getType() == Ty)
8064       return I->getOperand(0);
8065     
8066     // Otherwise, must be the same type of cast, so just reinsert a new one.
8067     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8068                            Ty);
8069     break;
8070   case Instruction::Select: {
8071     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8072     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8073     Res = SelectInst::Create(I->getOperand(0), True, False);
8074     break;
8075   }
8076   case Instruction::PHI: {
8077     PHINode *OPN = cast<PHINode>(I);
8078     PHINode *NPN = PHINode::Create(Ty);
8079     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8080       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8081       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8082     }
8083     Res = NPN;
8084     break;
8085   }
8086   default: 
8087     // TODO: Can handle more cases here.
8088     llvm_unreachable("Unreachable!");
8089     break;
8090   }
8091   
8092   Res->takeName(I);
8093   return InsertNewInstBefore(Res, *I);
8094 }
8095
8096 /// @brief Implement the transforms common to all CastInst visitors.
8097 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8098   Value *Src = CI.getOperand(0);
8099
8100   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8101   // eliminate it now.
8102   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8103     if (Instruction::CastOps opc = 
8104         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8105       // The first cast (CSrc) is eliminable so we need to fix up or replace
8106       // the second cast (CI). CSrc will then have a good chance of being dead.
8107       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8108     }
8109   }
8110
8111   // If we are casting a select then fold the cast into the select
8112   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8113     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8114       return NV;
8115
8116   // If we are casting a PHI then fold the cast into the PHI
8117   if (isa<PHINode>(Src))
8118     if (Instruction *NV = FoldOpIntoPhi(CI))
8119       return NV;
8120   
8121   return 0;
8122 }
8123
8124 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8125 /// or not there is a sequence of GEP indices into the type that will land us at
8126 /// the specified offset.  If so, fill them into NewIndices and return the
8127 /// resultant element type, otherwise return null.
8128 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8129                                        SmallVectorImpl<Value*> &NewIndices,
8130                                        const TargetData *TD,
8131                                        LLVMContext *Context) {
8132   if (!TD) return 0;
8133   if (!Ty->isSized()) return 0;
8134   
8135   // Start with the index over the outer type.  Note that the type size
8136   // might be zero (even if the offset isn't zero) if the indexed type
8137   // is something like [0 x {int, int}]
8138   const Type *IntPtrTy = TD->getIntPtrType();
8139   int64_t FirstIdx = 0;
8140   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8141     FirstIdx = Offset/TySize;
8142     Offset -= FirstIdx*TySize;
8143     
8144     // Handle hosts where % returns negative instead of values [0..TySize).
8145     if (Offset < 0) {
8146       --FirstIdx;
8147       Offset += TySize;
8148       assert(Offset >= 0);
8149     }
8150     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8151   }
8152   
8153   NewIndices.push_back(Context->getConstantInt(IntPtrTy, FirstIdx));
8154     
8155   // Index into the types.  If we fail, set OrigBase to null.
8156   while (Offset) {
8157     // Indexing into tail padding between struct/array elements.
8158     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8159       return 0;
8160     
8161     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8162       const StructLayout *SL = TD->getStructLayout(STy);
8163       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8164              "Offset must stay within the indexed type");
8165       
8166       unsigned Elt = SL->getElementContainingOffset(Offset);
8167       NewIndices.push_back(Context->getConstantInt(Type::Int32Ty, Elt));
8168       
8169       Offset -= SL->getElementOffset(Elt);
8170       Ty = STy->getElementType(Elt);
8171     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8172       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8173       assert(EltSize && "Cannot index into a zero-sized array");
8174       NewIndices.push_back(Context->getConstantInt(IntPtrTy,Offset/EltSize));
8175       Offset %= EltSize;
8176       Ty = AT->getElementType();
8177     } else {
8178       // Otherwise, we can't index into the middle of this atomic type, bail.
8179       return 0;
8180     }
8181   }
8182   
8183   return Ty;
8184 }
8185
8186 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8187 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8188   Value *Src = CI.getOperand(0);
8189   
8190   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8191     // If casting the result of a getelementptr instruction with no offset, turn
8192     // this into a cast of the original pointer!
8193     if (GEP->hasAllZeroIndices()) {
8194       // Changing the cast operand is usually not a good idea but it is safe
8195       // here because the pointer operand is being replaced with another 
8196       // pointer operand so the opcode doesn't need to change.
8197       AddToWorkList(GEP);
8198       CI.setOperand(0, GEP->getOperand(0));
8199       return &CI;
8200     }
8201     
8202     // If the GEP has a single use, and the base pointer is a bitcast, and the
8203     // GEP computes a constant offset, see if we can convert these three
8204     // instructions into fewer.  This typically happens with unions and other
8205     // non-type-safe code.
8206     if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8207       if (GEP->hasAllConstantIndices()) {
8208         // We are guaranteed to get a constant from EmitGEPOffset.
8209         ConstantInt *OffsetV =
8210                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8211         int64_t Offset = OffsetV->getSExtValue();
8212         
8213         // Get the base pointer input of the bitcast, and the type it points to.
8214         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8215         const Type *GEPIdxTy =
8216           cast<PointerType>(OrigBase->getType())->getElementType();
8217         SmallVector<Value*, 8> NewIndices;
8218         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8219           // If we were able to index down into an element, create the GEP
8220           // and bitcast the result.  This eliminates one bitcast, potentially
8221           // two.
8222           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
8223                                                         NewIndices.begin(),
8224                                                         NewIndices.end(), "");
8225           InsertNewInstBefore(NGEP, CI);
8226           NGEP->takeName(GEP);
8227           
8228           if (isa<BitCastInst>(CI))
8229             return new BitCastInst(NGEP, CI.getType());
8230           assert(isa<PtrToIntInst>(CI));
8231           return new PtrToIntInst(NGEP, CI.getType());
8232         }
8233       }      
8234     }
8235   }
8236     
8237   return commonCastTransforms(CI);
8238 }
8239
8240 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8241 /// type like i42.  We don't want to introduce operations on random non-legal
8242 /// integer types where they don't already exist in the code.  In the future,
8243 /// we should consider making this based off target-data, so that 32-bit targets
8244 /// won't get i64 operations etc.
8245 static bool isSafeIntegerType(const Type *Ty) {
8246   switch (Ty->getPrimitiveSizeInBits()) {
8247   case 8:
8248   case 16:
8249   case 32:
8250   case 64:
8251     return true;
8252   default: 
8253     return false;
8254   }
8255 }
8256
8257 /// commonIntCastTransforms - This function implements the common transforms
8258 /// for trunc, zext, and sext.
8259 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8260   if (Instruction *Result = commonCastTransforms(CI))
8261     return Result;
8262
8263   Value *Src = CI.getOperand(0);
8264   const Type *SrcTy = Src->getType();
8265   const Type *DestTy = CI.getType();
8266   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8267   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8268
8269   // See if we can simplify any instructions used by the LHS whose sole 
8270   // purpose is to compute bits we don't care about.
8271   if (SimplifyDemandedInstructionBits(CI))
8272     return &CI;
8273
8274   // If the source isn't an instruction or has more than one use then we
8275   // can't do anything more. 
8276   Instruction *SrcI = dyn_cast<Instruction>(Src);
8277   if (!SrcI || !Src->hasOneUse())
8278     return 0;
8279
8280   // Attempt to propagate the cast into the instruction for int->int casts.
8281   int NumCastsRemoved = 0;
8282   // Only do this if the dest type is a simple type, don't convert the
8283   // expression tree to something weird like i93 unless the source is also
8284   // strange.
8285   if ((isSafeIntegerType(DestTy->getScalarType()) ||
8286        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8287       CanEvaluateInDifferentType(SrcI, DestTy,
8288                                  CI.getOpcode(), NumCastsRemoved)) {
8289     // If this cast is a truncate, evaluting in a different type always
8290     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8291     // we need to do an AND to maintain the clear top-part of the computation,
8292     // so we require that the input have eliminated at least one cast.  If this
8293     // is a sign extension, we insert two new casts (to do the extension) so we
8294     // require that two casts have been eliminated.
8295     bool DoXForm = false;
8296     bool JustReplace = false;
8297     switch (CI.getOpcode()) {
8298     default:
8299       // All the others use floating point so we shouldn't actually 
8300       // get here because of the check above.
8301       llvm_unreachable("Unknown cast type");
8302     case Instruction::Trunc:
8303       DoXForm = true;
8304       break;
8305     case Instruction::ZExt: {
8306       DoXForm = NumCastsRemoved >= 1;
8307       if (!DoXForm && 0) {
8308         // If it's unnecessary to issue an AND to clear the high bits, it's
8309         // always profitable to do this xform.
8310         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8311         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8312         if (MaskedValueIsZero(TryRes, Mask))
8313           return ReplaceInstUsesWith(CI, TryRes);
8314         
8315         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8316           if (TryI->use_empty())
8317             EraseInstFromFunction(*TryI);
8318       }
8319       break;
8320     }
8321     case Instruction::SExt: {
8322       DoXForm = NumCastsRemoved >= 2;
8323       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8324         // If we do not have to emit the truncate + sext pair, then it's always
8325         // profitable to do this xform.
8326         //
8327         // It's not safe to eliminate the trunc + sext pair if one of the
8328         // eliminated cast is a truncate. e.g.
8329         // t2 = trunc i32 t1 to i16
8330         // t3 = sext i16 t2 to i32
8331         // !=
8332         // i32 t1
8333         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8334         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8335         if (NumSignBits > (DestBitSize - SrcBitSize))
8336           return ReplaceInstUsesWith(CI, TryRes);
8337         
8338         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8339           if (TryI->use_empty())
8340             EraseInstFromFunction(*TryI);
8341       }
8342       break;
8343     }
8344     }
8345     
8346     if (DoXForm) {
8347       DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8348            << " cast: " << CI;
8349       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8350                                            CI.getOpcode() == Instruction::SExt);
8351       if (JustReplace)
8352         // Just replace this cast with the result.
8353         return ReplaceInstUsesWith(CI, Res);
8354
8355       assert(Res->getType() == DestTy);
8356       switch (CI.getOpcode()) {
8357       default: llvm_unreachable("Unknown cast type!");
8358       case Instruction::Trunc:
8359         // Just replace this cast with the result.
8360         return ReplaceInstUsesWith(CI, Res);
8361       case Instruction::ZExt: {
8362         assert(SrcBitSize < DestBitSize && "Not a zext?");
8363
8364         // If the high bits are already zero, just replace this cast with the
8365         // result.
8366         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8367         if (MaskedValueIsZero(Res, Mask))
8368           return ReplaceInstUsesWith(CI, Res);
8369
8370         // We need to emit an AND to clear the high bits.
8371         Constant *C = Context->getConstantInt(APInt::getLowBitsSet(DestBitSize,
8372                                                             SrcBitSize));
8373         return BinaryOperator::CreateAnd(Res, C);
8374       }
8375       case Instruction::SExt: {
8376         // If the high bits are already filled with sign bit, just replace this
8377         // cast with the result.
8378         unsigned NumSignBits = ComputeNumSignBits(Res);
8379         if (NumSignBits > (DestBitSize - SrcBitSize))
8380           return ReplaceInstUsesWith(CI, Res);
8381
8382         // We need to emit a cast to truncate, then a cast to sext.
8383         return CastInst::Create(Instruction::SExt,
8384             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8385                              CI), DestTy);
8386       }
8387       }
8388     }
8389   }
8390   
8391   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8392   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8393
8394   switch (SrcI->getOpcode()) {
8395   case Instruction::Add:
8396   case Instruction::Mul:
8397   case Instruction::And:
8398   case Instruction::Or:
8399   case Instruction::Xor:
8400     // If we are discarding information, rewrite.
8401     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8402       // Don't insert two casts unless at least one can be eliminated.
8403       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8404           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8405         Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8406         Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8407         return BinaryOperator::Create(
8408             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8409       }
8410     }
8411
8412     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8413     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8414         SrcI->getOpcode() == Instruction::Xor &&
8415         Op1 == Context->getTrue() &&
8416         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8417       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8418       return BinaryOperator::CreateXor(New,
8419                                       Context->getConstantInt(CI.getType(), 1));
8420     }
8421     break;
8422
8423   case Instruction::Shl: {
8424     // Canonicalize trunc inside shl, if we can.
8425     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8426     if (CI && DestBitSize < SrcBitSize &&
8427         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8428       Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8429       Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8430       return BinaryOperator::CreateShl(Op0c, Op1c);
8431     }
8432     break;
8433   }
8434   }
8435   return 0;
8436 }
8437
8438 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8439   if (Instruction *Result = commonIntCastTransforms(CI))
8440     return Result;
8441   
8442   Value *Src = CI.getOperand(0);
8443   const Type *Ty = CI.getType();
8444   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8445   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8446
8447   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8448   if (DestBitWidth == 1) {
8449     Constant *One = Context->getConstantInt(Src->getType(), 1);
8450     Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8451     Value *Zero = Context->getNullValue(Src->getType());
8452     return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
8453   }
8454
8455   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8456   ConstantInt *ShAmtV = 0;
8457   Value *ShiftOp = 0;
8458   if (Src->hasOneUse() &&
8459       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
8460     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8461     
8462     // Get a mask for the bits shifting in.
8463     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8464     if (MaskedValueIsZero(ShiftOp, Mask)) {
8465       if (ShAmt >= DestBitWidth)        // All zeros.
8466         return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
8467       
8468       // Okay, we can shrink this.  Truncate the input, then return a new
8469       // shift.
8470       Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8471       Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
8472       return BinaryOperator::CreateLShr(V1, V2);
8473     }
8474   }
8475   
8476   return 0;
8477 }
8478
8479 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8480 /// in order to eliminate the icmp.
8481 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8482                                              bool DoXform) {
8483   // If we are just checking for a icmp eq of a single bit and zext'ing it
8484   // to an integer, then shift the bit to the appropriate place and then
8485   // cast to integer to avoid the comparison.
8486   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8487     const APInt &Op1CV = Op1C->getValue();
8488       
8489     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8490     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8491     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8492         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8493       if (!DoXform) return ICI;
8494
8495       Value *In = ICI->getOperand(0);
8496       Value *Sh = Context->getConstantInt(In->getType(),
8497                                    In->getType()->getScalarSizeInBits()-1);
8498       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8499                                                         In->getName()+".lobit"),
8500                                CI);
8501       if (In->getType() != CI.getType())
8502         In = CastInst::CreateIntegerCast(In, CI.getType(),
8503                                          false/*ZExt*/, "tmp", &CI);
8504
8505       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8506         Constant *One = Context->getConstantInt(In->getType(), 1);
8507         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8508                                                          In->getName()+".not"),
8509                                  CI);
8510       }
8511
8512       return ReplaceInstUsesWith(CI, In);
8513     }
8514       
8515       
8516       
8517     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8518     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8519     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8520     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8521     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8522     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8523     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8524     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8525     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8526         // This only works for EQ and NE
8527         ICI->isEquality()) {
8528       // If Op1C some other power of two, convert:
8529       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8530       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8531       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8532       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8533         
8534       APInt KnownZeroMask(~KnownZero);
8535       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8536         if (!DoXform) return ICI;
8537
8538         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8539         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8540           // (X&4) == 2 --> false
8541           // (X&4) != 2 --> true
8542           Constant *Res = Context->getConstantInt(Type::Int1Ty, isNE);
8543           Res = Context->getConstantExprZExt(Res, CI.getType());
8544           return ReplaceInstUsesWith(CI, Res);
8545         }
8546           
8547         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8548         Value *In = ICI->getOperand(0);
8549         if (ShiftAmt) {
8550           // Perform a logical shr by shiftamt.
8551           // Insert the shift to put the result in the low bit.
8552           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8553                               Context->getConstantInt(In->getType(), ShiftAmt),
8554                                                    In->getName()+".lobit"), CI);
8555         }
8556           
8557         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8558           Constant *One = Context->getConstantInt(In->getType(), 1);
8559           In = BinaryOperator::CreateXor(In, One, "tmp");
8560           InsertNewInstBefore(cast<Instruction>(In), CI);
8561         }
8562           
8563         if (CI.getType() == In->getType())
8564           return ReplaceInstUsesWith(CI, In);
8565         else
8566           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8567       }
8568     }
8569   }
8570
8571   return 0;
8572 }
8573
8574 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8575   // If one of the common conversion will work ..
8576   if (Instruction *Result = commonIntCastTransforms(CI))
8577     return Result;
8578
8579   Value *Src = CI.getOperand(0);
8580
8581   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8582   // types and if the sizes are just right we can convert this into a logical
8583   // 'and' which will be much cheaper than the pair of casts.
8584   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8585     // Get the sizes of the types involved.  We know that the intermediate type
8586     // will be smaller than A or C, but don't know the relation between A and C.
8587     Value *A = CSrc->getOperand(0);
8588     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8589     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8590     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8591     // If we're actually extending zero bits, then if
8592     // SrcSize <  DstSize: zext(a & mask)
8593     // SrcSize == DstSize: a & mask
8594     // SrcSize  > DstSize: trunc(a) & mask
8595     if (SrcSize < DstSize) {
8596       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8597       Constant *AndConst = Context->getConstantInt(A->getType(), AndValue);
8598       Instruction *And =
8599         BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8600       InsertNewInstBefore(And, CI);
8601       return new ZExtInst(And, CI.getType());
8602     } else if (SrcSize == DstSize) {
8603       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8604       return BinaryOperator::CreateAnd(A, Context->getConstantInt(A->getType(),
8605                                                            AndValue));
8606     } else if (SrcSize > DstSize) {
8607       Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8608       InsertNewInstBefore(Trunc, CI);
8609       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8610       return BinaryOperator::CreateAnd(Trunc, 
8611                                        Context->getConstantInt(Trunc->getType(),
8612                                                                AndValue));
8613     }
8614   }
8615
8616   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8617     return transformZExtICmp(ICI, CI);
8618
8619   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8620   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8621     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8622     // of the (zext icmp) will be transformed.
8623     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8624     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8625     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8626         (transformZExtICmp(LHS, CI, false) ||
8627          transformZExtICmp(RHS, CI, false))) {
8628       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8629       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8630       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8631     }
8632   }
8633
8634   // zext(trunc(t) & C) -> (t & zext(C)).
8635   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8636     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8637       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8638         Value *TI0 = TI->getOperand(0);
8639         if (TI0->getType() == CI.getType())
8640           return
8641             BinaryOperator::CreateAnd(TI0,
8642                                 Context->getConstantExprZExt(C, CI.getType()));
8643       }
8644
8645   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8646   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8647     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8648       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8649         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8650             And->getOperand(1) == C)
8651           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8652             Value *TI0 = TI->getOperand(0);
8653             if (TI0->getType() == CI.getType()) {
8654               Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
8655               Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8656               InsertNewInstBefore(NewAnd, *And);
8657               return BinaryOperator::CreateXor(NewAnd, ZC);
8658             }
8659           }
8660
8661   return 0;
8662 }
8663
8664 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8665   if (Instruction *I = commonIntCastTransforms(CI))
8666     return I;
8667   
8668   Value *Src = CI.getOperand(0);
8669   
8670   // Canonicalize sign-extend from i1 to a select.
8671   if (Src->getType() == Type::Int1Ty)
8672     return SelectInst::Create(Src,
8673                               Context->getAllOnesValue(CI.getType()),
8674                               Context->getNullValue(CI.getType()));
8675
8676   // See if the value being truncated is already sign extended.  If so, just
8677   // eliminate the trunc/sext pair.
8678   if (Operator::getOpcode(Src) == Instruction::Trunc) {
8679     Value *Op = cast<User>(Src)->getOperand(0);
8680     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8681     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8682     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8683     unsigned NumSignBits = ComputeNumSignBits(Op);
8684
8685     if (OpBits == DestBits) {
8686       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8687       // bits, it is already ready.
8688       if (NumSignBits > DestBits-MidBits)
8689         return ReplaceInstUsesWith(CI, Op);
8690     } else if (OpBits < DestBits) {
8691       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8692       // bits, just sext from i32.
8693       if (NumSignBits > OpBits-MidBits)
8694         return new SExtInst(Op, CI.getType(), "tmp");
8695     } else {
8696       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8697       // bits, just truncate to i32.
8698       if (NumSignBits > OpBits-MidBits)
8699         return new TruncInst(Op, CI.getType(), "tmp");
8700     }
8701   }
8702
8703   // If the input is a shl/ashr pair of a same constant, then this is a sign
8704   // extension from a smaller value.  If we could trust arbitrary bitwidth
8705   // integers, we could turn this into a truncate to the smaller bit and then
8706   // use a sext for the whole extension.  Since we don't, look deeper and check
8707   // for a truncate.  If the source and dest are the same type, eliminate the
8708   // trunc and extend and just do shifts.  For example, turn:
8709   //   %a = trunc i32 %i to i8
8710   //   %b = shl i8 %a, 6
8711   //   %c = ashr i8 %b, 6
8712   //   %d = sext i8 %c to i32
8713   // into:
8714   //   %a = shl i32 %i, 30
8715   //   %d = ashr i32 %a, 30
8716   Value *A = 0;
8717   ConstantInt *BA = 0, *CA = 0;
8718   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8719                         m_ConstantInt(CA)), *Context) &&
8720       BA == CA && isa<TruncInst>(A)) {
8721     Value *I = cast<TruncInst>(A)->getOperand(0);
8722     if (I->getType() == CI.getType()) {
8723       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8724       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8725       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8726       Constant *ShAmtV = Context->getConstantInt(CI.getType(), ShAmt);
8727       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8728                                                         CI.getName()), CI);
8729       return BinaryOperator::CreateAShr(I, ShAmtV);
8730     }
8731   }
8732   
8733   return 0;
8734 }
8735
8736 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8737 /// in the specified FP type without changing its value.
8738 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8739                               LLVMContext *Context) {
8740   bool losesInfo;
8741   APFloat F = CFP->getValueAPF();
8742   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8743   if (!losesInfo)
8744     return Context->getConstantFP(F);
8745   return 0;
8746 }
8747
8748 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8749 /// through it until we get the source value.
8750 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8751   if (Instruction *I = dyn_cast<Instruction>(V))
8752     if (I->getOpcode() == Instruction::FPExt)
8753       return LookThroughFPExtensions(I->getOperand(0), Context);
8754   
8755   // If this value is a constant, return the constant in the smallest FP type
8756   // that can accurately represent it.  This allows us to turn
8757   // (float)((double)X+2.0) into x+2.0f.
8758   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8759     if (CFP->getType() == Type::PPC_FP128Ty)
8760       return V;  // No constant folding of this.
8761     // See if the value can be truncated to float and then reextended.
8762     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8763       return V;
8764     if (CFP->getType() == Type::DoubleTy)
8765       return V;  // Won't shrink.
8766     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8767       return V;
8768     // Don't try to shrink to various long double types.
8769   }
8770   
8771   return V;
8772 }
8773
8774 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8775   if (Instruction *I = commonCastTransforms(CI))
8776     return I;
8777   
8778   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8779   // smaller than the destination type, we can eliminate the truncate by doing
8780   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8781   // many builtins (sqrt, etc).
8782   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8783   if (OpI && OpI->hasOneUse()) {
8784     switch (OpI->getOpcode()) {
8785     default: break;
8786     case Instruction::FAdd:
8787     case Instruction::FSub:
8788     case Instruction::FMul:
8789     case Instruction::FDiv:
8790     case Instruction::FRem:
8791       const Type *SrcTy = OpI->getType();
8792       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8793       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8794       if (LHSTrunc->getType() != SrcTy && 
8795           RHSTrunc->getType() != SrcTy) {
8796         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8797         // If the source types were both smaller than the destination type of
8798         // the cast, do this xform.
8799         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8800             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8801           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8802                                       CI.getType(), CI);
8803           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8804                                       CI.getType(), CI);
8805           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8806         }
8807       }
8808       break;  
8809     }
8810   }
8811   return 0;
8812 }
8813
8814 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8815   return commonCastTransforms(CI);
8816 }
8817
8818 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8819   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8820   if (OpI == 0)
8821     return commonCastTransforms(FI);
8822
8823   // fptoui(uitofp(X)) --> X
8824   // fptoui(sitofp(X)) --> X
8825   // This is safe if the intermediate type has enough bits in its mantissa to
8826   // accurately represent all values of X.  For example, do not do this with
8827   // i64->float->i64.  This is also safe for sitofp case, because any negative
8828   // 'X' value would cause an undefined result for the fptoui. 
8829   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8830       OpI->getOperand(0)->getType() == FI.getType() &&
8831       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8832                     OpI->getType()->getFPMantissaWidth())
8833     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8834
8835   return commonCastTransforms(FI);
8836 }
8837
8838 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8839   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8840   if (OpI == 0)
8841     return commonCastTransforms(FI);
8842   
8843   // fptosi(sitofp(X)) --> X
8844   // fptosi(uitofp(X)) --> X
8845   // This is safe if the intermediate type has enough bits in its mantissa to
8846   // accurately represent all values of X.  For example, do not do this with
8847   // i64->float->i64.  This is also safe for sitofp case, because any negative
8848   // 'X' value would cause an undefined result for the fptoui. 
8849   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8850       OpI->getOperand(0)->getType() == FI.getType() &&
8851       (int)FI.getType()->getScalarSizeInBits() <=
8852                     OpI->getType()->getFPMantissaWidth())
8853     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8854   
8855   return commonCastTransforms(FI);
8856 }
8857
8858 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8859   return commonCastTransforms(CI);
8860 }
8861
8862 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8863   return commonCastTransforms(CI);
8864 }
8865
8866 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8867   // If the destination integer type is smaller than the intptr_t type for
8868   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8869   // trunc to be exposed to other transforms.  Don't do this for extending
8870   // ptrtoint's, because we don't know if the target sign or zero extends its
8871   // pointers.
8872   if (TD &&
8873       CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8874     Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8875                                                     TD->getIntPtrType(),
8876                                                     "tmp"), CI);
8877     return new TruncInst(P, CI.getType());
8878   }
8879   
8880   return commonPointerCastTransforms(CI);
8881 }
8882
8883 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8884   // If the source integer type is larger than the intptr_t type for
8885   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8886   // allows the trunc to be exposed to other transforms.  Don't do this for
8887   // extending inttoptr's, because we don't know if the target sign or zero
8888   // extends to pointers.
8889   if (TD &&
8890       CI.getOperand(0)->getType()->getScalarSizeInBits() >
8891       TD->getPointerSizeInBits()) {
8892     Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8893                                                  TD->getIntPtrType(),
8894                                                  "tmp"), CI);
8895     return new IntToPtrInst(P, CI.getType());
8896   }
8897   
8898   if (Instruction *I = commonCastTransforms(CI))
8899     return I;
8900
8901   return 0;
8902 }
8903
8904 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8905   // If the operands are integer typed then apply the integer transforms,
8906   // otherwise just apply the common ones.
8907   Value *Src = CI.getOperand(0);
8908   const Type *SrcTy = Src->getType();
8909   const Type *DestTy = CI.getType();
8910
8911   if (isa<PointerType>(SrcTy)) {
8912     if (Instruction *I = commonPointerCastTransforms(CI))
8913       return I;
8914   } else {
8915     if (Instruction *Result = commonCastTransforms(CI))
8916       return Result;
8917   }
8918
8919
8920   // Get rid of casts from one type to the same type. These are useless and can
8921   // be replaced by the operand.
8922   if (DestTy == Src->getType())
8923     return ReplaceInstUsesWith(CI, Src);
8924
8925   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8926     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8927     const Type *DstElTy = DstPTy->getElementType();
8928     const Type *SrcElTy = SrcPTy->getElementType();
8929     
8930     // If the address spaces don't match, don't eliminate the bitcast, which is
8931     // required for changing types.
8932     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8933       return 0;
8934     
8935     // If we are casting a malloc or alloca to a pointer to a type of the same
8936     // size, rewrite the allocation instruction to allocate the "right" type.
8937     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8938       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8939         return V;
8940     
8941     // If the source and destination are pointers, and this cast is equivalent
8942     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8943     // This can enhance SROA and other transforms that want type-safe pointers.
8944     Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
8945     unsigned NumZeros = 0;
8946     while (SrcElTy != DstElTy && 
8947            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8948            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8949       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8950       ++NumZeros;
8951     }
8952
8953     // If we found a path from the src to dest, create the getelementptr now.
8954     if (SrcElTy == DstElTy) {
8955       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8956       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
8957                                        ((Instruction*) NULL));
8958     }
8959   }
8960
8961   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8962     if (DestVTy->getNumElements() == 1) {
8963       if (!isa<VectorType>(SrcTy)) {
8964         Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
8965                                        DestVTy->getElementType(), CI);
8966         return InsertElementInst::Create(Context->getUndef(DestTy), Elem,
8967                                          Context->getNullValue(Type::Int32Ty));
8968       }
8969       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8970     }
8971   }
8972
8973   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8974     if (SrcVTy->getNumElements() == 1) {
8975       if (!isa<VectorType>(DestTy)) {
8976         Instruction *Elem =
8977             new ExtractElementInst(Src, Context->getNullValue(Type::Int32Ty));
8978         InsertNewInstBefore(Elem, CI);
8979         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8980       }
8981     }
8982   }
8983
8984   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8985     if (SVI->hasOneUse()) {
8986       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8987       // a bitconvert to a vector with the same # elts.
8988       if (isa<VectorType>(DestTy) && 
8989           cast<VectorType>(DestTy)->getNumElements() ==
8990                 SVI->getType()->getNumElements() &&
8991           SVI->getType()->getNumElements() ==
8992             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8993         CastInst *Tmp;
8994         // If either of the operands is a cast from CI.getType(), then
8995         // evaluating the shuffle in the casted destination's type will allow
8996         // us to eliminate at least one cast.
8997         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8998              Tmp->getOperand(0)->getType() == DestTy) ||
8999             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
9000              Tmp->getOperand(0)->getType() == DestTy)) {
9001           Value *LHS = InsertCastBefore(Instruction::BitCast,
9002                                         SVI->getOperand(0), DestTy, CI);
9003           Value *RHS = InsertCastBefore(Instruction::BitCast,
9004                                         SVI->getOperand(1), DestTy, CI);
9005           // Return a new shuffle vector.  Use the same element ID's, as we
9006           // know the vector types match #elts.
9007           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9008         }
9009       }
9010     }
9011   }
9012   return 0;
9013 }
9014
9015 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9016 ///   %C = or %A, %B
9017 ///   %D = select %cond, %C, %A
9018 /// into:
9019 ///   %C = select %cond, %B, 0
9020 ///   %D = or %A, %C
9021 ///
9022 /// Assuming that the specified instruction is an operand to the select, return
9023 /// a bitmask indicating which operands of this instruction are foldable if they
9024 /// equal the other incoming value of the select.
9025 ///
9026 static unsigned GetSelectFoldableOperands(Instruction *I) {
9027   switch (I->getOpcode()) {
9028   case Instruction::Add:
9029   case Instruction::Mul:
9030   case Instruction::And:
9031   case Instruction::Or:
9032   case Instruction::Xor:
9033     return 3;              // Can fold through either operand.
9034   case Instruction::Sub:   // Can only fold on the amount subtracted.
9035   case Instruction::Shl:   // Can only fold on the shift amount.
9036   case Instruction::LShr:
9037   case Instruction::AShr:
9038     return 1;
9039   default:
9040     return 0;              // Cannot fold
9041   }
9042 }
9043
9044 /// GetSelectFoldableConstant - For the same transformation as the previous
9045 /// function, return the identity constant that goes into the select.
9046 static Constant *GetSelectFoldableConstant(Instruction *I,
9047                                            LLVMContext *Context) {
9048   switch (I->getOpcode()) {
9049   default: llvm_unreachable("This cannot happen!");
9050   case Instruction::Add:
9051   case Instruction::Sub:
9052   case Instruction::Or:
9053   case Instruction::Xor:
9054   case Instruction::Shl:
9055   case Instruction::LShr:
9056   case Instruction::AShr:
9057     return Context->getNullValue(I->getType());
9058   case Instruction::And:
9059     return Context->getAllOnesValue(I->getType());
9060   case Instruction::Mul:
9061     return Context->getConstantInt(I->getType(), 1);
9062   }
9063 }
9064
9065 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9066 /// have the same opcode and only one use each.  Try to simplify this.
9067 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9068                                           Instruction *FI) {
9069   if (TI->getNumOperands() == 1) {
9070     // If this is a non-volatile load or a cast from the same type,
9071     // merge.
9072     if (TI->isCast()) {
9073       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9074         return 0;
9075     } else {
9076       return 0;  // unknown unary op.
9077     }
9078
9079     // Fold this by inserting a select from the input values.
9080     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9081                                            FI->getOperand(0), SI.getName()+".v");
9082     InsertNewInstBefore(NewSI, SI);
9083     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9084                             TI->getType());
9085   }
9086
9087   // Only handle binary operators here.
9088   if (!isa<BinaryOperator>(TI))
9089     return 0;
9090
9091   // Figure out if the operations have any operands in common.
9092   Value *MatchOp, *OtherOpT, *OtherOpF;
9093   bool MatchIsOpZero;
9094   if (TI->getOperand(0) == FI->getOperand(0)) {
9095     MatchOp  = TI->getOperand(0);
9096     OtherOpT = TI->getOperand(1);
9097     OtherOpF = FI->getOperand(1);
9098     MatchIsOpZero = true;
9099   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9100     MatchOp  = TI->getOperand(1);
9101     OtherOpT = TI->getOperand(0);
9102     OtherOpF = FI->getOperand(0);
9103     MatchIsOpZero = false;
9104   } else if (!TI->isCommutative()) {
9105     return 0;
9106   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9107     MatchOp  = TI->getOperand(0);
9108     OtherOpT = TI->getOperand(1);
9109     OtherOpF = FI->getOperand(0);
9110     MatchIsOpZero = true;
9111   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9112     MatchOp  = TI->getOperand(1);
9113     OtherOpT = TI->getOperand(0);
9114     OtherOpF = FI->getOperand(1);
9115     MatchIsOpZero = true;
9116   } else {
9117     return 0;
9118   }
9119
9120   // If we reach here, they do have operations in common.
9121   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9122                                          OtherOpF, SI.getName()+".v");
9123   InsertNewInstBefore(NewSI, SI);
9124
9125   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9126     if (MatchIsOpZero)
9127       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9128     else
9129       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9130   }
9131   llvm_unreachable("Shouldn't get here");
9132   return 0;
9133 }
9134
9135 static bool isSelect01(Constant *C1, Constant *C2) {
9136   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9137   if (!C1I)
9138     return false;
9139   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9140   if (!C2I)
9141     return false;
9142   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9143 }
9144
9145 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9146 /// facilitate further optimization.
9147 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9148                                             Value *FalseVal) {
9149   // See the comment above GetSelectFoldableOperands for a description of the
9150   // transformation we are doing here.
9151   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9152     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9153         !isa<Constant>(FalseVal)) {
9154       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9155         unsigned OpToFold = 0;
9156         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9157           OpToFold = 1;
9158         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9159           OpToFold = 2;
9160         }
9161
9162         if (OpToFold) {
9163           Constant *C = GetSelectFoldableConstant(TVI, Context);
9164           Value *OOp = TVI->getOperand(2-OpToFold);
9165           // Avoid creating select between 2 constants unless it's selecting
9166           // between 0 and 1.
9167           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9168             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9169             InsertNewInstBefore(NewSel, SI);
9170             NewSel->takeName(TVI);
9171             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9172               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9173             llvm_unreachable("Unknown instruction!!");
9174           }
9175         }
9176       }
9177     }
9178   }
9179
9180   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9181     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9182         !isa<Constant>(TrueVal)) {
9183       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9184         unsigned OpToFold = 0;
9185         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9186           OpToFold = 1;
9187         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9188           OpToFold = 2;
9189         }
9190
9191         if (OpToFold) {
9192           Constant *C = GetSelectFoldableConstant(FVI, Context);
9193           Value *OOp = FVI->getOperand(2-OpToFold);
9194           // Avoid creating select between 2 constants unless it's selecting
9195           // between 0 and 1.
9196           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9197             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9198             InsertNewInstBefore(NewSel, SI);
9199             NewSel->takeName(FVI);
9200             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9201               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9202             llvm_unreachable("Unknown instruction!!");
9203           }
9204         }
9205       }
9206     }
9207   }
9208
9209   return 0;
9210 }
9211
9212 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9213 /// ICmpInst as its first operand.
9214 ///
9215 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9216                                                    ICmpInst *ICI) {
9217   bool Changed = false;
9218   ICmpInst::Predicate Pred = ICI->getPredicate();
9219   Value *CmpLHS = ICI->getOperand(0);
9220   Value *CmpRHS = ICI->getOperand(1);
9221   Value *TrueVal = SI.getTrueValue();
9222   Value *FalseVal = SI.getFalseValue();
9223
9224   // Check cases where the comparison is with a constant that
9225   // can be adjusted to fit the min/max idiom. We may edit ICI in
9226   // place here, so make sure the select is the only user.
9227   if (ICI->hasOneUse())
9228     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9229       switch (Pred) {
9230       default: break;
9231       case ICmpInst::ICMP_ULT:
9232       case ICmpInst::ICMP_SLT: {
9233         // X < MIN ? T : F  -->  F
9234         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9235           return ReplaceInstUsesWith(SI, FalseVal);
9236         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9237         Constant *AdjustedRHS = SubOne(CI, Context);
9238         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9239             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9240           Pred = ICmpInst::getSwappedPredicate(Pred);
9241           CmpRHS = AdjustedRHS;
9242           std::swap(FalseVal, TrueVal);
9243           ICI->setPredicate(Pred);
9244           ICI->setOperand(1, CmpRHS);
9245           SI.setOperand(1, TrueVal);
9246           SI.setOperand(2, FalseVal);
9247           Changed = true;
9248         }
9249         break;
9250       }
9251       case ICmpInst::ICMP_UGT:
9252       case ICmpInst::ICMP_SGT: {
9253         // X > MAX ? T : F  -->  F
9254         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9255           return ReplaceInstUsesWith(SI, FalseVal);
9256         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9257         Constant *AdjustedRHS = AddOne(CI, Context);
9258         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9259             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9260           Pred = ICmpInst::getSwappedPredicate(Pred);
9261           CmpRHS = AdjustedRHS;
9262           std::swap(FalseVal, TrueVal);
9263           ICI->setPredicate(Pred);
9264           ICI->setOperand(1, CmpRHS);
9265           SI.setOperand(1, TrueVal);
9266           SI.setOperand(2, FalseVal);
9267           Changed = true;
9268         }
9269         break;
9270       }
9271       }
9272
9273       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9274       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9275       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9276       if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9277           match(FalseVal, m_ConstantInt<0>(), *Context))
9278         Pred = ICI->getPredicate();
9279       else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9280                match(FalseVal, m_ConstantInt<-1>(), *Context))
9281         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9282       
9283       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9284         // If we are just checking for a icmp eq of a single bit and zext'ing it
9285         // to an integer, then shift the bit to the appropriate place and then
9286         // cast to integer to avoid the comparison.
9287         const APInt &Op1CV = CI->getValue();
9288     
9289         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9290         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9291         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9292             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9293           Value *In = ICI->getOperand(0);
9294           Value *Sh = Context->getConstantInt(In->getType(),
9295                                        In->getType()->getScalarSizeInBits()-1);
9296           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9297                                                           In->getName()+".lobit"),
9298                                    *ICI);
9299           if (In->getType() != SI.getType())
9300             In = CastInst::CreateIntegerCast(In, SI.getType(),
9301                                              true/*SExt*/, "tmp", ICI);
9302     
9303           if (Pred == ICmpInst::ICMP_SGT)
9304             In = InsertNewInstBefore(BinaryOperator::CreateNot(*Context, In,
9305                                        In->getName()+".not"), *ICI);
9306     
9307           return ReplaceInstUsesWith(SI, In);
9308         }
9309       }
9310     }
9311
9312   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9313     // Transform (X == Y) ? X : Y  -> Y
9314     if (Pred == ICmpInst::ICMP_EQ)
9315       return ReplaceInstUsesWith(SI, FalseVal);
9316     // Transform (X != Y) ? X : Y  -> X
9317     if (Pred == ICmpInst::ICMP_NE)
9318       return ReplaceInstUsesWith(SI, TrueVal);
9319     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9320
9321   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9322     // Transform (X == Y) ? Y : X  -> X
9323     if (Pred == ICmpInst::ICMP_EQ)
9324       return ReplaceInstUsesWith(SI, FalseVal);
9325     // Transform (X != Y) ? Y : X  -> Y
9326     if (Pred == ICmpInst::ICMP_NE)
9327       return ReplaceInstUsesWith(SI, TrueVal);
9328     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9329   }
9330
9331   /// NOTE: if we wanted to, this is where to detect integer ABS
9332
9333   return Changed ? &SI : 0;
9334 }
9335
9336 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9337   Value *CondVal = SI.getCondition();
9338   Value *TrueVal = SI.getTrueValue();
9339   Value *FalseVal = SI.getFalseValue();
9340
9341   // select true, X, Y  -> X
9342   // select false, X, Y -> Y
9343   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9344     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9345
9346   // select C, X, X -> X
9347   if (TrueVal == FalseVal)
9348     return ReplaceInstUsesWith(SI, TrueVal);
9349
9350   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9351     return ReplaceInstUsesWith(SI, FalseVal);
9352   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9353     return ReplaceInstUsesWith(SI, TrueVal);
9354   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9355     if (isa<Constant>(TrueVal))
9356       return ReplaceInstUsesWith(SI, TrueVal);
9357     else
9358       return ReplaceInstUsesWith(SI, FalseVal);
9359   }
9360
9361   if (SI.getType() == Type::Int1Ty) {
9362     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9363       if (C->getZExtValue()) {
9364         // Change: A = select B, true, C --> A = or B, C
9365         return BinaryOperator::CreateOr(CondVal, FalseVal);
9366       } else {
9367         // Change: A = select B, false, C --> A = and !B, C
9368         Value *NotCond =
9369           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9370                                              "not."+CondVal->getName()), SI);
9371         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9372       }
9373     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9374       if (C->getZExtValue() == false) {
9375         // Change: A = select B, C, false --> A = and B, C
9376         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9377       } else {
9378         // Change: A = select B, C, true --> A = or !B, C
9379         Value *NotCond =
9380           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9381                                              "not."+CondVal->getName()), SI);
9382         return BinaryOperator::CreateOr(NotCond, TrueVal);
9383       }
9384     }
9385     
9386     // select a, b, a  -> a&b
9387     // select a, a, b  -> a|b
9388     if (CondVal == TrueVal)
9389       return BinaryOperator::CreateOr(CondVal, FalseVal);
9390     else if (CondVal == FalseVal)
9391       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9392   }
9393
9394   // Selecting between two integer constants?
9395   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9396     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9397       // select C, 1, 0 -> zext C to int
9398       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9399         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9400       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9401         // select C, 0, 1 -> zext !C to int
9402         Value *NotCond =
9403           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9404                                                "not."+CondVal->getName()), SI);
9405         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9406       }
9407
9408       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9409         // If one of the constants is zero (we know they can't both be) and we
9410         // have an icmp instruction with zero, and we have an 'and' with the
9411         // non-constant value, eliminate this whole mess.  This corresponds to
9412         // cases like this: ((X & 27) ? 27 : 0)
9413         if (TrueValC->isZero() || FalseValC->isZero())
9414           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9415               cast<Constant>(IC->getOperand(1))->isNullValue())
9416             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9417               if (ICA->getOpcode() == Instruction::And &&
9418                   isa<ConstantInt>(ICA->getOperand(1)) &&
9419                   (ICA->getOperand(1) == TrueValC ||
9420                    ICA->getOperand(1) == FalseValC) &&
9421                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9422                 // Okay, now we know that everything is set up, we just don't
9423                 // know whether we have a icmp_ne or icmp_eq and whether the 
9424                 // true or false val is the zero.
9425                 bool ShouldNotVal = !TrueValC->isZero();
9426                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9427                 Value *V = ICA;
9428                 if (ShouldNotVal)
9429                   V = InsertNewInstBefore(BinaryOperator::Create(
9430                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9431                 return ReplaceInstUsesWith(SI, V);
9432               }
9433       }
9434     }
9435
9436   // See if we are selecting two values based on a comparison of the two values.
9437   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9438     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9439       // Transform (X == Y) ? X : Y  -> Y
9440       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9441         // This is not safe in general for floating point:  
9442         // consider X== -0, Y== +0.
9443         // It becomes safe if either operand is a nonzero constant.
9444         ConstantFP *CFPt, *CFPf;
9445         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9446               !CFPt->getValueAPF().isZero()) ||
9447             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9448              !CFPf->getValueAPF().isZero()))
9449         return ReplaceInstUsesWith(SI, FalseVal);
9450       }
9451       // Transform (X != Y) ? X : Y  -> X
9452       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9453         return ReplaceInstUsesWith(SI, TrueVal);
9454       // NOTE: if we wanted to, this is where to detect MIN/MAX
9455
9456     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9457       // Transform (X == Y) ? Y : X  -> X
9458       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9459         // This is not safe in general for floating point:  
9460         // consider X== -0, Y== +0.
9461         // It becomes safe if either operand is a nonzero constant.
9462         ConstantFP *CFPt, *CFPf;
9463         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9464               !CFPt->getValueAPF().isZero()) ||
9465             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9466              !CFPf->getValueAPF().isZero()))
9467           return ReplaceInstUsesWith(SI, FalseVal);
9468       }
9469       // Transform (X != Y) ? Y : X  -> Y
9470       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9471         return ReplaceInstUsesWith(SI, TrueVal);
9472       // NOTE: if we wanted to, this is where to detect MIN/MAX
9473     }
9474     // NOTE: if we wanted to, this is where to detect ABS
9475   }
9476
9477   // See if we are selecting two values based on a comparison of the two values.
9478   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9479     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9480       return Result;
9481
9482   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9483     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9484       if (TI->hasOneUse() && FI->hasOneUse()) {
9485         Instruction *AddOp = 0, *SubOp = 0;
9486
9487         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9488         if (TI->getOpcode() == FI->getOpcode())
9489           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9490             return IV;
9491
9492         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9493         // even legal for FP.
9494         if ((TI->getOpcode() == Instruction::Sub &&
9495              FI->getOpcode() == Instruction::Add) ||
9496             (TI->getOpcode() == Instruction::FSub &&
9497              FI->getOpcode() == Instruction::FAdd)) {
9498           AddOp = FI; SubOp = TI;
9499         } else if ((FI->getOpcode() == Instruction::Sub &&
9500                     TI->getOpcode() == Instruction::Add) ||
9501                    (FI->getOpcode() == Instruction::FSub &&
9502                     TI->getOpcode() == Instruction::FAdd)) {
9503           AddOp = TI; SubOp = FI;
9504         }
9505
9506         if (AddOp) {
9507           Value *OtherAddOp = 0;
9508           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9509             OtherAddOp = AddOp->getOperand(1);
9510           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9511             OtherAddOp = AddOp->getOperand(0);
9512           }
9513
9514           if (OtherAddOp) {
9515             // So at this point we know we have (Y -> OtherAddOp):
9516             //        select C, (add X, Y), (sub X, Z)
9517             Value *NegVal;  // Compute -Z
9518             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9519               NegVal = Context->getConstantExprNeg(C);
9520             } else {
9521               NegVal = InsertNewInstBefore(
9522                     BinaryOperator::CreateNeg(*Context, SubOp->getOperand(1),
9523                                               "tmp"), SI);
9524             }
9525
9526             Value *NewTrueOp = OtherAddOp;
9527             Value *NewFalseOp = NegVal;
9528             if (AddOp != TI)
9529               std::swap(NewTrueOp, NewFalseOp);
9530             Instruction *NewSel =
9531               SelectInst::Create(CondVal, NewTrueOp,
9532                                  NewFalseOp, SI.getName() + ".p");
9533
9534             NewSel = InsertNewInstBefore(NewSel, SI);
9535             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9536           }
9537         }
9538       }
9539
9540   // See if we can fold the select into one of our operands.
9541   if (SI.getType()->isInteger()) {
9542     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9543     if (FoldI)
9544       return FoldI;
9545   }
9546
9547   if (BinaryOperator::isNot(CondVal)) {
9548     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9549     SI.setOperand(1, FalseVal);
9550     SI.setOperand(2, TrueVal);
9551     return &SI;
9552   }
9553
9554   return 0;
9555 }
9556
9557 /// EnforceKnownAlignment - If the specified pointer points to an object that
9558 /// we control, modify the object's alignment to PrefAlign. This isn't
9559 /// often possible though. If alignment is important, a more reliable approach
9560 /// is to simply align all global variables and allocation instructions to
9561 /// their preferred alignment from the beginning.
9562 ///
9563 static unsigned EnforceKnownAlignment(Value *V,
9564                                       unsigned Align, unsigned PrefAlign) {
9565
9566   User *U = dyn_cast<User>(V);
9567   if (!U) return Align;
9568
9569   switch (Operator::getOpcode(U)) {
9570   default: break;
9571   case Instruction::BitCast:
9572     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9573   case Instruction::GetElementPtr: {
9574     // If all indexes are zero, it is just the alignment of the base pointer.
9575     bool AllZeroOperands = true;
9576     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9577       if (!isa<Constant>(*i) ||
9578           !cast<Constant>(*i)->isNullValue()) {
9579         AllZeroOperands = false;
9580         break;
9581       }
9582
9583     if (AllZeroOperands) {
9584       // Treat this like a bitcast.
9585       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9586     }
9587     break;
9588   }
9589   }
9590
9591   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9592     // If there is a large requested alignment and we can, bump up the alignment
9593     // of the global.
9594     if (!GV->isDeclaration()) {
9595       if (GV->getAlignment() >= PrefAlign)
9596         Align = GV->getAlignment();
9597       else {
9598         GV->setAlignment(PrefAlign);
9599         Align = PrefAlign;
9600       }
9601     }
9602   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9603     // If there is a requested alignment and if this is an alloca, round up.  We
9604     // don't do this for malloc, because some systems can't respect the request.
9605     if (isa<AllocaInst>(AI)) {
9606       if (AI->getAlignment() >= PrefAlign)
9607         Align = AI->getAlignment();
9608       else {
9609         AI->setAlignment(PrefAlign);
9610         Align = PrefAlign;
9611       }
9612     }
9613   }
9614
9615   return Align;
9616 }
9617
9618 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9619 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9620 /// and it is more than the alignment of the ultimate object, see if we can
9621 /// increase the alignment of the ultimate object, making this check succeed.
9622 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9623                                                   unsigned PrefAlign) {
9624   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9625                       sizeof(PrefAlign) * CHAR_BIT;
9626   APInt Mask = APInt::getAllOnesValue(BitWidth);
9627   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9628   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9629   unsigned TrailZ = KnownZero.countTrailingOnes();
9630   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9631
9632   if (PrefAlign > Align)
9633     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9634   
9635     // We don't need to make any adjustment.
9636   return Align;
9637 }
9638
9639 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9640   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9641   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9642   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9643   unsigned CopyAlign = MI->getAlignment();
9644
9645   if (CopyAlign < MinAlign) {
9646     MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(), 
9647                                              MinAlign, false));
9648     return MI;
9649   }
9650   
9651   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9652   // load/store.
9653   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9654   if (MemOpLength == 0) return 0;
9655   
9656   // Source and destination pointer types are always "i8*" for intrinsic.  See
9657   // if the size is something we can handle with a single primitive load/store.
9658   // A single load+store correctly handles overlapping memory in the memmove
9659   // case.
9660   unsigned Size = MemOpLength->getZExtValue();
9661   if (Size == 0) return MI;  // Delete this mem transfer.
9662   
9663   if (Size > 8 || (Size&(Size-1)))
9664     return 0;  // If not 1/2/4/8 bytes, exit.
9665   
9666   // Use an integer load+store unless we can find something better.
9667   Type *NewPtrTy =
9668                 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
9669   
9670   // Memcpy forces the use of i8* for the source and destination.  That means
9671   // that if you're using memcpy to move one double around, you'll get a cast
9672   // from double* to i8*.  We'd much rather use a double load+store rather than
9673   // an i64 load+store, here because this improves the odds that the source or
9674   // dest address will be promotable.  See if we can find a better type than the
9675   // integer datatype.
9676   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9677     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9678     if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9679       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9680       // down through these levels if so.
9681       while (!SrcETy->isSingleValueType()) {
9682         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9683           if (STy->getNumElements() == 1)
9684             SrcETy = STy->getElementType(0);
9685           else
9686             break;
9687         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9688           if (ATy->getNumElements() == 1)
9689             SrcETy = ATy->getElementType();
9690           else
9691             break;
9692         } else
9693           break;
9694       }
9695       
9696       if (SrcETy->isSingleValueType())
9697         NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
9698     }
9699   }
9700   
9701   
9702   // If the memcpy/memmove provides better alignment info than we can
9703   // infer, use it.
9704   SrcAlign = std::max(SrcAlign, CopyAlign);
9705   DstAlign = std::max(DstAlign, CopyAlign);
9706   
9707   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9708   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9709   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9710   InsertNewInstBefore(L, *MI);
9711   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9712
9713   // Set the size of the copy to 0, it will be deleted on the next iteration.
9714   MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
9715   return MI;
9716 }
9717
9718 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9719   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9720   if (MI->getAlignment() < Alignment) {
9721     MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9722                                              Alignment, false));
9723     return MI;
9724   }
9725   
9726   // Extract the length and alignment and fill if they are constant.
9727   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9728   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9729   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9730     return 0;
9731   uint64_t Len = LenC->getZExtValue();
9732   Alignment = MI->getAlignment();
9733   
9734   // If the length is zero, this is a no-op
9735   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9736   
9737   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9738   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9739     const Type *ITy = Context->getIntegerType(Len*8);  // n=1 -> i8.
9740     
9741     Value *Dest = MI->getDest();
9742     Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
9743
9744     // Alignment 0 is identity for alignment 1 for memset, but not store.
9745     if (Alignment == 0) Alignment = 1;
9746     
9747     // Extract the fill value and store.
9748     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9749     InsertNewInstBefore(new StoreInst(Context->getConstantInt(ITy, Fill),
9750                                       Dest, false, Alignment), *MI);
9751     
9752     // Set the size of the copy to 0, it will be deleted on the next iteration.
9753     MI->setLength(Context->getNullValue(LenC->getType()));
9754     return MI;
9755   }
9756
9757   return 0;
9758 }
9759
9760
9761 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9762 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9763 /// the heavy lifting.
9764 ///
9765 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9766   // If the caller function is nounwind, mark the call as nounwind, even if the
9767   // callee isn't.
9768   if (CI.getParent()->getParent()->doesNotThrow() &&
9769       !CI.doesNotThrow()) {
9770     CI.setDoesNotThrow();
9771     return &CI;
9772   }
9773   
9774   
9775   
9776   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9777   if (!II) return visitCallSite(&CI);
9778   
9779   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9780   // visitCallSite.
9781   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9782     bool Changed = false;
9783
9784     // memmove/cpy/set of zero bytes is a noop.
9785     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9786       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9787
9788       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9789         if (CI->getZExtValue() == 1) {
9790           // Replace the instruction with just byte operations.  We would
9791           // transform other cases to loads/stores, but we don't know if
9792           // alignment is sufficient.
9793         }
9794     }
9795
9796     // If we have a memmove and the source operation is a constant global,
9797     // then the source and dest pointers can't alias, so we can change this
9798     // into a call to memcpy.
9799     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9800       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9801         if (GVSrc->isConstant()) {
9802           Module *M = CI.getParent()->getParent()->getParent();
9803           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9804           const Type *Tys[1];
9805           Tys[0] = CI.getOperand(3)->getType();
9806           CI.setOperand(0, 
9807                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9808           Changed = true;
9809         }
9810
9811       // memmove(x,x,size) -> noop.
9812       if (MMI->getSource() == MMI->getDest())
9813         return EraseInstFromFunction(CI);
9814     }
9815
9816     // If we can determine a pointer alignment that is bigger than currently
9817     // set, update the alignment.
9818     if (isa<MemTransferInst>(MI)) {
9819       if (Instruction *I = SimplifyMemTransfer(MI))
9820         return I;
9821     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9822       if (Instruction *I = SimplifyMemSet(MSI))
9823         return I;
9824     }
9825           
9826     if (Changed) return II;
9827   }
9828   
9829   switch (II->getIntrinsicID()) {
9830   default: break;
9831   case Intrinsic::bswap:
9832     // bswap(bswap(x)) -> x
9833     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9834       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9835         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9836     break;
9837   case Intrinsic::ppc_altivec_lvx:
9838   case Intrinsic::ppc_altivec_lvxl:
9839   case Intrinsic::x86_sse_loadu_ps:
9840   case Intrinsic::x86_sse2_loadu_pd:
9841   case Intrinsic::x86_sse2_loadu_dq:
9842     // Turn PPC lvx     -> load if the pointer is known aligned.
9843     // Turn X86 loadups -> load if the pointer is known aligned.
9844     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9845       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9846                                    Context->getPointerTypeUnqual(II->getType()),
9847                                        CI);
9848       return new LoadInst(Ptr);
9849     }
9850     break;
9851   case Intrinsic::ppc_altivec_stvx:
9852   case Intrinsic::ppc_altivec_stvxl:
9853     // Turn stvx -> store if the pointer is known aligned.
9854     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9855       const Type *OpPtrTy = 
9856         Context->getPointerTypeUnqual(II->getOperand(1)->getType());
9857       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9858       return new StoreInst(II->getOperand(1), Ptr);
9859     }
9860     break;
9861   case Intrinsic::x86_sse_storeu_ps:
9862   case Intrinsic::x86_sse2_storeu_pd:
9863   case Intrinsic::x86_sse2_storeu_dq:
9864     // Turn X86 storeu -> store if the pointer is known aligned.
9865     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9866       const Type *OpPtrTy = 
9867         Context->getPointerTypeUnqual(II->getOperand(2)->getType());
9868       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9869       return new StoreInst(II->getOperand(2), Ptr);
9870     }
9871     break;
9872     
9873   case Intrinsic::x86_sse_cvttss2si: {
9874     // These intrinsics only demands the 0th element of its input vector.  If
9875     // we can simplify the input based on that, do so now.
9876     unsigned VWidth =
9877       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9878     APInt DemandedElts(VWidth, 1);
9879     APInt UndefElts(VWidth, 0);
9880     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9881                                               UndefElts)) {
9882       II->setOperand(1, V);
9883       return II;
9884     }
9885     break;
9886   }
9887     
9888   case Intrinsic::ppc_altivec_vperm:
9889     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9890     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9891       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9892       
9893       // Check that all of the elements are integer constants or undefs.
9894       bool AllEltsOk = true;
9895       for (unsigned i = 0; i != 16; ++i) {
9896         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9897             !isa<UndefValue>(Mask->getOperand(i))) {
9898           AllEltsOk = false;
9899           break;
9900         }
9901       }
9902       
9903       if (AllEltsOk) {
9904         // Cast the input vectors to byte vectors.
9905         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9906         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9907         Value *Result = Context->getUndef(Op0->getType());
9908         
9909         // Only extract each element once.
9910         Value *ExtractedElts[32];
9911         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9912         
9913         for (unsigned i = 0; i != 16; ++i) {
9914           if (isa<UndefValue>(Mask->getOperand(i)))
9915             continue;
9916           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9917           Idx &= 31;  // Match the hardware behavior.
9918           
9919           if (ExtractedElts[Idx] == 0) {
9920             Instruction *Elt = 
9921               new ExtractElementInst(Idx < 16 ? Op0 : Op1, 
9922                   Context->getConstantInt(Type::Int32Ty, Idx&15, false), "tmp");
9923             InsertNewInstBefore(Elt, CI);
9924             ExtractedElts[Idx] = Elt;
9925           }
9926         
9927           // Insert this value into the result vector.
9928           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9929                                Context->getConstantInt(Type::Int32Ty, i, false), 
9930                                "tmp");
9931           InsertNewInstBefore(cast<Instruction>(Result), CI);
9932         }
9933         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9934       }
9935     }
9936     break;
9937
9938   case Intrinsic::stackrestore: {
9939     // If the save is right next to the restore, remove the restore.  This can
9940     // happen when variable allocas are DCE'd.
9941     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9942       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9943         BasicBlock::iterator BI = SS;
9944         if (&*++BI == II)
9945           return EraseInstFromFunction(CI);
9946       }
9947     }
9948     
9949     // Scan down this block to see if there is another stack restore in the
9950     // same block without an intervening call/alloca.
9951     BasicBlock::iterator BI = II;
9952     TerminatorInst *TI = II->getParent()->getTerminator();
9953     bool CannotRemove = false;
9954     for (++BI; &*BI != TI; ++BI) {
9955       if (isa<AllocaInst>(BI)) {
9956         CannotRemove = true;
9957         break;
9958       }
9959       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9960         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9961           // If there is a stackrestore below this one, remove this one.
9962           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9963             return EraseInstFromFunction(CI);
9964           // Otherwise, ignore the intrinsic.
9965         } else {
9966           // If we found a non-intrinsic call, we can't remove the stack
9967           // restore.
9968           CannotRemove = true;
9969           break;
9970         }
9971       }
9972     }
9973     
9974     // If the stack restore is in a return/unwind block and if there are no
9975     // allocas or calls between the restore and the return, nuke the restore.
9976     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9977       return EraseInstFromFunction(CI);
9978     break;
9979   }
9980   }
9981
9982   return visitCallSite(II);
9983 }
9984
9985 // InvokeInst simplification
9986 //
9987 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9988   return visitCallSite(&II);
9989 }
9990
9991 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9992 /// passed through the varargs area, we can eliminate the use of the cast.
9993 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9994                                          const CastInst * const CI,
9995                                          const TargetData * const TD,
9996                                          const int ix) {
9997   if (!CI->isLosslessCast())
9998     return false;
9999
10000   // The size of ByVal arguments is derived from the type, so we
10001   // can't change to a type with a different size.  If the size were
10002   // passed explicitly we could avoid this check.
10003   if (!CS.paramHasAttr(ix, Attribute::ByVal))
10004     return true;
10005
10006   const Type* SrcTy = 
10007             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10008   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10009   if (!SrcTy->isSized() || !DstTy->isSized())
10010     return false;
10011   if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10012     return false;
10013   return true;
10014 }
10015
10016 // visitCallSite - Improvements for call and invoke instructions.
10017 //
10018 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10019   bool Changed = false;
10020
10021   // If the callee is a constexpr cast of a function, attempt to move the cast
10022   // to the arguments of the call/invoke.
10023   if (transformConstExprCastCall(CS)) return 0;
10024
10025   Value *Callee = CS.getCalledValue();
10026
10027   if (Function *CalleeF = dyn_cast<Function>(Callee))
10028     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10029       Instruction *OldCall = CS.getInstruction();
10030       // If the call and callee calling conventions don't match, this call must
10031       // be unreachable, as the call is undefined.
10032       new StoreInst(Context->getTrue(),
10033                 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), 
10034                                   OldCall);
10035       if (!OldCall->use_empty())
10036         OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
10037       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10038         return EraseInstFromFunction(*OldCall);
10039       return 0;
10040     }
10041
10042   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10043     // This instruction is not reachable, just remove it.  We insert a store to
10044     // undef so that we know that this code is not reachable, despite the fact
10045     // that we can't modify the CFG here.
10046     new StoreInst(Context->getTrue(),
10047                Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10048                   CS.getInstruction());
10049
10050     if (!CS.getInstruction()->use_empty())
10051       CS.getInstruction()->
10052         replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
10053
10054     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10055       // Don't break the CFG, insert a dummy cond branch.
10056       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10057                          Context->getTrue(), II);
10058     }
10059     return EraseInstFromFunction(*CS.getInstruction());
10060   }
10061
10062   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10063     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10064       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10065         return transformCallThroughTrampoline(CS);
10066
10067   const PointerType *PTy = cast<PointerType>(Callee->getType());
10068   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10069   if (FTy->isVarArg()) {
10070     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10071     // See if we can optimize any arguments passed through the varargs area of
10072     // the call.
10073     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10074            E = CS.arg_end(); I != E; ++I, ++ix) {
10075       CastInst *CI = dyn_cast<CastInst>(*I);
10076       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10077         *I = CI->getOperand(0);
10078         Changed = true;
10079       }
10080     }
10081   }
10082
10083   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10084     // Inline asm calls cannot throw - mark them 'nounwind'.
10085     CS.setDoesNotThrow();
10086     Changed = true;
10087   }
10088
10089   return Changed ? CS.getInstruction() : 0;
10090 }
10091
10092 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10093 // attempt to move the cast to the arguments of the call/invoke.
10094 //
10095 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10096   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10097   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10098   if (CE->getOpcode() != Instruction::BitCast || 
10099       !isa<Function>(CE->getOperand(0)))
10100     return false;
10101   Function *Callee = cast<Function>(CE->getOperand(0));
10102   Instruction *Caller = CS.getInstruction();
10103   const AttrListPtr &CallerPAL = CS.getAttributes();
10104
10105   // Okay, this is a cast from a function to a different type.  Unless doing so
10106   // would cause a type conversion of one of our arguments, change this call to
10107   // be a direct call with arguments casted to the appropriate types.
10108   //
10109   const FunctionType *FT = Callee->getFunctionType();
10110   const Type *OldRetTy = Caller->getType();
10111   const Type *NewRetTy = FT->getReturnType();
10112
10113   if (isa<StructType>(NewRetTy))
10114     return false; // TODO: Handle multiple return values.
10115
10116   // Check to see if we are changing the return type...
10117   if (OldRetTy != NewRetTy) {
10118     if (Callee->isDeclaration() &&
10119         // Conversion is ok if changing from one pointer type to another or from
10120         // a pointer to an integer of the same size.
10121         !((isa<PointerType>(OldRetTy) || !TD ||
10122            OldRetTy == TD->getIntPtrType()) &&
10123           (isa<PointerType>(NewRetTy) || !TD ||
10124            NewRetTy == TD->getIntPtrType())))
10125       return false;   // Cannot transform this return value.
10126
10127     if (!Caller->use_empty() &&
10128         // void -> non-void is handled specially
10129         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
10130       return false;   // Cannot transform this return value.
10131
10132     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10133       Attributes RAttrs = CallerPAL.getRetAttributes();
10134       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10135         return false;   // Attribute not compatible with transformed value.
10136     }
10137
10138     // If the callsite is an invoke instruction, and the return value is used by
10139     // a PHI node in a successor, we cannot change the return type of the call
10140     // because there is no place to put the cast instruction (without breaking
10141     // the critical edge).  Bail out in this case.
10142     if (!Caller->use_empty())
10143       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10144         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10145              UI != E; ++UI)
10146           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10147             if (PN->getParent() == II->getNormalDest() ||
10148                 PN->getParent() == II->getUnwindDest())
10149               return false;
10150   }
10151
10152   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10153   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10154
10155   CallSite::arg_iterator AI = CS.arg_begin();
10156   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10157     const Type *ParamTy = FT->getParamType(i);
10158     const Type *ActTy = (*AI)->getType();
10159
10160     if (!CastInst::isCastable(ActTy, ParamTy))
10161       return false;   // Cannot transform this parameter value.
10162
10163     if (CallerPAL.getParamAttributes(i + 1) 
10164         & Attribute::typeIncompatible(ParamTy))
10165       return false;   // Attribute not compatible with transformed value.
10166
10167     // Converting from one pointer type to another or between a pointer and an
10168     // integer of the same size is safe even if we do not have a body.
10169     bool isConvertible = ActTy == ParamTy ||
10170       (TD && ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10171               (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType())));
10172     if (Callee->isDeclaration() && !isConvertible) return false;
10173   }
10174
10175   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10176       Callee->isDeclaration())
10177     return false;   // Do not delete arguments unless we have a function body.
10178
10179   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10180       !CallerPAL.isEmpty())
10181     // In this case we have more arguments than the new function type, but we
10182     // won't be dropping them.  Check that these extra arguments have attributes
10183     // that are compatible with being a vararg call argument.
10184     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10185       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10186         break;
10187       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10188       if (PAttrs & Attribute::VarArgsIncompatible)
10189         return false;
10190     }
10191
10192   // Okay, we decided that this is a safe thing to do: go ahead and start
10193   // inserting cast instructions as necessary...
10194   std::vector<Value*> Args;
10195   Args.reserve(NumActualArgs);
10196   SmallVector<AttributeWithIndex, 8> attrVec;
10197   attrVec.reserve(NumCommonArgs);
10198
10199   // Get any return attributes.
10200   Attributes RAttrs = CallerPAL.getRetAttributes();
10201
10202   // If the return value is not being used, the type may not be compatible
10203   // with the existing attributes.  Wipe out any problematic attributes.
10204   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10205
10206   // Add the new return attributes.
10207   if (RAttrs)
10208     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10209
10210   AI = CS.arg_begin();
10211   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10212     const Type *ParamTy = FT->getParamType(i);
10213     if ((*AI)->getType() == ParamTy) {
10214       Args.push_back(*AI);
10215     } else {
10216       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10217           false, ParamTy, false);
10218       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10219       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10220     }
10221
10222     // Add any parameter attributes.
10223     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10224       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10225   }
10226
10227   // If the function takes more arguments than the call was taking, add them
10228   // now...
10229   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10230     Args.push_back(Context->getNullValue(FT->getParamType(i)));
10231
10232   // If we are removing arguments to the function, emit an obnoxious warning...
10233   if (FT->getNumParams() < NumActualArgs) {
10234     if (!FT->isVarArg()) {
10235       cerr << "WARNING: While resolving call to function '"
10236            << Callee->getName() << "' arguments were dropped!\n";
10237     } else {
10238       // Add all of the arguments in their promoted form to the arg list...
10239       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10240         const Type *PTy = getPromotedType((*AI)->getType());
10241         if (PTy != (*AI)->getType()) {
10242           // Must promote to pass through va_arg area!
10243           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
10244                                                                 PTy, false);
10245           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10246           InsertNewInstBefore(Cast, *Caller);
10247           Args.push_back(Cast);
10248         } else {
10249           Args.push_back(*AI);
10250         }
10251
10252         // Add any parameter attributes.
10253         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10254           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10255       }
10256     }
10257   }
10258
10259   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10260     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10261
10262   if (NewRetTy == Type::VoidTy)
10263     Caller->setName("");   // Void type should not have a name.
10264
10265   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
10266
10267   Instruction *NC;
10268   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10269     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10270                             Args.begin(), Args.end(),
10271                             Caller->getName(), Caller);
10272     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10273     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10274   } else {
10275     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10276                           Caller->getName(), Caller);
10277     CallInst *CI = cast<CallInst>(Caller);
10278     if (CI->isTailCall())
10279       cast<CallInst>(NC)->setTailCall();
10280     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10281     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10282   }
10283
10284   // Insert a cast of the return type as necessary.
10285   Value *NV = NC;
10286   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10287     if (NV->getType() != Type::VoidTy) {
10288       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10289                                                             OldRetTy, false);
10290       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10291
10292       // If this is an invoke instruction, we should insert it after the first
10293       // non-phi, instruction in the normal successor block.
10294       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10295         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10296         InsertNewInstBefore(NC, *I);
10297       } else {
10298         // Otherwise, it's a call, just insert cast right after the call instr
10299         InsertNewInstBefore(NC, *Caller);
10300       }
10301       AddUsersToWorkList(*Caller);
10302     } else {
10303       NV = Context->getUndef(Caller->getType());
10304     }
10305   }
10306
10307   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10308     Caller->replaceAllUsesWith(NV);
10309   Caller->eraseFromParent();
10310   RemoveFromWorkList(Caller);
10311   return true;
10312 }
10313
10314 // transformCallThroughTrampoline - Turn a call to a function created by the
10315 // init_trampoline intrinsic into a direct call to the underlying function.
10316 //
10317 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10318   Value *Callee = CS.getCalledValue();
10319   const PointerType *PTy = cast<PointerType>(Callee->getType());
10320   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10321   const AttrListPtr &Attrs = CS.getAttributes();
10322
10323   // If the call already has the 'nest' attribute somewhere then give up -
10324   // otherwise 'nest' would occur twice after splicing in the chain.
10325   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10326     return 0;
10327
10328   IntrinsicInst *Tramp =
10329     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10330
10331   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10332   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10333   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10334
10335   const AttrListPtr &NestAttrs = NestF->getAttributes();
10336   if (!NestAttrs.isEmpty()) {
10337     unsigned NestIdx = 1;
10338     const Type *NestTy = 0;
10339     Attributes NestAttr = Attribute::None;
10340
10341     // Look for a parameter marked with the 'nest' attribute.
10342     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10343          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10344       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10345         // Record the parameter type and any other attributes.
10346         NestTy = *I;
10347         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10348         break;
10349       }
10350
10351     if (NestTy) {
10352       Instruction *Caller = CS.getInstruction();
10353       std::vector<Value*> NewArgs;
10354       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10355
10356       SmallVector<AttributeWithIndex, 8> NewAttrs;
10357       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10358
10359       // Insert the nest argument into the call argument list, which may
10360       // mean appending it.  Likewise for attributes.
10361
10362       // Add any result attributes.
10363       if (Attributes Attr = Attrs.getRetAttributes())
10364         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10365
10366       {
10367         unsigned Idx = 1;
10368         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10369         do {
10370           if (Idx == NestIdx) {
10371             // Add the chain argument and attributes.
10372             Value *NestVal = Tramp->getOperand(3);
10373             if (NestVal->getType() != NestTy)
10374               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10375             NewArgs.push_back(NestVal);
10376             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10377           }
10378
10379           if (I == E)
10380             break;
10381
10382           // Add the original argument and attributes.
10383           NewArgs.push_back(*I);
10384           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10385             NewAttrs.push_back
10386               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10387
10388           ++Idx, ++I;
10389         } while (1);
10390       }
10391
10392       // Add any function attributes.
10393       if (Attributes Attr = Attrs.getFnAttributes())
10394         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10395
10396       // The trampoline may have been bitcast to a bogus type (FTy).
10397       // Handle this by synthesizing a new function type, equal to FTy
10398       // with the chain parameter inserted.
10399
10400       std::vector<const Type*> NewTypes;
10401       NewTypes.reserve(FTy->getNumParams()+1);
10402
10403       // Insert the chain's type into the list of parameter types, which may
10404       // mean appending it.
10405       {
10406         unsigned Idx = 1;
10407         FunctionType::param_iterator I = FTy->param_begin(),
10408           E = FTy->param_end();
10409
10410         do {
10411           if (Idx == NestIdx)
10412             // Add the chain's type.
10413             NewTypes.push_back(NestTy);
10414
10415           if (I == E)
10416             break;
10417
10418           // Add the original type.
10419           NewTypes.push_back(*I);
10420
10421           ++Idx, ++I;
10422         } while (1);
10423       }
10424
10425       // Replace the trampoline call with a direct call.  Let the generic
10426       // code sort out any function type mismatches.
10427       FunctionType *NewFTy =
10428                        Context->getFunctionType(FTy->getReturnType(), NewTypes, 
10429                                                 FTy->isVarArg());
10430       Constant *NewCallee =
10431         NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10432         NestF : Context->getConstantExprBitCast(NestF, 
10433                                          Context->getPointerTypeUnqual(NewFTy));
10434       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
10435
10436       Instruction *NewCaller;
10437       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10438         NewCaller = InvokeInst::Create(NewCallee,
10439                                        II->getNormalDest(), II->getUnwindDest(),
10440                                        NewArgs.begin(), NewArgs.end(),
10441                                        Caller->getName(), Caller);
10442         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10443         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10444       } else {
10445         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10446                                      Caller->getName(), Caller);
10447         if (cast<CallInst>(Caller)->isTailCall())
10448           cast<CallInst>(NewCaller)->setTailCall();
10449         cast<CallInst>(NewCaller)->
10450           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10451         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10452       }
10453       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10454         Caller->replaceAllUsesWith(NewCaller);
10455       Caller->eraseFromParent();
10456       RemoveFromWorkList(Caller);
10457       return 0;
10458     }
10459   }
10460
10461   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10462   // parameter, there is no need to adjust the argument list.  Let the generic
10463   // code sort out any function type mismatches.
10464   Constant *NewCallee =
10465     NestF->getType() == PTy ? NestF : 
10466                               Context->getConstantExprBitCast(NestF, PTy);
10467   CS.setCalledFunction(NewCallee);
10468   return CS.getInstruction();
10469 }
10470
10471 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10472 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10473 /// and a single binop.
10474 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10475   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10476   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10477   unsigned Opc = FirstInst->getOpcode();
10478   Value *LHSVal = FirstInst->getOperand(0);
10479   Value *RHSVal = FirstInst->getOperand(1);
10480     
10481   const Type *LHSType = LHSVal->getType();
10482   const Type *RHSType = RHSVal->getType();
10483   
10484   // Scan to see if all operands are the same opcode, all have one use, and all
10485   // kill their operands (i.e. the operands have one use).
10486   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10487     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10488     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10489         // Verify type of the LHS matches so we don't fold cmp's of different
10490         // types or GEP's with different index types.
10491         I->getOperand(0)->getType() != LHSType ||
10492         I->getOperand(1)->getType() != RHSType)
10493       return 0;
10494
10495     // If they are CmpInst instructions, check their predicates
10496     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10497       if (cast<CmpInst>(I)->getPredicate() !=
10498           cast<CmpInst>(FirstInst)->getPredicate())
10499         return 0;
10500     
10501     // Keep track of which operand needs a phi node.
10502     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10503     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10504   }
10505   
10506   // Otherwise, this is safe to transform!
10507   
10508   Value *InLHS = FirstInst->getOperand(0);
10509   Value *InRHS = FirstInst->getOperand(1);
10510   PHINode *NewLHS = 0, *NewRHS = 0;
10511   if (LHSVal == 0) {
10512     NewLHS = PHINode::Create(LHSType,
10513                              FirstInst->getOperand(0)->getName() + ".pn");
10514     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10515     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10516     InsertNewInstBefore(NewLHS, PN);
10517     LHSVal = NewLHS;
10518   }
10519   
10520   if (RHSVal == 0) {
10521     NewRHS = PHINode::Create(RHSType,
10522                              FirstInst->getOperand(1)->getName() + ".pn");
10523     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10524     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10525     InsertNewInstBefore(NewRHS, PN);
10526     RHSVal = NewRHS;
10527   }
10528   
10529   // Add all operands to the new PHIs.
10530   if (NewLHS || NewRHS) {
10531     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10532       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10533       if (NewLHS) {
10534         Value *NewInLHS = InInst->getOperand(0);
10535         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10536       }
10537       if (NewRHS) {
10538         Value *NewInRHS = InInst->getOperand(1);
10539         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10540       }
10541     }
10542   }
10543     
10544   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10545     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10546   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10547   return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10548                          LHSVal, RHSVal);
10549 }
10550
10551 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10552   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10553   
10554   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10555                                         FirstInst->op_end());
10556   // This is true if all GEP bases are allocas and if all indices into them are
10557   // constants.
10558   bool AllBasePointersAreAllocas = true;
10559   
10560   // Scan to see if all operands are the same opcode, all have one use, and all
10561   // kill their operands (i.e. the operands have one use).
10562   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10563     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10564     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10565       GEP->getNumOperands() != FirstInst->getNumOperands())
10566       return 0;
10567
10568     // Keep track of whether or not all GEPs are of alloca pointers.
10569     if (AllBasePointersAreAllocas &&
10570         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10571          !GEP->hasAllConstantIndices()))
10572       AllBasePointersAreAllocas = false;
10573     
10574     // Compare the operand lists.
10575     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10576       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10577         continue;
10578       
10579       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10580       // if one of the PHIs has a constant for the index.  The index may be
10581       // substantially cheaper to compute for the constants, so making it a
10582       // variable index could pessimize the path.  This also handles the case
10583       // for struct indices, which must always be constant.
10584       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10585           isa<ConstantInt>(GEP->getOperand(op)))
10586         return 0;
10587       
10588       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10589         return 0;
10590       FixedOperands[op] = 0;  // Needs a PHI.
10591     }
10592   }
10593   
10594   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10595   // bother doing this transformation.  At best, this will just save a bit of
10596   // offset calculation, but all the predecessors will have to materialize the
10597   // stack address into a register anyway.  We'd actually rather *clone* the
10598   // load up into the predecessors so that we have a load of a gep of an alloca,
10599   // which can usually all be folded into the load.
10600   if (AllBasePointersAreAllocas)
10601     return 0;
10602   
10603   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10604   // that is variable.
10605   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10606   
10607   bool HasAnyPHIs = false;
10608   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10609     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10610     Value *FirstOp = FirstInst->getOperand(i);
10611     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10612                                      FirstOp->getName()+".pn");
10613     InsertNewInstBefore(NewPN, PN);
10614     
10615     NewPN->reserveOperandSpace(e);
10616     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10617     OperandPhis[i] = NewPN;
10618     FixedOperands[i] = NewPN;
10619     HasAnyPHIs = true;
10620   }
10621
10622   
10623   // Add all operands to the new PHIs.
10624   if (HasAnyPHIs) {
10625     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10626       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10627       BasicBlock *InBB = PN.getIncomingBlock(i);
10628       
10629       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10630         if (PHINode *OpPhi = OperandPhis[op])
10631           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10632     }
10633   }
10634   
10635   Value *Base = FixedOperands[0];
10636   return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10637                                    FixedOperands.end());
10638 }
10639
10640
10641 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10642 /// sink the load out of the block that defines it.  This means that it must be
10643 /// obvious the value of the load is not changed from the point of the load to
10644 /// the end of the block it is in.
10645 ///
10646 /// Finally, it is safe, but not profitable, to sink a load targetting a
10647 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10648 /// to a register.
10649 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10650   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10651   
10652   for (++BBI; BBI != E; ++BBI)
10653     if (BBI->mayWriteToMemory())
10654       return false;
10655   
10656   // Check for non-address taken alloca.  If not address-taken already, it isn't
10657   // profitable to do this xform.
10658   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10659     bool isAddressTaken = false;
10660     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10661          UI != E; ++UI) {
10662       if (isa<LoadInst>(UI)) continue;
10663       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10664         // If storing TO the alloca, then the address isn't taken.
10665         if (SI->getOperand(1) == AI) continue;
10666       }
10667       isAddressTaken = true;
10668       break;
10669     }
10670     
10671     if (!isAddressTaken && AI->isStaticAlloca())
10672       return false;
10673   }
10674   
10675   // If this load is a load from a GEP with a constant offset from an alloca,
10676   // then we don't want to sink it.  In its present form, it will be
10677   // load [constant stack offset].  Sinking it will cause us to have to
10678   // materialize the stack addresses in each predecessor in a register only to
10679   // do a shared load from register in the successor.
10680   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10681     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10682       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10683         return false;
10684   
10685   return true;
10686 }
10687
10688
10689 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10690 // operator and they all are only used by the PHI, PHI together their
10691 // inputs, and do the operation once, to the result of the PHI.
10692 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10693   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10694
10695   // Scan the instruction, looking for input operations that can be folded away.
10696   // If all input operands to the phi are the same instruction (e.g. a cast from
10697   // the same type or "+42") we can pull the operation through the PHI, reducing
10698   // code size and simplifying code.
10699   Constant *ConstantOp = 0;
10700   const Type *CastSrcTy = 0;
10701   bool isVolatile = false;
10702   if (isa<CastInst>(FirstInst)) {
10703     CastSrcTy = FirstInst->getOperand(0)->getType();
10704   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10705     // Can fold binop, compare or shift here if the RHS is a constant, 
10706     // otherwise call FoldPHIArgBinOpIntoPHI.
10707     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10708     if (ConstantOp == 0)
10709       return FoldPHIArgBinOpIntoPHI(PN);
10710   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10711     isVolatile = LI->isVolatile();
10712     // We can't sink the load if the loaded value could be modified between the
10713     // load and the PHI.
10714     if (LI->getParent() != PN.getIncomingBlock(0) ||
10715         !isSafeAndProfitableToSinkLoad(LI))
10716       return 0;
10717     
10718     // If the PHI is of volatile loads and the load block has multiple
10719     // successors, sinking it would remove a load of the volatile value from
10720     // the path through the other successor.
10721     if (isVolatile &&
10722         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10723       return 0;
10724     
10725   } else if (isa<GetElementPtrInst>(FirstInst)) {
10726     return FoldPHIArgGEPIntoPHI(PN);
10727   } else {
10728     return 0;  // Cannot fold this operation.
10729   }
10730
10731   // Check to see if all arguments are the same operation.
10732   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10733     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10734     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10735     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10736       return 0;
10737     if (CastSrcTy) {
10738       if (I->getOperand(0)->getType() != CastSrcTy)
10739         return 0;  // Cast operation must match.
10740     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10741       // We can't sink the load if the loaded value could be modified between 
10742       // the load and the PHI.
10743       if (LI->isVolatile() != isVolatile ||
10744           LI->getParent() != PN.getIncomingBlock(i) ||
10745           !isSafeAndProfitableToSinkLoad(LI))
10746         return 0;
10747       
10748       // If the PHI is of volatile loads and the load block has multiple
10749       // successors, sinking it would remove a load of the volatile value from
10750       // the path through the other successor.
10751       if (isVolatile &&
10752           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10753         return 0;
10754       
10755     } else if (I->getOperand(1) != ConstantOp) {
10756       return 0;
10757     }
10758   }
10759
10760   // Okay, they are all the same operation.  Create a new PHI node of the
10761   // correct type, and PHI together all of the LHS's of the instructions.
10762   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10763                                    PN.getName()+".in");
10764   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10765
10766   Value *InVal = FirstInst->getOperand(0);
10767   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10768
10769   // Add all operands to the new PHI.
10770   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10771     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10772     if (NewInVal != InVal)
10773       InVal = 0;
10774     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10775   }
10776
10777   Value *PhiVal;
10778   if (InVal) {
10779     // The new PHI unions all of the same values together.  This is really
10780     // common, so we handle it intelligently here for compile-time speed.
10781     PhiVal = InVal;
10782     delete NewPN;
10783   } else {
10784     InsertNewInstBefore(NewPN, PN);
10785     PhiVal = NewPN;
10786   }
10787
10788   // Insert and return the new operation.
10789   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10790     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10791   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10792     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10793   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10794     return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10795                            PhiVal, ConstantOp);
10796   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10797   
10798   // If this was a volatile load that we are merging, make sure to loop through
10799   // and mark all the input loads as non-volatile.  If we don't do this, we will
10800   // insert a new volatile load and the old ones will not be deletable.
10801   if (isVolatile)
10802     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10803       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10804   
10805   return new LoadInst(PhiVal, "", isVolatile);
10806 }
10807
10808 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10809 /// that is dead.
10810 static bool DeadPHICycle(PHINode *PN,
10811                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10812   if (PN->use_empty()) return true;
10813   if (!PN->hasOneUse()) return false;
10814
10815   // Remember this node, and if we find the cycle, return.
10816   if (!PotentiallyDeadPHIs.insert(PN))
10817     return true;
10818   
10819   // Don't scan crazily complex things.
10820   if (PotentiallyDeadPHIs.size() == 16)
10821     return false;
10822
10823   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10824     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10825
10826   return false;
10827 }
10828
10829 /// PHIsEqualValue - Return true if this phi node is always equal to
10830 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10831 ///   z = some value; x = phi (y, z); y = phi (x, z)
10832 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10833                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10834   // See if we already saw this PHI node.
10835   if (!ValueEqualPHIs.insert(PN))
10836     return true;
10837   
10838   // Don't scan crazily complex things.
10839   if (ValueEqualPHIs.size() == 16)
10840     return false;
10841  
10842   // Scan the operands to see if they are either phi nodes or are equal to
10843   // the value.
10844   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10845     Value *Op = PN->getIncomingValue(i);
10846     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10847       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10848         return false;
10849     } else if (Op != NonPhiInVal)
10850       return false;
10851   }
10852   
10853   return true;
10854 }
10855
10856
10857 // PHINode simplification
10858 //
10859 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10860   // If LCSSA is around, don't mess with Phi nodes
10861   if (MustPreserveLCSSA) return 0;
10862   
10863   if (Value *V = PN.hasConstantValue())
10864     return ReplaceInstUsesWith(PN, V);
10865
10866   // If all PHI operands are the same operation, pull them through the PHI,
10867   // reducing code size.
10868   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10869       isa<Instruction>(PN.getIncomingValue(1)) &&
10870       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10871       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10872       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10873       // than themselves more than once.
10874       PN.getIncomingValue(0)->hasOneUse())
10875     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10876       return Result;
10877
10878   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10879   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10880   // PHI)... break the cycle.
10881   if (PN.hasOneUse()) {
10882     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10883     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10884       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10885       PotentiallyDeadPHIs.insert(&PN);
10886       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10887         return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10888     }
10889    
10890     // If this phi has a single use, and if that use just computes a value for
10891     // the next iteration of a loop, delete the phi.  This occurs with unused
10892     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10893     // common case here is good because the only other things that catch this
10894     // are induction variable analysis (sometimes) and ADCE, which is only run
10895     // late.
10896     if (PHIUser->hasOneUse() &&
10897         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10898         PHIUser->use_back() == &PN) {
10899       return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10900     }
10901   }
10902
10903   // We sometimes end up with phi cycles that non-obviously end up being the
10904   // same value, for example:
10905   //   z = some value; x = phi (y, z); y = phi (x, z)
10906   // where the phi nodes don't necessarily need to be in the same block.  Do a
10907   // quick check to see if the PHI node only contains a single non-phi value, if
10908   // so, scan to see if the phi cycle is actually equal to that value.
10909   {
10910     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10911     // Scan for the first non-phi operand.
10912     while (InValNo != NumOperandVals && 
10913            isa<PHINode>(PN.getIncomingValue(InValNo)))
10914       ++InValNo;
10915
10916     if (InValNo != NumOperandVals) {
10917       Value *NonPhiInVal = PN.getOperand(InValNo);
10918       
10919       // Scan the rest of the operands to see if there are any conflicts, if so
10920       // there is no need to recursively scan other phis.
10921       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10922         Value *OpVal = PN.getIncomingValue(InValNo);
10923         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10924           break;
10925       }
10926       
10927       // If we scanned over all operands, then we have one unique value plus
10928       // phi values.  Scan PHI nodes to see if they all merge in each other or
10929       // the value.
10930       if (InValNo == NumOperandVals) {
10931         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10932         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10933           return ReplaceInstUsesWith(PN, NonPhiInVal);
10934       }
10935     }
10936   }
10937   return 0;
10938 }
10939
10940 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10941                                    Instruction *InsertPoint,
10942                                    InstCombiner *IC) {
10943   unsigned PtrSize = DTy->getScalarSizeInBits();
10944   unsigned VTySize = V->getType()->getScalarSizeInBits();
10945   // We must cast correctly to the pointer type. Ensure that we
10946   // sign extend the integer value if it is smaller as this is
10947   // used for address computation.
10948   Instruction::CastOps opcode = 
10949      (VTySize < PtrSize ? Instruction::SExt :
10950       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10951   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10952 }
10953
10954
10955 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10956   Value *PtrOp = GEP.getOperand(0);
10957   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10958   // If so, eliminate the noop.
10959   if (GEP.getNumOperands() == 1)
10960     return ReplaceInstUsesWith(GEP, PtrOp);
10961
10962   if (isa<UndefValue>(GEP.getOperand(0)))
10963     return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
10964
10965   bool HasZeroPointerIndex = false;
10966   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10967     HasZeroPointerIndex = C->isNullValue();
10968
10969   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10970     return ReplaceInstUsesWith(GEP, PtrOp);
10971
10972   // Eliminate unneeded casts for indices.
10973   bool MadeChange = false;
10974   
10975   gep_type_iterator GTI = gep_type_begin(GEP);
10976   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10977        i != e; ++i, ++GTI) {
10978     if (TD && isa<SequentialType>(*GTI)) {
10979       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
10980         if (CI->getOpcode() == Instruction::ZExt ||
10981             CI->getOpcode() == Instruction::SExt) {
10982           const Type *SrcTy = CI->getOperand(0)->getType();
10983           // We can eliminate a cast from i32 to i64 iff the target 
10984           // is a 32-bit pointer target.
10985           if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
10986             MadeChange = true;
10987             *i = CI->getOperand(0);
10988           }
10989         }
10990       }
10991       // If we are using a wider index than needed for this platform, shrink it
10992       // to what we need.  If narrower, sign-extend it to what we need.
10993       // If the incoming value needs a cast instruction,
10994       // insert it.  This explicit cast can make subsequent optimizations more
10995       // obvious.
10996       Value *Op = *i;
10997       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
10998         if (Constant *C = dyn_cast<Constant>(Op)) {
10999           *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
11000           MadeChange = true;
11001         } else {
11002           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11003                                 GEP);
11004           *i = Op;
11005           MadeChange = true;
11006         }
11007       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
11008         if (Constant *C = dyn_cast<Constant>(Op)) {
11009           *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
11010           MadeChange = true;
11011         } else {
11012           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11013                                 GEP);
11014           *i = Op;
11015           MadeChange = true;
11016         }
11017       }
11018     }
11019   }
11020   if (MadeChange) return &GEP;
11021
11022   // Combine Indices - If the source pointer to this getelementptr instruction
11023   // is a getelementptr instruction, combine the indices of the two
11024   // getelementptr instructions into a single instruction.
11025   //
11026   SmallVector<Value*, 8> SrcGEPOperands;
11027   if (User *Src = dyn_castGetElementPtr(PtrOp))
11028     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
11029
11030   if (!SrcGEPOperands.empty()) {
11031     // Note that if our source is a gep chain itself that we wait for that
11032     // chain to be resolved before we perform this transformation.  This
11033     // avoids us creating a TON of code in some cases.
11034     //
11035     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11036         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11037       return 0;   // Wait until our source is folded to completion.
11038
11039     SmallVector<Value*, 8> Indices;
11040
11041     // Find out whether the last index in the source GEP is a sequential idx.
11042     bool EndsWithSequential = false;
11043     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11044            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11045       EndsWithSequential = !isa<StructType>(*I);
11046
11047     // Can we combine the two pointer arithmetics offsets?
11048     if (EndsWithSequential) {
11049       // Replace: gep (gep %P, long B), long A, ...
11050       // With:    T = long A+B; gep %P, T, ...
11051       //
11052       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
11053       if (SO1 == Context->getNullValue(SO1->getType())) {
11054         Sum = GO1;
11055       } else if (GO1 == Context->getNullValue(GO1->getType())) {
11056         Sum = SO1;
11057       } else {
11058         // If they aren't the same type, convert both to an integer of the
11059         // target's pointer size.
11060         if (SO1->getType() != GO1->getType()) {
11061           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
11062             SO1 =
11063                 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
11064           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
11065             GO1 =
11066                 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
11067           } else if (TD) {
11068             unsigned PS = TD->getPointerSizeInBits();
11069             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
11070               // Convert GO1 to SO1's type.
11071               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11072
11073             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
11074               // Convert SO1 to GO1's type.
11075               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11076             } else {
11077               const Type *PT = TD->getIntPtrType();
11078               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11079               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11080             }
11081           }
11082         }
11083         if (isa<Constant>(SO1) && isa<Constant>(GO1))
11084           Sum = Context->getConstantExprAdd(cast<Constant>(SO1), 
11085                                             cast<Constant>(GO1));
11086         else {
11087           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11088           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11089         }
11090       }
11091
11092       // Recycle the GEP we already have if possible.
11093       if (SrcGEPOperands.size() == 2) {
11094         GEP.setOperand(0, SrcGEPOperands[0]);
11095         GEP.setOperand(1, Sum);
11096         return &GEP;
11097       } else {
11098         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11099                        SrcGEPOperands.end()-1);
11100         Indices.push_back(Sum);
11101         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11102       }
11103     } else if (isa<Constant>(*GEP.idx_begin()) &&
11104                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11105                SrcGEPOperands.size() != 1) {
11106       // Otherwise we can do the fold if the first index of the GEP is a zero
11107       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11108                      SrcGEPOperands.end());
11109       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11110     }
11111
11112     if (!Indices.empty())
11113       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11114                                        Indices.end(), GEP.getName());
11115
11116   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11117     // GEP of global variable.  If all of the indices for this GEP are
11118     // constants, we can promote this to a constexpr instead of an instruction.
11119
11120     // Scan for nonconstants...
11121     SmallVector<Constant*, 8> Indices;
11122     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11123     for (; I != E && isa<Constant>(*I); ++I)
11124       Indices.push_back(cast<Constant>(*I));
11125
11126     if (I == E) {  // If they are all constants...
11127       Constant *CE = Context->getConstantExprGetElementPtr(GV,
11128                                                     &Indices[0],Indices.size());
11129
11130       // Replace all uses of the GEP with the new constexpr...
11131       return ReplaceInstUsesWith(GEP, CE);
11132     }
11133   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
11134     if (!isa<PointerType>(X->getType())) {
11135       // Not interesting.  Source pointer must be a cast from pointer.
11136     } else if (HasZeroPointerIndex) {
11137       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11138       // into     : GEP [10 x i8]* X, i32 0, ...
11139       //
11140       // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11141       //           into     : GEP i8* X, ...
11142       // 
11143       // This occurs when the program declares an array extern like "int X[];"
11144       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11145       const PointerType *XTy = cast<PointerType>(X->getType());
11146       if (const ArrayType *CATy =
11147           dyn_cast<ArrayType>(CPTy->getElementType())) {
11148         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11149         if (CATy->getElementType() == XTy->getElementType()) {
11150           // -> GEP i8* X, ...
11151           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11152           return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11153                                            GEP.getName());
11154         } else if (const ArrayType *XATy =
11155                  dyn_cast<ArrayType>(XTy->getElementType())) {
11156           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11157           if (CATy->getElementType() == XATy->getElementType()) {
11158             // -> GEP [10 x i8]* X, i32 0, ...
11159             // At this point, we know that the cast source type is a pointer
11160             // to an array of the same type as the destination pointer
11161             // array.  Because the array type is never stepped over (there
11162             // is a leading zero) we can fold the cast into this GEP.
11163             GEP.setOperand(0, X);
11164             return &GEP;
11165           }
11166         }
11167       }
11168     } else if (GEP.getNumOperands() == 2) {
11169       // Transform things like:
11170       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11171       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11172       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11173       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11174       if (TD && isa<ArrayType>(SrcElTy) &&
11175           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11176           TD->getTypeAllocSize(ResElTy)) {
11177         Value *Idx[2];
11178         Idx[0] = Context->getNullValue(Type::Int32Ty);
11179         Idx[1] = GEP.getOperand(1);
11180         Value *V = InsertNewInstBefore(
11181                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
11182         // V and GEP are both pointer types --> BitCast
11183         return new BitCastInst(V, GEP.getType());
11184       }
11185       
11186       // Transform things like:
11187       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11188       //   (where tmp = 8*tmp2) into:
11189       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11190       
11191       if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
11192         uint64_t ArrayEltSize =
11193             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11194         
11195         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11196         // allow either a mul, shift, or constant here.
11197         Value *NewIdx = 0;
11198         ConstantInt *Scale = 0;
11199         if (ArrayEltSize == 1) {
11200           NewIdx = GEP.getOperand(1);
11201           Scale = 
11202                Context->getConstantInt(cast<IntegerType>(NewIdx->getType()), 1);
11203         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11204           NewIdx = Context->getConstantInt(CI->getType(), 1);
11205           Scale = CI;
11206         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11207           if (Inst->getOpcode() == Instruction::Shl &&
11208               isa<ConstantInt>(Inst->getOperand(1))) {
11209             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11210             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11211             Scale = Context->getConstantInt(cast<IntegerType>(Inst->getType()),
11212                                      1ULL << ShAmtVal);
11213             NewIdx = Inst->getOperand(0);
11214           } else if (Inst->getOpcode() == Instruction::Mul &&
11215                      isa<ConstantInt>(Inst->getOperand(1))) {
11216             Scale = cast<ConstantInt>(Inst->getOperand(1));
11217             NewIdx = Inst->getOperand(0);
11218           }
11219         }
11220         
11221         // If the index will be to exactly the right offset with the scale taken
11222         // out, perform the transformation. Note, we don't know whether Scale is
11223         // signed or not. We'll use unsigned version of division/modulo
11224         // operation after making sure Scale doesn't have the sign bit set.
11225         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11226             Scale->getZExtValue() % ArrayEltSize == 0) {
11227           Scale = Context->getConstantInt(Scale->getType(),
11228                                    Scale->getZExtValue() / ArrayEltSize);
11229           if (Scale->getZExtValue() != 1) {
11230             Constant *C =
11231                    Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
11232                                                        false /*ZExt*/);
11233             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11234             NewIdx = InsertNewInstBefore(Sc, GEP);
11235           }
11236
11237           // Insert the new GEP instruction.
11238           Value *Idx[2];
11239           Idx[0] = Context->getNullValue(Type::Int32Ty);
11240           Idx[1] = NewIdx;
11241           Instruction *NewGEP =
11242             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11243           NewGEP = InsertNewInstBefore(NewGEP, GEP);
11244           // The NewGEP must be pointer typed, so must the old one -> BitCast
11245           return new BitCastInst(NewGEP, GEP.getType());
11246         }
11247       }
11248     }
11249   }
11250   
11251   /// See if we can simplify:
11252   ///   X = bitcast A to B*
11253   ///   Y = gep X, <...constant indices...>
11254   /// into a gep of the original struct.  This is important for SROA and alias
11255   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11256   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11257     if (TD &&
11258         !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11259       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11260       // a constant back from EmitGEPOffset.
11261       ConstantInt *OffsetV =
11262                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11263       int64_t Offset = OffsetV->getSExtValue();
11264       
11265       // If this GEP instruction doesn't move the pointer, just replace the GEP
11266       // with a bitcast of the real input to the dest type.
11267       if (Offset == 0) {
11268         // If the bitcast is of an allocation, and the allocation will be
11269         // converted to match the type of the cast, don't touch this.
11270         if (isa<AllocationInst>(BCI->getOperand(0))) {
11271           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11272           if (Instruction *I = visitBitCast(*BCI)) {
11273             if (I != BCI) {
11274               I->takeName(BCI);
11275               BCI->getParent()->getInstList().insert(BCI, I);
11276               ReplaceInstUsesWith(*BCI, I);
11277             }
11278             return &GEP;
11279           }
11280         }
11281         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11282       }
11283       
11284       // Otherwise, if the offset is non-zero, we need to find out if there is a
11285       // field at Offset in 'A's type.  If so, we can pull the cast through the
11286       // GEP.
11287       SmallVector<Value*, 8> NewIndices;
11288       const Type *InTy =
11289         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11290       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11291         Instruction *NGEP =
11292            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11293                                      NewIndices.end());
11294         if (NGEP->getType() == GEP.getType()) return NGEP;
11295         InsertNewInstBefore(NGEP, GEP);
11296         NGEP->takeName(&GEP);
11297         return new BitCastInst(NGEP, GEP.getType());
11298       }
11299     }
11300   }    
11301     
11302   return 0;
11303 }
11304
11305 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11306   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11307   if (AI.isArrayAllocation()) {  // Check C != 1
11308     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11309       const Type *NewTy = 
11310         Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
11311       AllocationInst *New = 0;
11312
11313       // Create and insert the replacement instruction...
11314       if (isa<MallocInst>(AI))
11315         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11316       else {
11317         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11318         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11319       }
11320
11321       InsertNewInstBefore(New, AI);
11322
11323       // Scan to the end of the allocation instructions, to skip over a block of
11324       // allocas if possible...also skip interleaved debug info
11325       //
11326       BasicBlock::iterator It = New;
11327       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11328
11329       // Now that I is pointing to the first non-allocation-inst in the block,
11330       // insert our getelementptr instruction...
11331       //
11332       Value *NullIdx = Context->getNullValue(Type::Int32Ty);
11333       Value *Idx[2];
11334       Idx[0] = NullIdx;
11335       Idx[1] = NullIdx;
11336       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11337                                            New->getName()+".sub", It);
11338
11339       // Now make everything use the getelementptr instead of the original
11340       // allocation.
11341       return ReplaceInstUsesWith(AI, V);
11342     } else if (isa<UndefValue>(AI.getArraySize())) {
11343       return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11344     }
11345   }
11346
11347   if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11348     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11349     // Note that we only do this for alloca's, because malloc should allocate
11350     // and return a unique pointer, even for a zero byte allocation.
11351     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11352       return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11353
11354     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11355     if (AI.getAlignment() == 0)
11356       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11357   }
11358
11359   return 0;
11360 }
11361
11362 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11363   Value *Op = FI.getOperand(0);
11364
11365   // free undef -> unreachable.
11366   if (isa<UndefValue>(Op)) {
11367     // Insert a new store to null because we cannot modify the CFG here.
11368     new StoreInst(Context->getTrue(),
11369            Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
11370     return EraseInstFromFunction(FI);
11371   }
11372   
11373   // If we have 'free null' delete the instruction.  This can happen in stl code
11374   // when lots of inlining happens.
11375   if (isa<ConstantPointerNull>(Op))
11376     return EraseInstFromFunction(FI);
11377   
11378   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11379   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11380     FI.setOperand(0, CI->getOperand(0));
11381     return &FI;
11382   }
11383   
11384   // Change free (gep X, 0,0,0,0) into free(X)
11385   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11386     if (GEPI->hasAllZeroIndices()) {
11387       AddToWorkList(GEPI);
11388       FI.setOperand(0, GEPI->getOperand(0));
11389       return &FI;
11390     }
11391   }
11392   
11393   // Change free(malloc) into nothing, if the malloc has a single use.
11394   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11395     if (MI->hasOneUse()) {
11396       EraseInstFromFunction(FI);
11397       return EraseInstFromFunction(*MI);
11398     }
11399
11400   return 0;
11401 }
11402
11403
11404 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11405 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11406                                         const TargetData *TD) {
11407   User *CI = cast<User>(LI.getOperand(0));
11408   Value *CastOp = CI->getOperand(0);
11409   LLVMContext *Context = IC.getContext();
11410
11411   if (TD) {
11412     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11413       // Instead of loading constant c string, use corresponding integer value
11414       // directly if string length is small enough.
11415       std::string Str;
11416       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11417         unsigned len = Str.length();
11418         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11419         unsigned numBits = Ty->getPrimitiveSizeInBits();
11420         // Replace LI with immediate integer store.
11421         if ((numBits >> 3) == len + 1) {
11422           APInt StrVal(numBits, 0);
11423           APInt SingleChar(numBits, 0);
11424           if (TD->isLittleEndian()) {
11425             for (signed i = len-1; i >= 0; i--) {
11426               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11427               StrVal = (StrVal << 8) | SingleChar;
11428             }
11429           } else {
11430             for (unsigned i = 0; i < len; i++) {
11431               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11432               StrVal = (StrVal << 8) | SingleChar;
11433             }
11434             // Append NULL at the end.
11435             SingleChar = 0;
11436             StrVal = (StrVal << 8) | SingleChar;
11437           }
11438           Value *NL = Context->getConstantInt(StrVal);
11439           return IC.ReplaceInstUsesWith(LI, NL);
11440         }
11441       }
11442     }
11443   }
11444
11445   const PointerType *DestTy = cast<PointerType>(CI->getType());
11446   const Type *DestPTy = DestTy->getElementType();
11447   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11448
11449     // If the address spaces don't match, don't eliminate the cast.
11450     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11451       return 0;
11452
11453     const Type *SrcPTy = SrcTy->getElementType();
11454
11455     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11456          isa<VectorType>(DestPTy)) {
11457       // If the source is an array, the code below will not succeed.  Check to
11458       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11459       // constants.
11460       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11461         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11462           if (ASrcTy->getNumElements() != 0) {
11463             Value *Idxs[2];
11464             Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11465             CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
11466             SrcTy = cast<PointerType>(CastOp->getType());
11467             SrcPTy = SrcTy->getElementType();
11468           }
11469
11470       if (IC.getTargetData() &&
11471           (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11472             isa<VectorType>(SrcPTy)) &&
11473           // Do not allow turning this into a load of an integer, which is then
11474           // casted to a pointer, this pessimizes pointer analysis a lot.
11475           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11476           IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11477                IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11478
11479         // Okay, we are casting from one integer or pointer type to another of
11480         // the same size.  Instead of casting the pointer before the load, cast
11481         // the result of the loaded value.
11482         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11483                                                              CI->getName(),
11484                                                          LI.isVolatile()),LI);
11485         // Now cast the result of the load.
11486         return new BitCastInst(NewLoad, LI.getType());
11487       }
11488     }
11489   }
11490   return 0;
11491 }
11492
11493 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11494   Value *Op = LI.getOperand(0);
11495
11496   // Attempt to improve the alignment.
11497   if (TD) {
11498     unsigned KnownAlign =
11499       GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11500     if (KnownAlign >
11501         (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11502                                   LI.getAlignment()))
11503       LI.setAlignment(KnownAlign);
11504   }
11505
11506   // load (cast X) --> cast (load X) iff safe
11507   if (isa<CastInst>(Op))
11508     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11509       return Res;
11510
11511   // None of the following transforms are legal for volatile loads.
11512   if (LI.isVolatile()) return 0;
11513   
11514   // Do really simple store-to-load forwarding and load CSE, to catch cases
11515   // where there are several consequtive memory accesses to the same location,
11516   // separated by a few arithmetic operations.
11517   BasicBlock::iterator BBI = &LI;
11518   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11519     return ReplaceInstUsesWith(LI, AvailableVal);
11520
11521   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11522     const Value *GEPI0 = GEPI->getOperand(0);
11523     // TODO: Consider a target hook for valid address spaces for this xform.
11524     if (isa<ConstantPointerNull>(GEPI0) &&
11525         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11526       // Insert a new store to null instruction before the load to indicate
11527       // that this code is not reachable.  We do this instead of inserting
11528       // an unreachable instruction directly because we cannot modify the
11529       // CFG.
11530       new StoreInst(Context->getUndef(LI.getType()),
11531                     Context->getNullValue(Op->getType()), &LI);
11532       return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11533     }
11534   } 
11535
11536   if (Constant *C = dyn_cast<Constant>(Op)) {
11537     // load null/undef -> undef
11538     // TODO: Consider a target hook for valid address spaces for this xform.
11539     if (isa<UndefValue>(C) || (C->isNullValue() && 
11540         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11541       // Insert a new store to null instruction before the load to indicate that
11542       // this code is not reachable.  We do this instead of inserting an
11543       // unreachable instruction directly because we cannot modify the CFG.
11544       new StoreInst(Context->getUndef(LI.getType()),
11545                     Context->getNullValue(Op->getType()), &LI);
11546       return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11547     }
11548
11549     // Instcombine load (constant global) into the value loaded.
11550     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11551       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11552         return ReplaceInstUsesWith(LI, GV->getInitializer());
11553
11554     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11555     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11556       if (CE->getOpcode() == Instruction::GetElementPtr) {
11557         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11558           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11559             if (Constant *V = 
11560                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE, 
11561                                                       *Context))
11562               return ReplaceInstUsesWith(LI, V);
11563         if (CE->getOperand(0)->isNullValue()) {
11564           // Insert a new store to null instruction before the load to indicate
11565           // that this code is not reachable.  We do this instead of inserting
11566           // an unreachable instruction directly because we cannot modify the
11567           // CFG.
11568           new StoreInst(Context->getUndef(LI.getType()),
11569                         Context->getNullValue(Op->getType()), &LI);
11570           return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11571         }
11572
11573       } else if (CE->isCast()) {
11574         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11575           return Res;
11576       }
11577     }
11578   }
11579     
11580   // If this load comes from anywhere in a constant global, and if the global
11581   // is all undef or zero, we know what it loads.
11582   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11583     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11584       if (GV->getInitializer()->isNullValue())
11585         return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
11586       else if (isa<UndefValue>(GV->getInitializer()))
11587         return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11588     }
11589   }
11590
11591   if (Op->hasOneUse()) {
11592     // Change select and PHI nodes to select values instead of addresses: this
11593     // helps alias analysis out a lot, allows many others simplifications, and
11594     // exposes redundancy in the code.
11595     //
11596     // Note that we cannot do the transformation unless we know that the
11597     // introduced loads cannot trap!  Something like this is valid as long as
11598     // the condition is always false: load (select bool %C, int* null, int* %G),
11599     // but it would not be valid if we transformed it to load from null
11600     // unconditionally.
11601     //
11602     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11603       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11604       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11605           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11606         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11607                                      SI->getOperand(1)->getName()+".val"), LI);
11608         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11609                                      SI->getOperand(2)->getName()+".val"), LI);
11610         return SelectInst::Create(SI->getCondition(), V1, V2);
11611       }
11612
11613       // load (select (cond, null, P)) -> load P
11614       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11615         if (C->isNullValue()) {
11616           LI.setOperand(0, SI->getOperand(2));
11617           return &LI;
11618         }
11619
11620       // load (select (cond, P, null)) -> load P
11621       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11622         if (C->isNullValue()) {
11623           LI.setOperand(0, SI->getOperand(1));
11624           return &LI;
11625         }
11626     }
11627   }
11628   return 0;
11629 }
11630
11631 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11632 /// when possible.  This makes it generally easy to do alias analysis and/or
11633 /// SROA/mem2reg of the memory object.
11634 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11635   User *CI = cast<User>(SI.getOperand(1));
11636   Value *CastOp = CI->getOperand(0);
11637   LLVMContext *Context = IC.getContext();
11638
11639   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11640   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11641   if (SrcTy == 0) return 0;
11642   
11643   const Type *SrcPTy = SrcTy->getElementType();
11644
11645   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11646     return 0;
11647   
11648   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11649   /// to its first element.  This allows us to handle things like:
11650   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11651   /// on 32-bit hosts.
11652   SmallVector<Value*, 4> NewGEPIndices;
11653   
11654   // If the source is an array, the code below will not succeed.  Check to
11655   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11656   // constants.
11657   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11658     // Index through pointer.
11659     Constant *Zero = Context->getNullValue(Type::Int32Ty);
11660     NewGEPIndices.push_back(Zero);
11661     
11662     while (1) {
11663       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11664         if (!STy->getNumElements()) /* Struct can be empty {} */
11665           break;
11666         NewGEPIndices.push_back(Zero);
11667         SrcPTy = STy->getElementType(0);
11668       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11669         NewGEPIndices.push_back(Zero);
11670         SrcPTy = ATy->getElementType();
11671       } else {
11672         break;
11673       }
11674     }
11675     
11676     SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
11677   }
11678
11679   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11680     return 0;
11681   
11682   // If the pointers point into different address spaces or if they point to
11683   // values with different sizes, we can't do the transformation.
11684   if (!IC.getTargetData() ||
11685       SrcTy->getAddressSpace() != 
11686         cast<PointerType>(CI->getType())->getAddressSpace() ||
11687       IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11688       IC.getTargetData()->getTypeSizeInBits(DestPTy))
11689     return 0;
11690
11691   // Okay, we are casting from one integer or pointer type to another of
11692   // the same size.  Instead of casting the pointer before 
11693   // the store, cast the value to be stored.
11694   Value *NewCast;
11695   Value *SIOp0 = SI.getOperand(0);
11696   Instruction::CastOps opcode = Instruction::BitCast;
11697   const Type* CastSrcTy = SIOp0->getType();
11698   const Type* CastDstTy = SrcPTy;
11699   if (isa<PointerType>(CastDstTy)) {
11700     if (CastSrcTy->isInteger())
11701       opcode = Instruction::IntToPtr;
11702   } else if (isa<IntegerType>(CastDstTy)) {
11703     if (isa<PointerType>(SIOp0->getType()))
11704       opcode = Instruction::PtrToInt;
11705   }
11706   
11707   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11708   // emit a GEP to index into its first field.
11709   if (!NewGEPIndices.empty()) {
11710     if (Constant *C = dyn_cast<Constant>(CastOp))
11711       CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0], 
11712                                               NewGEPIndices.size());
11713     else
11714       CastOp = IC.InsertNewInstBefore(
11715               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11716                                         NewGEPIndices.end()), SI);
11717   }
11718   
11719   if (Constant *C = dyn_cast<Constant>(SIOp0))
11720     NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
11721   else
11722     NewCast = IC.InsertNewInstBefore(
11723       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11724       SI);
11725   return new StoreInst(NewCast, CastOp);
11726 }
11727
11728 /// equivalentAddressValues - Test if A and B will obviously have the same
11729 /// value. This includes recognizing that %t0 and %t1 will have the same
11730 /// value in code like this:
11731 ///   %t0 = getelementptr \@a, 0, 3
11732 ///   store i32 0, i32* %t0
11733 ///   %t1 = getelementptr \@a, 0, 3
11734 ///   %t2 = load i32* %t1
11735 ///
11736 static bool equivalentAddressValues(Value *A, Value *B) {
11737   // Test if the values are trivially equivalent.
11738   if (A == B) return true;
11739   
11740   // Test if the values come form identical arithmetic instructions.
11741   if (isa<BinaryOperator>(A) ||
11742       isa<CastInst>(A) ||
11743       isa<PHINode>(A) ||
11744       isa<GetElementPtrInst>(A))
11745     if (Instruction *BI = dyn_cast<Instruction>(B))
11746       if (cast<Instruction>(A)->isIdenticalTo(BI))
11747         return true;
11748   
11749   // Otherwise they may not be equivalent.
11750   return false;
11751 }
11752
11753 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11754 // return the llvm.dbg.declare.
11755 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11756   if (!V->hasNUses(2))
11757     return 0;
11758   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11759        UI != E; ++UI) {
11760     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11761       return DI;
11762     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11763       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11764         return DI;
11765       }
11766   }
11767   return 0;
11768 }
11769
11770 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11771   Value *Val = SI.getOperand(0);
11772   Value *Ptr = SI.getOperand(1);
11773
11774   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11775     EraseInstFromFunction(SI);
11776     ++NumCombined;
11777     return 0;
11778   }
11779   
11780   // If the RHS is an alloca with a single use, zapify the store, making the
11781   // alloca dead.
11782   // If the RHS is an alloca with a two uses, the other one being a 
11783   // llvm.dbg.declare, zapify the store and the declare, making the
11784   // alloca dead.  We must do this to prevent declare's from affecting
11785   // codegen.
11786   if (!SI.isVolatile()) {
11787     if (Ptr->hasOneUse()) {
11788       if (isa<AllocaInst>(Ptr)) {
11789         EraseInstFromFunction(SI);
11790         ++NumCombined;
11791         return 0;
11792       }
11793       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11794         if (isa<AllocaInst>(GEP->getOperand(0))) {
11795           if (GEP->getOperand(0)->hasOneUse()) {
11796             EraseInstFromFunction(SI);
11797             ++NumCombined;
11798             return 0;
11799           }
11800           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11801             EraseInstFromFunction(*DI);
11802             EraseInstFromFunction(SI);
11803             ++NumCombined;
11804             return 0;
11805           }
11806         }
11807       }
11808     }
11809     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11810       EraseInstFromFunction(*DI);
11811       EraseInstFromFunction(SI);
11812       ++NumCombined;
11813       return 0;
11814     }
11815   }
11816
11817   // Attempt to improve the alignment.
11818   if (TD) {
11819     unsigned KnownAlign =
11820       GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11821     if (KnownAlign >
11822         (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11823                                   SI.getAlignment()))
11824       SI.setAlignment(KnownAlign);
11825   }
11826
11827   // Do really simple DSE, to catch cases where there are several consecutive
11828   // stores to the same location, separated by a few arithmetic operations. This
11829   // situation often occurs with bitfield accesses.
11830   BasicBlock::iterator BBI = &SI;
11831   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11832        --ScanInsts) {
11833     --BBI;
11834     // Don't count debug info directives, lest they affect codegen,
11835     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11836     // It is necessary for correctness to skip those that feed into a
11837     // llvm.dbg.declare, as these are not present when debugging is off.
11838     if (isa<DbgInfoIntrinsic>(BBI) ||
11839         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11840       ScanInsts++;
11841       continue;
11842     }    
11843     
11844     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11845       // Prev store isn't volatile, and stores to the same location?
11846       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11847                                                           SI.getOperand(1))) {
11848         ++NumDeadStore;
11849         ++BBI;
11850         EraseInstFromFunction(*PrevSI);
11851         continue;
11852       }
11853       break;
11854     }
11855     
11856     // If this is a load, we have to stop.  However, if the loaded value is from
11857     // the pointer we're loading and is producing the pointer we're storing,
11858     // then *this* store is dead (X = load P; store X -> P).
11859     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11860       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11861           !SI.isVolatile()) {
11862         EraseInstFromFunction(SI);
11863         ++NumCombined;
11864         return 0;
11865       }
11866       // Otherwise, this is a load from some other location.  Stores before it
11867       // may not be dead.
11868       break;
11869     }
11870     
11871     // Don't skip over loads or things that can modify memory.
11872     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11873       break;
11874   }
11875   
11876   
11877   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11878
11879   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11880   if (isa<ConstantPointerNull>(Ptr) &&
11881       cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11882     if (!isa<UndefValue>(Val)) {
11883       SI.setOperand(0, Context->getUndef(Val->getType()));
11884       if (Instruction *U = dyn_cast<Instruction>(Val))
11885         AddToWorkList(U);  // Dropped a use.
11886       ++NumCombined;
11887     }
11888     return 0;  // Do not modify these!
11889   }
11890
11891   // store undef, Ptr -> noop
11892   if (isa<UndefValue>(Val)) {
11893     EraseInstFromFunction(SI);
11894     ++NumCombined;
11895     return 0;
11896   }
11897
11898   // If the pointer destination is a cast, see if we can fold the cast into the
11899   // source instead.
11900   if (isa<CastInst>(Ptr))
11901     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11902       return Res;
11903   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11904     if (CE->isCast())
11905       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11906         return Res;
11907
11908   
11909   // If this store is the last instruction in the basic block (possibly
11910   // excepting debug info instructions and the pointer bitcasts that feed
11911   // into them), and if the block ends with an unconditional branch, try
11912   // to move it to the successor block.
11913   BBI = &SI; 
11914   do {
11915     ++BBI;
11916   } while (isa<DbgInfoIntrinsic>(BBI) ||
11917            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11918   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11919     if (BI->isUnconditional())
11920       if (SimplifyStoreAtEndOfBlock(SI))
11921         return 0;  // xform done!
11922   
11923   return 0;
11924 }
11925
11926 /// SimplifyStoreAtEndOfBlock - Turn things like:
11927 ///   if () { *P = v1; } else { *P = v2 }
11928 /// into a phi node with a store in the successor.
11929 ///
11930 /// Simplify things like:
11931 ///   *P = v1; if () { *P = v2; }
11932 /// into a phi node with a store in the successor.
11933 ///
11934 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11935   BasicBlock *StoreBB = SI.getParent();
11936   
11937   // Check to see if the successor block has exactly two incoming edges.  If
11938   // so, see if the other predecessor contains a store to the same location.
11939   // if so, insert a PHI node (if needed) and move the stores down.
11940   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11941   
11942   // Determine whether Dest has exactly two predecessors and, if so, compute
11943   // the other predecessor.
11944   pred_iterator PI = pred_begin(DestBB);
11945   BasicBlock *OtherBB = 0;
11946   if (*PI != StoreBB)
11947     OtherBB = *PI;
11948   ++PI;
11949   if (PI == pred_end(DestBB))
11950     return false;
11951   
11952   if (*PI != StoreBB) {
11953     if (OtherBB)
11954       return false;
11955     OtherBB = *PI;
11956   }
11957   if (++PI != pred_end(DestBB))
11958     return false;
11959
11960   // Bail out if all the relevant blocks aren't distinct (this can happen,
11961   // for example, if SI is in an infinite loop)
11962   if (StoreBB == DestBB || OtherBB == DestBB)
11963     return false;
11964
11965   // Verify that the other block ends in a branch and is not otherwise empty.
11966   BasicBlock::iterator BBI = OtherBB->getTerminator();
11967   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11968   if (!OtherBr || BBI == OtherBB->begin())
11969     return false;
11970   
11971   // If the other block ends in an unconditional branch, check for the 'if then
11972   // else' case.  there is an instruction before the branch.
11973   StoreInst *OtherStore = 0;
11974   if (OtherBr->isUnconditional()) {
11975     --BBI;
11976     // Skip over debugging info.
11977     while (isa<DbgInfoIntrinsic>(BBI) ||
11978            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11979       if (BBI==OtherBB->begin())
11980         return false;
11981       --BBI;
11982     }
11983     // If this isn't a store, or isn't a store to the same location, bail out.
11984     OtherStore = dyn_cast<StoreInst>(BBI);
11985     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11986       return false;
11987   } else {
11988     // Otherwise, the other block ended with a conditional branch. If one of the
11989     // destinations is StoreBB, then we have the if/then case.
11990     if (OtherBr->getSuccessor(0) != StoreBB && 
11991         OtherBr->getSuccessor(1) != StoreBB)
11992       return false;
11993     
11994     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11995     // if/then triangle.  See if there is a store to the same ptr as SI that
11996     // lives in OtherBB.
11997     for (;; --BBI) {
11998       // Check to see if we find the matching store.
11999       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12000         if (OtherStore->getOperand(1) != SI.getOperand(1))
12001           return false;
12002         break;
12003       }
12004       // If we find something that may be using or overwriting the stored
12005       // value, or if we run out of instructions, we can't do the xform.
12006       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12007           BBI == OtherBB->begin())
12008         return false;
12009     }
12010     
12011     // In order to eliminate the store in OtherBr, we have to
12012     // make sure nothing reads or overwrites the stored value in
12013     // StoreBB.
12014     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12015       // FIXME: This should really be AA driven.
12016       if (I->mayReadFromMemory() || I->mayWriteToMemory())
12017         return false;
12018     }
12019   }
12020   
12021   // Insert a PHI node now if we need it.
12022   Value *MergedVal = OtherStore->getOperand(0);
12023   if (MergedVal != SI.getOperand(0)) {
12024     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12025     PN->reserveOperandSpace(2);
12026     PN->addIncoming(SI.getOperand(0), SI.getParent());
12027     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12028     MergedVal = InsertNewInstBefore(PN, DestBB->front());
12029   }
12030   
12031   // Advance to a place where it is safe to insert the new store and
12032   // insert it.
12033   BBI = DestBB->getFirstNonPHI();
12034   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12035                                     OtherStore->isVolatile()), *BBI);
12036   
12037   // Nuke the old stores.
12038   EraseInstFromFunction(SI);
12039   EraseInstFromFunction(*OtherStore);
12040   ++NumCombined;
12041   return true;
12042 }
12043
12044
12045 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12046   // Change br (not X), label True, label False to: br X, label False, True
12047   Value *X = 0;
12048   BasicBlock *TrueDest;
12049   BasicBlock *FalseDest;
12050   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
12051       !isa<Constant>(X)) {
12052     // Swap Destinations and condition...
12053     BI.setCondition(X);
12054     BI.setSuccessor(0, FalseDest);
12055     BI.setSuccessor(1, TrueDest);
12056     return &BI;
12057   }
12058
12059   // Cannonicalize fcmp_one -> fcmp_oeq
12060   FCmpInst::Predicate FPred; Value *Y;
12061   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
12062                              TrueDest, FalseDest), *Context))
12063     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12064          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12065       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12066       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
12067       Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
12068       NewSCC->takeName(I);
12069       // Swap Destinations and condition...
12070       BI.setCondition(NewSCC);
12071       BI.setSuccessor(0, FalseDest);
12072       BI.setSuccessor(1, TrueDest);
12073       RemoveFromWorkList(I);
12074       I->eraseFromParent();
12075       AddToWorkList(NewSCC);
12076       return &BI;
12077     }
12078
12079   // Cannonicalize icmp_ne -> icmp_eq
12080   ICmpInst::Predicate IPred;
12081   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12082                       TrueDest, FalseDest), *Context))
12083     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12084          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12085          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12086       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12087       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
12088       Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
12089       NewSCC->takeName(I);
12090       // Swap Destinations and condition...
12091       BI.setCondition(NewSCC);
12092       BI.setSuccessor(0, FalseDest);
12093       BI.setSuccessor(1, TrueDest);
12094       RemoveFromWorkList(I);
12095       I->eraseFromParent();;
12096       AddToWorkList(NewSCC);
12097       return &BI;
12098     }
12099
12100   return 0;
12101 }
12102
12103 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12104   Value *Cond = SI.getCondition();
12105   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12106     if (I->getOpcode() == Instruction::Add)
12107       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12108         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12109         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12110           SI.setOperand(i,
12111                    Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
12112                                                 AddRHS));
12113         SI.setOperand(0, I->getOperand(0));
12114         AddToWorkList(I);
12115         return &SI;
12116       }
12117   }
12118   return 0;
12119 }
12120
12121 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12122   Value *Agg = EV.getAggregateOperand();
12123
12124   if (!EV.hasIndices())
12125     return ReplaceInstUsesWith(EV, Agg);
12126
12127   if (Constant *C = dyn_cast<Constant>(Agg)) {
12128     if (isa<UndefValue>(C))
12129       return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
12130       
12131     if (isa<ConstantAggregateZero>(C))
12132       return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
12133
12134     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12135       // Extract the element indexed by the first index out of the constant
12136       Value *V = C->getOperand(*EV.idx_begin());
12137       if (EV.getNumIndices() > 1)
12138         // Extract the remaining indices out of the constant indexed by the
12139         // first index
12140         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12141       else
12142         return ReplaceInstUsesWith(EV, V);
12143     }
12144     return 0; // Can't handle other constants
12145   } 
12146   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12147     // We're extracting from an insertvalue instruction, compare the indices
12148     const unsigned *exti, *exte, *insi, *inse;
12149     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12150          exte = EV.idx_end(), inse = IV->idx_end();
12151          exti != exte && insi != inse;
12152          ++exti, ++insi) {
12153       if (*insi != *exti)
12154         // The insert and extract both reference distinctly different elements.
12155         // This means the extract is not influenced by the insert, and we can
12156         // replace the aggregate operand of the extract with the aggregate
12157         // operand of the insert. i.e., replace
12158         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12159         // %E = extractvalue { i32, { i32 } } %I, 0
12160         // with
12161         // %E = extractvalue { i32, { i32 } } %A, 0
12162         return ExtractValueInst::Create(IV->getAggregateOperand(),
12163                                         EV.idx_begin(), EV.idx_end());
12164     }
12165     if (exti == exte && insi == inse)
12166       // Both iterators are at the end: Index lists are identical. Replace
12167       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12168       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12169       // with "i32 42"
12170       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12171     if (exti == exte) {
12172       // The extract list is a prefix of the insert list. i.e. replace
12173       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12174       // %E = extractvalue { i32, { i32 } } %I, 1
12175       // with
12176       // %X = extractvalue { i32, { i32 } } %A, 1
12177       // %E = insertvalue { i32 } %X, i32 42, 0
12178       // by switching the order of the insert and extract (though the
12179       // insertvalue should be left in, since it may have other uses).
12180       Value *NewEV = InsertNewInstBefore(
12181         ExtractValueInst::Create(IV->getAggregateOperand(),
12182                                  EV.idx_begin(), EV.idx_end()),
12183         EV);
12184       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12185                                      insi, inse);
12186     }
12187     if (insi == inse)
12188       // The insert list is a prefix of the extract list
12189       // We can simply remove the common indices from the extract and make it
12190       // operate on the inserted value instead of the insertvalue result.
12191       // i.e., replace
12192       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12193       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12194       // with
12195       // %E extractvalue { i32 } { i32 42 }, 0
12196       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12197                                       exti, exte);
12198   }
12199   // Can't simplify extracts from other values. Note that nested extracts are
12200   // already simplified implicitely by the above (extract ( extract (insert) )
12201   // will be translated into extract ( insert ( extract ) ) first and then just
12202   // the value inserted, if appropriate).
12203   return 0;
12204 }
12205
12206 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12207 /// is to leave as a vector operation.
12208 static bool CheapToScalarize(Value *V, bool isConstant) {
12209   if (isa<ConstantAggregateZero>(V)) 
12210     return true;
12211   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12212     if (isConstant) return true;
12213     // If all elts are the same, we can extract.
12214     Constant *Op0 = C->getOperand(0);
12215     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12216       if (C->getOperand(i) != Op0)
12217         return false;
12218     return true;
12219   }
12220   Instruction *I = dyn_cast<Instruction>(V);
12221   if (!I) return false;
12222   
12223   // Insert element gets simplified to the inserted element or is deleted if
12224   // this is constant idx extract element and its a constant idx insertelt.
12225   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12226       isa<ConstantInt>(I->getOperand(2)))
12227     return true;
12228   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12229     return true;
12230   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12231     if (BO->hasOneUse() &&
12232         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12233          CheapToScalarize(BO->getOperand(1), isConstant)))
12234       return true;
12235   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12236     if (CI->hasOneUse() &&
12237         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12238          CheapToScalarize(CI->getOperand(1), isConstant)))
12239       return true;
12240   
12241   return false;
12242 }
12243
12244 /// Read and decode a shufflevector mask.
12245 ///
12246 /// It turns undef elements into values that are larger than the number of
12247 /// elements in the input.
12248 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12249   unsigned NElts = SVI->getType()->getNumElements();
12250   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12251     return std::vector<unsigned>(NElts, 0);
12252   if (isa<UndefValue>(SVI->getOperand(2)))
12253     return std::vector<unsigned>(NElts, 2*NElts);
12254
12255   std::vector<unsigned> Result;
12256   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12257   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12258     if (isa<UndefValue>(*i))
12259       Result.push_back(NElts*2);  // undef -> 8
12260     else
12261       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12262   return Result;
12263 }
12264
12265 /// FindScalarElement - Given a vector and an element number, see if the scalar
12266 /// value is already around as a register, for example if it were inserted then
12267 /// extracted from the vector.
12268 static Value *FindScalarElement(Value *V, unsigned EltNo,
12269                                 LLVMContext *Context) {
12270   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12271   const VectorType *PTy = cast<VectorType>(V->getType());
12272   unsigned Width = PTy->getNumElements();
12273   if (EltNo >= Width)  // Out of range access.
12274     return Context->getUndef(PTy->getElementType());
12275   
12276   if (isa<UndefValue>(V))
12277     return Context->getUndef(PTy->getElementType());
12278   else if (isa<ConstantAggregateZero>(V))
12279     return Context->getNullValue(PTy->getElementType());
12280   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12281     return CP->getOperand(EltNo);
12282   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12283     // If this is an insert to a variable element, we don't know what it is.
12284     if (!isa<ConstantInt>(III->getOperand(2))) 
12285       return 0;
12286     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12287     
12288     // If this is an insert to the element we are looking for, return the
12289     // inserted value.
12290     if (EltNo == IIElt) 
12291       return III->getOperand(1);
12292     
12293     // Otherwise, the insertelement doesn't modify the value, recurse on its
12294     // vector input.
12295     return FindScalarElement(III->getOperand(0), EltNo, Context);
12296   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12297     unsigned LHSWidth =
12298       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12299     unsigned InEl = getShuffleMask(SVI)[EltNo];
12300     if (InEl < LHSWidth)
12301       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12302     else if (InEl < LHSWidth*2)
12303       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12304     else
12305       return Context->getUndef(PTy->getElementType());
12306   }
12307   
12308   // Otherwise, we don't know.
12309   return 0;
12310 }
12311
12312 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12313   // If vector val is undef, replace extract with scalar undef.
12314   if (isa<UndefValue>(EI.getOperand(0)))
12315     return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12316
12317   // If vector val is constant 0, replace extract with scalar 0.
12318   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12319     return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
12320   
12321   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12322     // If vector val is constant with all elements the same, replace EI with
12323     // that element. When the elements are not identical, we cannot replace yet
12324     // (we do that below, but only when the index is constant).
12325     Constant *op0 = C->getOperand(0);
12326     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12327       if (C->getOperand(i) != op0) {
12328         op0 = 0; 
12329         break;
12330       }
12331     if (op0)
12332       return ReplaceInstUsesWith(EI, op0);
12333   }
12334   
12335   // If extracting a specified index from the vector, see if we can recursively
12336   // find a previously computed scalar that was inserted into the vector.
12337   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12338     unsigned IndexVal = IdxC->getZExtValue();
12339     unsigned VectorWidth = 
12340       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12341       
12342     // If this is extracting an invalid index, turn this into undef, to avoid
12343     // crashing the code below.
12344     if (IndexVal >= VectorWidth)
12345       return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12346     
12347     // This instruction only demands the single element from the input vector.
12348     // If the input vector has a single use, simplify it based on this use
12349     // property.
12350     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12351       APInt UndefElts(VectorWidth, 0);
12352       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12353       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12354                                                 DemandedMask, UndefElts)) {
12355         EI.setOperand(0, V);
12356         return &EI;
12357       }
12358     }
12359     
12360     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12361       return ReplaceInstUsesWith(EI, Elt);
12362     
12363     // If the this extractelement is directly using a bitcast from a vector of
12364     // the same number of elements, see if we can find the source element from
12365     // it.  In this case, we will end up needing to bitcast the scalars.
12366     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12367       if (const VectorType *VT = 
12368               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12369         if (VT->getNumElements() == VectorWidth)
12370           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12371                                              IndexVal, Context))
12372             return new BitCastInst(Elt, EI.getType());
12373     }
12374   }
12375   
12376   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12377     if (I->hasOneUse()) {
12378       // Push extractelement into predecessor operation if legal and
12379       // profitable to do so
12380       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12381         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12382         if (CheapToScalarize(BO, isConstantElt)) {
12383           ExtractElementInst *newEI0 = 
12384             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12385                                    EI.getName()+".lhs");
12386           ExtractElementInst *newEI1 =
12387             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12388                                    EI.getName()+".rhs");
12389           InsertNewInstBefore(newEI0, EI);
12390           InsertNewInstBefore(newEI1, EI);
12391           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12392         }
12393       } else if (isa<LoadInst>(I)) {
12394         unsigned AS = 
12395           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12396         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12397                                   Context->getPointerType(EI.getType(), AS),EI);
12398         GetElementPtrInst *GEP =
12399           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12400         InsertNewInstBefore(GEP, EI);
12401         return new LoadInst(GEP);
12402       }
12403     }
12404     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12405       // Extracting the inserted element?
12406       if (IE->getOperand(2) == EI.getOperand(1))
12407         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12408       // If the inserted and extracted elements are constants, they must not
12409       // be the same value, extract from the pre-inserted value instead.
12410       if (isa<Constant>(IE->getOperand(2)) &&
12411           isa<Constant>(EI.getOperand(1))) {
12412         AddUsesToWorkList(EI);
12413         EI.setOperand(0, IE->getOperand(0));
12414         return &EI;
12415       }
12416     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12417       // If this is extracting an element from a shufflevector, figure out where
12418       // it came from and extract from the appropriate input element instead.
12419       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12420         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12421         Value *Src;
12422         unsigned LHSWidth =
12423           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12424
12425         if (SrcIdx < LHSWidth)
12426           Src = SVI->getOperand(0);
12427         else if (SrcIdx < LHSWidth*2) {
12428           SrcIdx -= LHSWidth;
12429           Src = SVI->getOperand(1);
12430         } else {
12431           return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12432         }
12433         return new ExtractElementInst(Src,
12434                          Context->getConstantInt(Type::Int32Ty, SrcIdx, false));
12435       }
12436     }
12437     // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12438   }
12439   return 0;
12440 }
12441
12442 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12443 /// elements from either LHS or RHS, return the shuffle mask and true. 
12444 /// Otherwise, return false.
12445 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12446                                          std::vector<Constant*> &Mask,
12447                                          LLVMContext *Context) {
12448   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12449          "Invalid CollectSingleShuffleElements");
12450   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12451
12452   if (isa<UndefValue>(V)) {
12453     Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12454     return true;
12455   } else if (V == LHS) {
12456     for (unsigned i = 0; i != NumElts; ++i)
12457       Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12458     return true;
12459   } else if (V == RHS) {
12460     for (unsigned i = 0; i != NumElts; ++i)
12461       Mask.push_back(Context->getConstantInt(Type::Int32Ty, i+NumElts));
12462     return true;
12463   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12464     // If this is an insert of an extract from some other vector, include it.
12465     Value *VecOp    = IEI->getOperand(0);
12466     Value *ScalarOp = IEI->getOperand(1);
12467     Value *IdxOp    = IEI->getOperand(2);
12468     
12469     if (!isa<ConstantInt>(IdxOp))
12470       return false;
12471     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12472     
12473     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12474       // Okay, we can handle this if the vector we are insertinting into is
12475       // transitively ok.
12476       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12477         // If so, update the mask to reflect the inserted undef.
12478         Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
12479         return true;
12480       }      
12481     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12482       if (isa<ConstantInt>(EI->getOperand(1)) &&
12483           EI->getOperand(0)->getType() == V->getType()) {
12484         unsigned ExtractedIdx =
12485           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12486         
12487         // This must be extracting from either LHS or RHS.
12488         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12489           // Okay, we can handle this if the vector we are insertinting into is
12490           // transitively ok.
12491           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12492             // If so, update the mask to reflect the inserted value.
12493             if (EI->getOperand(0) == LHS) {
12494               Mask[InsertedIdx % NumElts] = 
12495                  Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12496             } else {
12497               assert(EI->getOperand(0) == RHS);
12498               Mask[InsertedIdx % NumElts] = 
12499                 Context->getConstantInt(Type::Int32Ty, ExtractedIdx+NumElts);
12500               
12501             }
12502             return true;
12503           }
12504         }
12505       }
12506     }
12507   }
12508   // TODO: Handle shufflevector here!
12509   
12510   return false;
12511 }
12512
12513 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12514 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12515 /// that computes V and the LHS value of the shuffle.
12516 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12517                                      Value *&RHS, LLVMContext *Context) {
12518   assert(isa<VectorType>(V->getType()) && 
12519          (RHS == 0 || V->getType() == RHS->getType()) &&
12520          "Invalid shuffle!");
12521   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12522
12523   if (isa<UndefValue>(V)) {
12524     Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12525     return V;
12526   } else if (isa<ConstantAggregateZero>(V)) {
12527     Mask.assign(NumElts, Context->getConstantInt(Type::Int32Ty, 0));
12528     return V;
12529   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12530     // If this is an insert of an extract from some other vector, include it.
12531     Value *VecOp    = IEI->getOperand(0);
12532     Value *ScalarOp = IEI->getOperand(1);
12533     Value *IdxOp    = IEI->getOperand(2);
12534     
12535     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12536       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12537           EI->getOperand(0)->getType() == V->getType()) {
12538         unsigned ExtractedIdx =
12539           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12540         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12541         
12542         // Either the extracted from or inserted into vector must be RHSVec,
12543         // otherwise we'd end up with a shuffle of three inputs.
12544         if (EI->getOperand(0) == RHS || RHS == 0) {
12545           RHS = EI->getOperand(0);
12546           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12547           Mask[InsertedIdx % NumElts] = 
12548             Context->getConstantInt(Type::Int32Ty, NumElts+ExtractedIdx);
12549           return V;
12550         }
12551         
12552         if (VecOp == RHS) {
12553           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12554                                             RHS, Context);
12555           // Everything but the extracted element is replaced with the RHS.
12556           for (unsigned i = 0; i != NumElts; ++i) {
12557             if (i != InsertedIdx)
12558               Mask[i] = Context->getConstantInt(Type::Int32Ty, NumElts+i);
12559           }
12560           return V;
12561         }
12562         
12563         // If this insertelement is a chain that comes from exactly these two
12564         // vectors, return the vector and the effective shuffle.
12565         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12566                                          Context))
12567           return EI->getOperand(0);
12568         
12569       }
12570     }
12571   }
12572   // TODO: Handle shufflevector here!
12573   
12574   // Otherwise, can't do anything fancy.  Return an identity vector.
12575   for (unsigned i = 0; i != NumElts; ++i)
12576     Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12577   return V;
12578 }
12579
12580 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12581   Value *VecOp    = IE.getOperand(0);
12582   Value *ScalarOp = IE.getOperand(1);
12583   Value *IdxOp    = IE.getOperand(2);
12584   
12585   // Inserting an undef or into an undefined place, remove this.
12586   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12587     ReplaceInstUsesWith(IE, VecOp);
12588   
12589   // If the inserted element was extracted from some other vector, and if the 
12590   // indexes are constant, try to turn this into a shufflevector operation.
12591   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12592     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12593         EI->getOperand(0)->getType() == IE.getType()) {
12594       unsigned NumVectorElts = IE.getType()->getNumElements();
12595       unsigned ExtractedIdx =
12596         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12597       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12598       
12599       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12600         return ReplaceInstUsesWith(IE, VecOp);
12601       
12602       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12603         return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
12604       
12605       // If we are extracting a value from a vector, then inserting it right
12606       // back into the same place, just use the input vector.
12607       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12608         return ReplaceInstUsesWith(IE, VecOp);      
12609       
12610       // We could theoretically do this for ANY input.  However, doing so could
12611       // turn chains of insertelement instructions into a chain of shufflevector
12612       // instructions, and right now we do not merge shufflevectors.  As such,
12613       // only do this in a situation where it is clear that there is benefit.
12614       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12615         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12616         // the values of VecOp, except then one read from EIOp0.
12617         // Build a new shuffle mask.
12618         std::vector<Constant*> Mask;
12619         if (isa<UndefValue>(VecOp))
12620           Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
12621         else {
12622           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12623           Mask.assign(NumVectorElts, Context->getConstantInt(Type::Int32Ty,
12624                                                        NumVectorElts));
12625         } 
12626         Mask[InsertedIdx] = 
12627                            Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12628         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12629                                      Context->getConstantVector(Mask));
12630       }
12631       
12632       // If this insertelement isn't used by some other insertelement, turn it
12633       // (and any insertelements it points to), into one big shuffle.
12634       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12635         std::vector<Constant*> Mask;
12636         Value *RHS = 0;
12637         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12638         if (RHS == 0) RHS = Context->getUndef(LHS->getType());
12639         // We now have a shuffle of LHS, RHS, Mask.
12640         return new ShuffleVectorInst(LHS, RHS,
12641                                      Context->getConstantVector(Mask));
12642       }
12643     }
12644   }
12645
12646   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12647   APInt UndefElts(VWidth, 0);
12648   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12649   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12650     return &IE;
12651
12652   return 0;
12653 }
12654
12655
12656 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12657   Value *LHS = SVI.getOperand(0);
12658   Value *RHS = SVI.getOperand(1);
12659   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12660
12661   bool MadeChange = false;
12662
12663   // Undefined shuffle mask -> undefined value.
12664   if (isa<UndefValue>(SVI.getOperand(2)))
12665     return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
12666
12667   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12668
12669   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12670     return 0;
12671
12672   APInt UndefElts(VWidth, 0);
12673   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12674   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12675     LHS = SVI.getOperand(0);
12676     RHS = SVI.getOperand(1);
12677     MadeChange = true;
12678   }
12679   
12680   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12681   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12682   if (LHS == RHS || isa<UndefValue>(LHS)) {
12683     if (isa<UndefValue>(LHS) && LHS == RHS) {
12684       // shuffle(undef,undef,mask) -> undef.
12685       return ReplaceInstUsesWith(SVI, LHS);
12686     }
12687     
12688     // Remap any references to RHS to use LHS.
12689     std::vector<Constant*> Elts;
12690     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12691       if (Mask[i] >= 2*e)
12692         Elts.push_back(Context->getUndef(Type::Int32Ty));
12693       else {
12694         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12695             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12696           Mask[i] = 2*e;     // Turn into undef.
12697           Elts.push_back(Context->getUndef(Type::Int32Ty));
12698         } else {
12699           Mask[i] = Mask[i] % e;  // Force to LHS.
12700           Elts.push_back(Context->getConstantInt(Type::Int32Ty, Mask[i]));
12701         }
12702       }
12703     }
12704     SVI.setOperand(0, SVI.getOperand(1));
12705     SVI.setOperand(1, Context->getUndef(RHS->getType()));
12706     SVI.setOperand(2, Context->getConstantVector(Elts));
12707     LHS = SVI.getOperand(0);
12708     RHS = SVI.getOperand(1);
12709     MadeChange = true;
12710   }
12711   
12712   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12713   bool isLHSID = true, isRHSID = true;
12714     
12715   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12716     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12717     // Is this an identity shuffle of the LHS value?
12718     isLHSID &= (Mask[i] == i);
12719       
12720     // Is this an identity shuffle of the RHS value?
12721     isRHSID &= (Mask[i]-e == i);
12722   }
12723
12724   // Eliminate identity shuffles.
12725   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12726   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12727   
12728   // If the LHS is a shufflevector itself, see if we can combine it with this
12729   // one without producing an unusual shuffle.  Here we are really conservative:
12730   // we are absolutely afraid of producing a shuffle mask not in the input
12731   // program, because the code gen may not be smart enough to turn a merged
12732   // shuffle into two specific shuffles: it may produce worse code.  As such,
12733   // we only merge two shuffles if the result is one of the two input shuffle
12734   // masks.  In this case, merging the shuffles just removes one instruction,
12735   // which we know is safe.  This is good for things like turning:
12736   // (splat(splat)) -> splat.
12737   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12738     if (isa<UndefValue>(RHS)) {
12739       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12740
12741       std::vector<unsigned> NewMask;
12742       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12743         if (Mask[i] >= 2*e)
12744           NewMask.push_back(2*e);
12745         else
12746           NewMask.push_back(LHSMask[Mask[i]]);
12747       
12748       // If the result mask is equal to the src shuffle or this shuffle mask, do
12749       // the replacement.
12750       if (NewMask == LHSMask || NewMask == Mask) {
12751         unsigned LHSInNElts =
12752           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12753         std::vector<Constant*> Elts;
12754         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12755           if (NewMask[i] >= LHSInNElts*2) {
12756             Elts.push_back(Context->getUndef(Type::Int32Ty));
12757           } else {
12758             Elts.push_back(Context->getConstantInt(Type::Int32Ty, NewMask[i]));
12759           }
12760         }
12761         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12762                                      LHSSVI->getOperand(1),
12763                                      Context->getConstantVector(Elts));
12764       }
12765     }
12766   }
12767
12768   return MadeChange ? &SVI : 0;
12769 }
12770
12771
12772
12773
12774 /// TryToSinkInstruction - Try to move the specified instruction from its
12775 /// current block into the beginning of DestBlock, which can only happen if it's
12776 /// safe to move the instruction past all of the instructions between it and the
12777 /// end of its block.
12778 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12779   assert(I->hasOneUse() && "Invariants didn't hold!");
12780
12781   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12782   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12783     return false;
12784
12785   // Do not sink alloca instructions out of the entry block.
12786   if (isa<AllocaInst>(I) && I->getParent() ==
12787         &DestBlock->getParent()->getEntryBlock())
12788     return false;
12789
12790   // We can only sink load instructions if there is nothing between the load and
12791   // the end of block that could change the value.
12792   if (I->mayReadFromMemory()) {
12793     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12794          Scan != E; ++Scan)
12795       if (Scan->mayWriteToMemory())
12796         return false;
12797   }
12798
12799   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12800
12801   CopyPrecedingStopPoint(I, InsertPos);
12802   I->moveBefore(InsertPos);
12803   ++NumSunkInst;
12804   return true;
12805 }
12806
12807
12808 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12809 /// all reachable code to the worklist.
12810 ///
12811 /// This has a couple of tricks to make the code faster and more powerful.  In
12812 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12813 /// them to the worklist (this significantly speeds up instcombine on code where
12814 /// many instructions are dead or constant).  Additionally, if we find a branch
12815 /// whose condition is a known constant, we only visit the reachable successors.
12816 ///
12817 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12818                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12819                                        InstCombiner &IC,
12820                                        const TargetData *TD) {
12821   SmallVector<BasicBlock*, 256> Worklist;
12822   Worklist.push_back(BB);
12823
12824   while (!Worklist.empty()) {
12825     BB = Worklist.back();
12826     Worklist.pop_back();
12827     
12828     // We have now visited this block!  If we've already been here, ignore it.
12829     if (!Visited.insert(BB)) continue;
12830
12831     DbgInfoIntrinsic *DBI_Prev = NULL;
12832     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12833       Instruction *Inst = BBI++;
12834       
12835       // DCE instruction if trivially dead.
12836       if (isInstructionTriviallyDead(Inst)) {
12837         ++NumDeadInst;
12838         DOUT << "IC: DCE: " << *Inst;
12839         Inst->eraseFromParent();
12840         continue;
12841       }
12842       
12843       // ConstantProp instruction if trivially constant.
12844       if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12845         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12846         Inst->replaceAllUsesWith(C);
12847         ++NumConstProp;
12848         Inst->eraseFromParent();
12849         continue;
12850       }
12851      
12852       // If there are two consecutive llvm.dbg.stoppoint calls then
12853       // it is likely that the optimizer deleted code in between these
12854       // two intrinsics. 
12855       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12856       if (DBI_Next) {
12857         if (DBI_Prev
12858             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12859             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12860           IC.RemoveFromWorkList(DBI_Prev);
12861           DBI_Prev->eraseFromParent();
12862         }
12863         DBI_Prev = DBI_Next;
12864       } else {
12865         DBI_Prev = 0;
12866       }
12867
12868       IC.AddToWorkList(Inst);
12869     }
12870
12871     // Recursively visit successors.  If this is a branch or switch on a
12872     // constant, only visit the reachable successor.
12873     TerminatorInst *TI = BB->getTerminator();
12874     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12875       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12876         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12877         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12878         Worklist.push_back(ReachableBB);
12879         continue;
12880       }
12881     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12882       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12883         // See if this is an explicit destination.
12884         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12885           if (SI->getCaseValue(i) == Cond) {
12886             BasicBlock *ReachableBB = SI->getSuccessor(i);
12887             Worklist.push_back(ReachableBB);
12888             continue;
12889           }
12890         
12891         // Otherwise it is the default destination.
12892         Worklist.push_back(SI->getSuccessor(0));
12893         continue;
12894       }
12895     }
12896     
12897     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12898       Worklist.push_back(TI->getSuccessor(i));
12899   }
12900 }
12901
12902 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12903   bool Changed = false;
12904   TD = getAnalysisIfAvailable<TargetData>();
12905   
12906   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12907              << F.getNameStr() << "\n");
12908
12909   {
12910     // Do a depth-first traversal of the function, populate the worklist with
12911     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12912     // track of which blocks we visit.
12913     SmallPtrSet<BasicBlock*, 64> Visited;
12914     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12915
12916     // Do a quick scan over the function.  If we find any blocks that are
12917     // unreachable, remove any instructions inside of them.  This prevents
12918     // the instcombine code from having to deal with some bad special cases.
12919     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12920       if (!Visited.count(BB)) {
12921         Instruction *Term = BB->getTerminator();
12922         while (Term != BB->begin()) {   // Remove instrs bottom-up
12923           BasicBlock::iterator I = Term; --I;
12924
12925           DOUT << "IC: DCE: " << *I;
12926           // A debug intrinsic shouldn't force another iteration if we weren't
12927           // going to do one without it.
12928           if (!isa<DbgInfoIntrinsic>(I)) {
12929             ++NumDeadInst;
12930             Changed = true;
12931           }
12932           if (!I->use_empty())
12933             I->replaceAllUsesWith(Context->getUndef(I->getType()));
12934           I->eraseFromParent();
12935         }
12936       }
12937   }
12938
12939   while (!Worklist.empty()) {
12940     Instruction *I = RemoveOneFromWorkList();
12941     if (I == 0) continue;  // skip null values.
12942
12943     // Check to see if we can DCE the instruction.
12944     if (isInstructionTriviallyDead(I)) {
12945       // Add operands to the worklist.
12946       if (I->getNumOperands() < 4)
12947         AddUsesToWorkList(*I);
12948       ++NumDeadInst;
12949
12950       DOUT << "IC: DCE: " << *I;
12951
12952       I->eraseFromParent();
12953       RemoveFromWorkList(I);
12954       Changed = true;
12955       continue;
12956     }
12957
12958     // Instruction isn't dead, see if we can constant propagate it.
12959     if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12960       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12961
12962       // Add operands to the worklist.
12963       AddUsesToWorkList(*I);
12964       ReplaceInstUsesWith(*I, C);
12965
12966       ++NumConstProp;
12967       I->eraseFromParent();
12968       RemoveFromWorkList(I);
12969       Changed = true;
12970       continue;
12971     }
12972
12973     if (TD) {
12974       // See if we can constant fold its operands.
12975       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12976         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
12977           if (Constant *NewC = ConstantFoldConstantExpression(CE,   
12978                                   F.getContext(), TD))
12979             if (NewC != CE) {
12980               i->set(NewC);
12981               Changed = true;
12982             }
12983     }
12984
12985     // See if we can trivially sink this instruction to a successor basic block.
12986     if (I->hasOneUse()) {
12987       BasicBlock *BB = I->getParent();
12988       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12989       if (UserParent != BB) {
12990         bool UserIsSuccessor = false;
12991         // See if the user is one of our successors.
12992         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12993           if (*SI == UserParent) {
12994             UserIsSuccessor = true;
12995             break;
12996           }
12997
12998         // If the user is one of our immediate successors, and if that successor
12999         // only has us as a predecessors (we'd have to split the critical edge
13000         // otherwise), we can keep going.
13001         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13002             next(pred_begin(UserParent)) == pred_end(UserParent))
13003           // Okay, the CFG is simple enough, try to sink this instruction.
13004           Changed |= TryToSinkInstruction(I, UserParent);
13005       }
13006     }
13007
13008     // Now that we have an instruction, try combining it to simplify it...
13009 #ifndef NDEBUG
13010     std::string OrigI;
13011 #endif
13012     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
13013     if (Instruction *Result = visit(*I)) {
13014       ++NumCombined;
13015       // Should we replace the old instruction with a new one?
13016       if (Result != I) {
13017         DOUT << "IC: Old = " << *I
13018              << "    New = " << *Result;
13019
13020         // Everything uses the new instruction now.
13021         I->replaceAllUsesWith(Result);
13022
13023         // Push the new instruction and any users onto the worklist.
13024         AddToWorkList(Result);
13025         AddUsersToWorkList(*Result);
13026
13027         // Move the name to the new instruction first.
13028         Result->takeName(I);
13029
13030         // Insert the new instruction into the basic block...
13031         BasicBlock *InstParent = I->getParent();
13032         BasicBlock::iterator InsertPos = I;
13033
13034         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
13035           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13036             ++InsertPos;
13037
13038         InstParent->getInstList().insert(InsertPos, Result);
13039
13040         // Make sure that we reprocess all operands now that we reduced their
13041         // use counts.
13042         AddUsesToWorkList(*I);
13043
13044         // Instructions can end up on the worklist more than once.  Make sure
13045         // we do not process an instruction that has been deleted.
13046         RemoveFromWorkList(I);
13047
13048         // Erase the old instruction.
13049         InstParent->getInstList().erase(I);
13050       } else {
13051 #ifndef NDEBUG
13052         DOUT << "IC: Mod = " << OrigI
13053              << "    New = " << *I;
13054 #endif
13055
13056         // If the instruction was modified, it's possible that it is now dead.
13057         // if so, remove it.
13058         if (isInstructionTriviallyDead(I)) {
13059           // Make sure we process all operands now that we are reducing their
13060           // use counts.
13061           AddUsesToWorkList(*I);
13062
13063           // Instructions may end up in the worklist more than once.  Erase all
13064           // occurrences of this instruction.
13065           RemoveFromWorkList(I);
13066           I->eraseFromParent();
13067         } else {
13068           AddToWorkList(I);
13069           AddUsersToWorkList(*I);
13070         }
13071       }
13072       Changed = true;
13073     }
13074   }
13075
13076   assert(WorklistMap.empty() && "Worklist empty, but map not?");
13077     
13078   // Do an explicit clear, this shrinks the map if needed.
13079   WorklistMap.clear();
13080   return Changed;
13081 }
13082
13083
13084 bool InstCombiner::runOnFunction(Function &F) {
13085   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13086   Context = &F.getContext();
13087   
13088   bool EverMadeChange = false;
13089
13090   // Iterate while there is work to do.
13091   unsigned Iteration = 0;
13092   while (DoOneIteration(F, Iteration++))
13093     EverMadeChange = true;
13094   return EverMadeChange;
13095 }
13096
13097 FunctionPass *llvm::createInstructionCombiningPass() {
13098   return new InstCombiner();
13099 }