Rename getConstantInt{True|False} to get{True|False} at Chris' behest.
[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 *getContext() { return Context; }
89
90     /// AddToWorkList - Add the specified instruction to the worklist if it
91     /// isn't already in it.
92     void AddToWorkList(Instruction *I) {
93       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
94         Worklist.push_back(I);
95     }
96     
97     // RemoveFromWorkList - remove I from the worklist if it exists.
98     void RemoveFromWorkList(Instruction *I) {
99       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
100       if (It == WorklistMap.end()) return; // Not in worklist.
101       
102       // Don't bother moving everything down, just null out the slot.
103       Worklist[It->second] = 0;
104       
105       WorklistMap.erase(It);
106     }
107     
108     Instruction *RemoveOneFromWorkList() {
109       Instruction *I = Worklist.back();
110       Worklist.pop_back();
111       WorklistMap.erase(I);
112       return I;
113     }
114
115     
116     /// AddUsersToWorkList - When an instruction is simplified, add all users of
117     /// the instruction to the work lists because they might get more simplified
118     /// now.
119     ///
120     void AddUsersToWorkList(Value &I) {
121       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
122            UI != UE; ++UI)
123         AddToWorkList(cast<Instruction>(*UI));
124     }
125
126     /// AddUsesToWorkList - When an instruction is simplified, add operands to
127     /// the work lists because they might get more simplified now.
128     ///
129     void AddUsesToWorkList(Instruction &I) {
130       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
131         if (Instruction *Op = dyn_cast<Instruction>(*i))
132           AddToWorkList(Op);
133     }
134     
135     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
136     /// dead.  Add all of its operands to the worklist, turning them into
137     /// undef's to reduce the number of uses of those instructions.
138     ///
139     /// Return the specified operand before it is turned into an undef.
140     ///
141     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
142       Value *R = I.getOperand(op);
143       
144       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
145         if (Instruction *Op = dyn_cast<Instruction>(*i)) {
146           AddToWorkList(Op);
147           // Set the operand to undef to drop the use.
148           *i = Context->getUndef(Op->getType());
149         }
150       
151       return R;
152     }
153
154   public:
155     virtual bool runOnFunction(Function &F);
156     
157     bool DoOneIteration(Function &F, unsigned ItNum);
158
159     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
160       AU.addRequired<TargetData>();
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, TD->getIntPtrType());
473   
474   // We don't want to form an inttoptr or ptrtoint that converts to an integer
475   // type that differs from the pointer size.
476   if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
477       (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
478     Res = 0;
479   
480   return Instruction::CastOps(Res);
481 }
482
483 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
484 /// in any code being generated.  It does not require codegen if V is simple
485 /// enough or if the cast can be folded into other casts.
486 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
487                               const Type *Ty, TargetData *TD) {
488   if (V->getType() == Ty || isa<Constant>(V)) return false;
489   
490   // If this is another cast that can be eliminated, it isn't codegen either.
491   if (const CastInst *CI = dyn_cast<CastInst>(V))
492     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
493       return false;
494   return true;
495 }
496
497 // SimplifyCommutative - This performs a few simplifications for commutative
498 // operators:
499 //
500 //  1. Order operands such that they are listed from right (least complex) to
501 //     left (most complex).  This puts constants before unary operators before
502 //     binary operators.
503 //
504 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
505 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
506 //
507 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
508   bool Changed = false;
509   if (getComplexity(Context, I.getOperand(0)) < 
510       getComplexity(Context, I.getOperand(1)))
511     Changed = !I.swapOperands();
512
513   if (!I.isAssociative()) return Changed;
514   Instruction::BinaryOps Opcode = I.getOpcode();
515   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
516     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
517       if (isa<Constant>(I.getOperand(1))) {
518         Constant *Folded = Context->getConstantExpr(I.getOpcode(),
519                                              cast<Constant>(I.getOperand(1)),
520                                              cast<Constant>(Op->getOperand(1)));
521         I.setOperand(0, Op->getOperand(0));
522         I.setOperand(1, Folded);
523         return true;
524       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
525         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
526             isOnlyUse(Op) && isOnlyUse(Op1)) {
527           Constant *C1 = cast<Constant>(Op->getOperand(1));
528           Constant *C2 = cast<Constant>(Op1->getOperand(1));
529
530           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
531           Constant *Folded = Context->getConstantExpr(I.getOpcode(), C1, C2);
532           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
533                                                     Op1->getOperand(0),
534                                                     Op1->getName(), &I);
535           AddToWorkList(New);
536           I.setOperand(0, New);
537           I.setOperand(1, Folded);
538           return true;
539         }
540     }
541   return Changed;
542 }
543
544 /// SimplifyCompare - For a CmpInst this function just orders the operands
545 /// so that theyare listed from right (least complex) to left (most complex).
546 /// This puts constants before unary operators before binary operators.
547 bool InstCombiner::SimplifyCompare(CmpInst &I) {
548   if (getComplexity(Context, I.getOperand(0)) >=
549       getComplexity(Context, I.getOperand(1)))
550     return false;
551   I.swapOperands();
552   // Compare instructions are not associative so there's nothing else we can do.
553   return true;
554 }
555
556 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
557 // if the LHS is a constant zero (which is the 'negate' form).
558 //
559 static inline Value *dyn_castNegVal(Value *V, LLVMContext *Context) {
560   if (BinaryOperator::isNeg(V))
561     return BinaryOperator::getNegArgument(V);
562
563   // Constants can be considered to be negated values if they can be folded.
564   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
565     return Context->getConstantExprNeg(C);
566
567   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
568     if (C->getType()->getElementType()->isInteger())
569       return Context->getConstantExprNeg(C);
570
571   return 0;
572 }
573
574 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
575 // instruction if the LHS is a constant negative zero (which is the 'negate'
576 // form).
577 //
578 static inline Value *dyn_castFNegVal(Value *V, LLVMContext *Context) {
579   if (BinaryOperator::isFNeg(V))
580     return BinaryOperator::getFNegArgument(V);
581
582   // Constants can be considered to be negated values if they can be folded.
583   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
584     return Context->getConstantExprFNeg(C);
585
586   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
587     if (C->getType()->getElementType()->isFloatingPoint())
588       return Context->getConstantExprFNeg(C);
589
590   return 0;
591 }
592
593 static inline Value *dyn_castNotVal(Value *V, LLVMContext *Context) {
594   if (BinaryOperator::isNot(V))
595     return BinaryOperator::getNotArgument(V);
596
597   // Constants can be considered to be not'ed values...
598   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
599     return Context->getConstantInt(~C->getValue());
600   return 0;
601 }
602
603 // dyn_castFoldableMul - If this value is a multiply that can be folded into
604 // other computations (because it has a constant operand), return the
605 // non-constant operand of the multiply, and set CST to point to the multiplier.
606 // Otherwise, return null.
607 //
608 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST,
609                                          LLVMContext *Context) {
610   if (V->hasOneUse() && V->getType()->isInteger())
611     if (Instruction *I = dyn_cast<Instruction>(V)) {
612       if (I->getOpcode() == Instruction::Mul)
613         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
614           return I->getOperand(0);
615       if (I->getOpcode() == Instruction::Shl)
616         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
617           // The multiplier is really 1 << CST.
618           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
619           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
620           CST = Context->getConstantInt(APInt(BitWidth, 1).shl(CSTVal));
621           return I->getOperand(0);
622         }
623     }
624   return 0;
625 }
626
627 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
628 /// expression, return it.
629 static User *dyn_castGetElementPtr(Value *V) {
630   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
631   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
632     if (CE->getOpcode() == Instruction::GetElementPtr)
633       return cast<User>(V);
634   return false;
635 }
636
637 /// AddOne - Add one to a ConstantInt
638 static Constant *AddOne(Constant *C, LLVMContext *Context) {
639   return Context->getConstantExprAdd(C, 
640     Context->getConstantInt(C->getType(), 1));
641 }
642 /// SubOne - Subtract one from a ConstantInt
643 static Constant *SubOne(ConstantInt *C, LLVMContext *Context) {
644   return Context->getConstantExprSub(C, 
645     Context->getConstantInt(C->getType(), 1));
646 }
647 /// MultiplyOverflows - True if the multiply can not be expressed in an int
648 /// this size.
649 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign,
650                               LLVMContext *Context) {
651   uint32_t W = C1->getBitWidth();
652   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
653   if (sign) {
654     LHSExt.sext(W * 2);
655     RHSExt.sext(W * 2);
656   } else {
657     LHSExt.zext(W * 2);
658     RHSExt.zext(W * 2);
659   }
660
661   APInt MulExt = LHSExt * RHSExt;
662
663   if (sign) {
664     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
665     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
666     return MulExt.slt(Min) || MulExt.sgt(Max);
667   } else 
668     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
669 }
670
671
672 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
673 /// specified instruction is a constant integer.  If so, check to see if there
674 /// are any bits set in the constant that are not demanded.  If so, shrink the
675 /// constant and return true.
676 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
677                                    APInt Demanded, LLVMContext *Context) {
678   assert(I && "No instruction?");
679   assert(OpNo < I->getNumOperands() && "Operand index too large");
680
681   // If the operand is not a constant integer, nothing to do.
682   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
683   if (!OpC) return false;
684
685   // If there are no bits set that aren't demanded, nothing to do.
686   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
687   if ((~Demanded & OpC->getValue()) == 0)
688     return false;
689
690   // This instruction is producing bits that are not demanded. Shrink the RHS.
691   Demanded &= OpC->getValue();
692   I->setOperand(OpNo, Context->getConstantInt(Demanded));
693   return true;
694 }
695
696 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
697 // set of known zero and one bits, compute the maximum and minimum values that
698 // could have the specified known zero and known one bits, returning them in
699 // min/max.
700 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
701                                                    const APInt& KnownOne,
702                                                    APInt& Min, APInt& Max) {
703   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
704          KnownZero.getBitWidth() == Min.getBitWidth() &&
705          KnownZero.getBitWidth() == Max.getBitWidth() &&
706          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
707   APInt UnknownBits = ~(KnownZero|KnownOne);
708
709   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
710   // bit if it is unknown.
711   Min = KnownOne;
712   Max = KnownOne|UnknownBits;
713   
714   if (UnknownBits.isNegative()) { // Sign bit is unknown
715     Min.set(Min.getBitWidth()-1);
716     Max.clear(Max.getBitWidth()-1);
717   }
718 }
719
720 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
721 // a set of known zero and one bits, compute the maximum and minimum values that
722 // could have the specified known zero and known one bits, returning them in
723 // min/max.
724 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
725                                                      const APInt &KnownOne,
726                                                      APInt &Min, APInt &Max) {
727   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
728          KnownZero.getBitWidth() == Min.getBitWidth() &&
729          KnownZero.getBitWidth() == Max.getBitWidth() &&
730          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
731   APInt UnknownBits = ~(KnownZero|KnownOne);
732   
733   // The minimum value is when the unknown bits are all zeros.
734   Min = KnownOne;
735   // The maximum value is when the unknown bits are all ones.
736   Max = KnownOne|UnknownBits;
737 }
738
739 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
740 /// SimplifyDemandedBits knows about.  See if the instruction has any
741 /// properties that allow us to simplify its operands.
742 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
743   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
744   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
745   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
746   
747   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
748                                      KnownZero, KnownOne, 0);
749   if (V == 0) return false;
750   if (V == &Inst) return true;
751   ReplaceInstUsesWith(Inst, V);
752   return true;
753 }
754
755 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
756 /// specified instruction operand if possible, updating it in place.  It returns
757 /// true if it made any change and false otherwise.
758 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
759                                         APInt &KnownZero, APInt &KnownOne,
760                                         unsigned Depth) {
761   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
762                                           KnownZero, KnownOne, Depth);
763   if (NewVal == 0) return false;
764   U.set(NewVal);
765   return true;
766 }
767
768
769 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
770 /// value based on the demanded bits.  When this function is called, it is known
771 /// that only the bits set in DemandedMask of the result of V are ever used
772 /// downstream. Consequently, depending on the mask and V, it may be possible
773 /// to replace V with a constant or one of its operands. In such cases, this
774 /// function does the replacement and returns true. In all other cases, it
775 /// returns false after analyzing the expression and setting KnownOne and known
776 /// to be one in the expression.  KnownZero contains all the bits that are known
777 /// to be zero in the expression. These are provided to potentially allow the
778 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
779 /// the expression. KnownOne and KnownZero always follow the invariant that 
780 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
781 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
782 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
783 /// and KnownOne must all be the same.
784 ///
785 /// This returns null if it did not change anything and it permits no
786 /// simplification.  This returns V itself if it did some simplification of V's
787 /// operands based on the information about what bits are demanded. This returns
788 /// some other non-null value if it found out that V is equal to another value
789 /// in the context where the specified bits are demanded, but not for all users.
790 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
791                                              APInt &KnownZero, APInt &KnownOne,
792                                              unsigned Depth) {
793   assert(V != 0 && "Null pointer of Value???");
794   assert(Depth <= 6 && "Limit Search Depth");
795   uint32_t BitWidth = DemandedMask.getBitWidth();
796   const Type *VTy = V->getType();
797   assert((TD || !isa<PointerType>(VTy)) &&
798          "SimplifyDemandedBits needs to know bit widths!");
799   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
800          (!VTy->isIntOrIntVector() ||
801           VTy->getScalarSizeInBits() == BitWidth) &&
802          KnownZero.getBitWidth() == BitWidth &&
803          KnownOne.getBitWidth() == BitWidth &&
804          "Value *V, DemandedMask, KnownZero and KnownOne "
805          "must have same BitWidth");
806   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
807     // We know all of the bits for a constant!
808     KnownOne = CI->getValue() & DemandedMask;
809     KnownZero = ~KnownOne & DemandedMask;
810     return 0;
811   }
812   if (isa<ConstantPointerNull>(V)) {
813     // We know all of the bits for a constant!
814     KnownOne.clear();
815     KnownZero = DemandedMask;
816     return 0;
817   }
818
819   KnownZero.clear();
820   KnownOne.clear();
821   if (DemandedMask == 0) {   // Not demanding any bits from V.
822     if (isa<UndefValue>(V))
823       return 0;
824     return Context->getUndef(VTy);
825   }
826   
827   if (Depth == 6)        // Limit search depth.
828     return 0;
829   
830   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
831   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
832
833   Instruction *I = dyn_cast<Instruction>(V);
834   if (!I) {
835     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
836     return 0;        // Only analyze instructions.
837   }
838
839   // If there are multiple uses of this value and we aren't at the root, then
840   // we can't do any simplifications of the operands, because DemandedMask
841   // only reflects the bits demanded by *one* of the users.
842   if (Depth != 0 && !I->hasOneUse()) {
843     // Despite the fact that we can't simplify this instruction in all User's
844     // context, we can at least compute the knownzero/knownone bits, and we can
845     // do simplifications that apply to *just* the one user if we know that
846     // this instruction has a simpler value in that context.
847     if (I->getOpcode() == Instruction::And) {
848       // If either the LHS or the RHS are Zero, the result is zero.
849       ComputeMaskedBits(I->getOperand(1), DemandedMask,
850                         RHSKnownZero, RHSKnownOne, Depth+1);
851       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
852                         LHSKnownZero, LHSKnownOne, Depth+1);
853       
854       // If all of the demanded bits are known 1 on one side, return the other.
855       // These bits cannot contribute to the result of the 'and' in this
856       // context.
857       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
858           (DemandedMask & ~LHSKnownZero))
859         return I->getOperand(0);
860       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
861           (DemandedMask & ~RHSKnownZero))
862         return I->getOperand(1);
863       
864       // If all of the demanded bits in the inputs are known zeros, return zero.
865       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
866         return Context->getNullValue(VTy);
867       
868     } else if (I->getOpcode() == Instruction::Or) {
869       // We can simplify (X|Y) -> X or Y in the user's context if we know that
870       // only bits from X or Y are demanded.
871       
872       // If either the LHS or the RHS are One, the result is One.
873       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
874                         RHSKnownZero, RHSKnownOne, Depth+1);
875       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
876                         LHSKnownZero, LHSKnownOne, Depth+1);
877       
878       // If all of the demanded bits are known zero on one side, return the
879       // other.  These bits cannot contribute to the result of the 'or' in this
880       // context.
881       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
882           (DemandedMask & ~LHSKnownOne))
883         return I->getOperand(0);
884       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
885           (DemandedMask & ~RHSKnownOne))
886         return I->getOperand(1);
887       
888       // If all of the potentially set bits on one side are known to be set on
889       // the other side, just use the 'other' side.
890       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
891           (DemandedMask & (~RHSKnownZero)))
892         return I->getOperand(0);
893       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
894           (DemandedMask & (~LHSKnownZero)))
895         return I->getOperand(1);
896     }
897     
898     // Compute the KnownZero/KnownOne bits to simplify things downstream.
899     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
900     return 0;
901   }
902   
903   // If this is the root being simplified, allow it to have multiple uses,
904   // just set the DemandedMask to all bits so that we can try to simplify the
905   // operands.  This allows visitTruncInst (for example) to simplify the
906   // operand of a trunc without duplicating all the logic below.
907   if (Depth == 0 && !V->hasOneUse())
908     DemandedMask = APInt::getAllOnesValue(BitWidth);
909   
910   switch (I->getOpcode()) {
911   default:
912     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
913     break;
914   case Instruction::And:
915     // If either the LHS or the RHS are Zero, the result is zero.
916     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
917                              RHSKnownZero, RHSKnownOne, Depth+1) ||
918         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
919                              LHSKnownZero, LHSKnownOne, Depth+1))
920       return I;
921     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
922     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
923
924     // If all of the demanded bits are known 1 on one side, return the other.
925     // These bits cannot contribute to the result of the 'and'.
926     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
927         (DemandedMask & ~LHSKnownZero))
928       return I->getOperand(0);
929     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
930         (DemandedMask & ~RHSKnownZero))
931       return I->getOperand(1);
932     
933     // If all of the demanded bits in the inputs are known zeros, return zero.
934     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
935       return Context->getNullValue(VTy);
936       
937     // If the RHS is a constant, see if we can simplify it.
938     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero, Context))
939       return I;
940       
941     // Output known-1 bits are only known if set in both the LHS & RHS.
942     RHSKnownOne &= LHSKnownOne;
943     // Output known-0 are known to be clear if zero in either the LHS | RHS.
944     RHSKnownZero |= LHSKnownZero;
945     break;
946   case Instruction::Or:
947     // If either the LHS or the RHS are One, the result is One.
948     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
949                              RHSKnownZero, RHSKnownOne, Depth+1) ||
950         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
951                              LHSKnownZero, LHSKnownOne, Depth+1))
952       return I;
953     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
954     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
955     
956     // If all of the demanded bits are known zero on one side, return the other.
957     // These bits cannot contribute to the result of the 'or'.
958     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
959         (DemandedMask & ~LHSKnownOne))
960       return I->getOperand(0);
961     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
962         (DemandedMask & ~RHSKnownOne))
963       return I->getOperand(1);
964
965     // If all of the potentially set bits on one side are known to be set on
966     // the other side, just use the 'other' side.
967     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
968         (DemandedMask & (~RHSKnownZero)))
969       return I->getOperand(0);
970     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
971         (DemandedMask & (~LHSKnownZero)))
972       return I->getOperand(1);
973         
974     // If the RHS is a constant, see if we can simplify it.
975     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
976       return I;
977           
978     // Output known-0 bits are only known if clear in both the LHS & RHS.
979     RHSKnownZero &= LHSKnownZero;
980     // Output known-1 are known to be set if set in either the LHS | RHS.
981     RHSKnownOne |= LHSKnownOne;
982     break;
983   case Instruction::Xor: {
984     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
985                              RHSKnownZero, RHSKnownOne, Depth+1) ||
986         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
987                              LHSKnownZero, LHSKnownOne, Depth+1))
988       return I;
989     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
990     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
991     
992     // If all of the demanded bits are known zero on one side, return the other.
993     // These bits cannot contribute to the result of the 'xor'.
994     if ((DemandedMask & RHSKnownZero) == DemandedMask)
995       return I->getOperand(0);
996     if ((DemandedMask & LHSKnownZero) == DemandedMask)
997       return I->getOperand(1);
998     
999     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1000     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1001                          (RHSKnownOne & LHSKnownOne);
1002     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1003     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1004                         (RHSKnownOne & LHSKnownZero);
1005     
1006     // If all of the demanded bits are known to be zero on one side or the
1007     // other, turn this into an *inclusive* or.
1008     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1009     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1010       Instruction *Or =
1011         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1012                                  I->getName());
1013       return InsertNewInstBefore(Or, *I);
1014     }
1015     
1016     // If all of the demanded bits on one side are known, and all of the set
1017     // bits on that side are also known to be set on the other side, turn this
1018     // into an AND, as we know the bits will be cleared.
1019     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1020     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1021       // all known
1022       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1023         Constant *AndC = Context->getConstantInt(~RHSKnownOne & DemandedMask);
1024         Instruction *And = 
1025           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1026         return InsertNewInstBefore(And, *I);
1027       }
1028     }
1029     
1030     // If the RHS is a constant, see if we can simplify it.
1031     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1032     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
1033       return I;
1034     
1035     RHSKnownZero = KnownZeroOut;
1036     RHSKnownOne  = KnownOneOut;
1037     break;
1038   }
1039   case Instruction::Select:
1040     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1041                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1042         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1043                              LHSKnownZero, LHSKnownOne, Depth+1))
1044       return I;
1045     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1046     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1047     
1048     // If the operands are constants, see if we can simplify them.
1049     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context) ||
1050         ShrinkDemandedConstant(I, 2, DemandedMask, Context))
1051       return I;
1052     
1053     // Only known if known in both the LHS and RHS.
1054     RHSKnownOne &= LHSKnownOne;
1055     RHSKnownZero &= LHSKnownZero;
1056     break;
1057   case Instruction::Trunc: {
1058     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1059     DemandedMask.zext(truncBf);
1060     RHSKnownZero.zext(truncBf);
1061     RHSKnownOne.zext(truncBf);
1062     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1063                              RHSKnownZero, RHSKnownOne, Depth+1))
1064       return I;
1065     DemandedMask.trunc(BitWidth);
1066     RHSKnownZero.trunc(BitWidth);
1067     RHSKnownOne.trunc(BitWidth);
1068     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1069     break;
1070   }
1071   case Instruction::BitCast:
1072     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1073       return false;  // vector->int or fp->int?
1074
1075     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1076       if (const VectorType *SrcVTy =
1077             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1078         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1079           // Don't touch a bitcast between vectors of different element counts.
1080           return false;
1081       } else
1082         // Don't touch a scalar-to-vector bitcast.
1083         return false;
1084     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1085       // Don't touch a vector-to-scalar bitcast.
1086       return false;
1087
1088     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1089                              RHSKnownZero, RHSKnownOne, Depth+1))
1090       return I;
1091     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1092     break;
1093   case Instruction::ZExt: {
1094     // Compute the bits in the result that are not present in the input.
1095     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1096     
1097     DemandedMask.trunc(SrcBitWidth);
1098     RHSKnownZero.trunc(SrcBitWidth);
1099     RHSKnownOne.trunc(SrcBitWidth);
1100     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1101                              RHSKnownZero, RHSKnownOne, Depth+1))
1102       return I;
1103     DemandedMask.zext(BitWidth);
1104     RHSKnownZero.zext(BitWidth);
1105     RHSKnownOne.zext(BitWidth);
1106     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1107     // The top bits are known to be zero.
1108     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1109     break;
1110   }
1111   case Instruction::SExt: {
1112     // Compute the bits in the result that are not present in the input.
1113     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1114     
1115     APInt InputDemandedBits = DemandedMask & 
1116                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1117
1118     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1119     // If any of the sign extended bits are demanded, we know that the sign
1120     // bit is demanded.
1121     if ((NewBits & DemandedMask) != 0)
1122       InputDemandedBits.set(SrcBitWidth-1);
1123       
1124     InputDemandedBits.trunc(SrcBitWidth);
1125     RHSKnownZero.trunc(SrcBitWidth);
1126     RHSKnownOne.trunc(SrcBitWidth);
1127     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1128                              RHSKnownZero, RHSKnownOne, Depth+1))
1129       return I;
1130     InputDemandedBits.zext(BitWidth);
1131     RHSKnownZero.zext(BitWidth);
1132     RHSKnownOne.zext(BitWidth);
1133     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1134       
1135     // If the sign bit of the input is known set or clear, then we know the
1136     // top bits of the result.
1137
1138     // If the input sign bit is known zero, or if the NewBits are not demanded
1139     // convert this into a zero extension.
1140     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1141       // Convert to ZExt cast
1142       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1143       return InsertNewInstBefore(NewCast, *I);
1144     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1145       RHSKnownOne |= NewBits;
1146     }
1147     break;
1148   }
1149   case Instruction::Add: {
1150     // Figure out what the input bits are.  If the top bits of the and result
1151     // are not demanded, then the add doesn't demand them from its input
1152     // either.
1153     unsigned NLZ = DemandedMask.countLeadingZeros();
1154       
1155     // If there is a constant on the RHS, there are a variety of xformations
1156     // we can do.
1157     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1158       // If null, this should be simplified elsewhere.  Some of the xforms here
1159       // won't work if the RHS is zero.
1160       if (RHS->isZero())
1161         break;
1162       
1163       // If the top bit of the output is demanded, demand everything from the
1164       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1165       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1166
1167       // Find information about known zero/one bits in the input.
1168       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1169                                LHSKnownZero, LHSKnownOne, Depth+1))
1170         return I;
1171
1172       // If the RHS of the add has bits set that can't affect the input, reduce
1173       // the constant.
1174       if (ShrinkDemandedConstant(I, 1, InDemandedBits, Context))
1175         return I;
1176       
1177       // Avoid excess work.
1178       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1179         break;
1180       
1181       // Turn it into OR if input bits are zero.
1182       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1183         Instruction *Or =
1184           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1185                                    I->getName());
1186         return InsertNewInstBefore(Or, *I);
1187       }
1188       
1189       // We can say something about the output known-zero and known-one bits,
1190       // depending on potential carries from the input constant and the
1191       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1192       // bits set and the RHS constant is 0x01001, then we know we have a known
1193       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1194       
1195       // To compute this, we first compute the potential carry bits.  These are
1196       // the bits which may be modified.  I'm not aware of a better way to do
1197       // this scan.
1198       const APInt &RHSVal = RHS->getValue();
1199       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1200       
1201       // Now that we know which bits have carries, compute the known-1/0 sets.
1202       
1203       // Bits are known one if they are known zero in one operand and one in the
1204       // other, and there is no input carry.
1205       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1206                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1207       
1208       // Bits are known zero if they are known zero in both operands and there
1209       // is no input carry.
1210       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1211     } else {
1212       // If the high-bits of this ADD are not demanded, then it does not demand
1213       // the high bits of its LHS or RHS.
1214       if (DemandedMask[BitWidth-1] == 0) {
1215         // Right fill the mask of bits for this ADD to demand the most
1216         // significant bit and all those below it.
1217         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1218         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1219                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1220             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1221                                  LHSKnownZero, LHSKnownOne, Depth+1))
1222           return I;
1223       }
1224     }
1225     break;
1226   }
1227   case Instruction::Sub:
1228     // If the high-bits of this SUB are not demanded, then it does not demand
1229     // the high bits of its LHS or RHS.
1230     if (DemandedMask[BitWidth-1] == 0) {
1231       // Right fill the mask of bits for this SUB to demand the most
1232       // significant bit and all those below it.
1233       uint32_t NLZ = DemandedMask.countLeadingZeros();
1234       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1235       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1236                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1237           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1238                                LHSKnownZero, LHSKnownOne, Depth+1))
1239         return I;
1240     }
1241     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1242     // the known zeros and ones.
1243     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1244     break;
1245   case Instruction::Shl:
1246     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1247       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1248       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1249       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1250                                RHSKnownZero, RHSKnownOne, Depth+1))
1251         return I;
1252       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1253       RHSKnownZero <<= ShiftAmt;
1254       RHSKnownOne  <<= ShiftAmt;
1255       // low bits known zero.
1256       if (ShiftAmt)
1257         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1258     }
1259     break;
1260   case Instruction::LShr:
1261     // For a logical shift right
1262     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1263       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1264       
1265       // Unsigned shift right.
1266       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1267       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1268                                RHSKnownZero, RHSKnownOne, Depth+1))
1269         return I;
1270       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1271       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1272       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1273       if (ShiftAmt) {
1274         // Compute the new bits that are at the top now.
1275         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1276         RHSKnownZero |= HighBits;  // high bits known zero.
1277       }
1278     }
1279     break;
1280   case Instruction::AShr:
1281     // If this is an arithmetic shift right and only the low-bit is set, we can
1282     // always convert this into a logical shr, even if the shift amount is
1283     // variable.  The low bit of the shift cannot be an input sign bit unless
1284     // the shift amount is >= the size of the datatype, which is undefined.
1285     if (DemandedMask == 1) {
1286       // Perform the logical shift right.
1287       Instruction *NewVal = BinaryOperator::CreateLShr(
1288                         I->getOperand(0), I->getOperand(1), I->getName());
1289       return InsertNewInstBefore(NewVal, *I);
1290     }    
1291
1292     // If the sign bit is the only bit demanded by this ashr, then there is no
1293     // need to do it, the shift doesn't change the high bit.
1294     if (DemandedMask.isSignBit())
1295       return I->getOperand(0);
1296     
1297     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1298       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1299       
1300       // Signed shift right.
1301       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1302       // If any of the "high bits" are demanded, we should set the sign bit as
1303       // demanded.
1304       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1305         DemandedMaskIn.set(BitWidth-1);
1306       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1307                                RHSKnownZero, RHSKnownOne, Depth+1))
1308         return I;
1309       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1310       // Compute the new bits that are at the top now.
1311       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1312       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1313       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1314         
1315       // Handle the sign bits.
1316       APInt SignBit(APInt::getSignBit(BitWidth));
1317       // Adjust to where it is now in the mask.
1318       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1319         
1320       // If the input sign bit is known to be zero, or if none of the top bits
1321       // are demanded, turn this into an unsigned shift right.
1322       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1323           (HighBits & ~DemandedMask) == HighBits) {
1324         // Perform the logical shift right.
1325         Instruction *NewVal = BinaryOperator::CreateLShr(
1326                           I->getOperand(0), SA, I->getName());
1327         return InsertNewInstBefore(NewVal, *I);
1328       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1329         RHSKnownOne |= HighBits;
1330       }
1331     }
1332     break;
1333   case Instruction::SRem:
1334     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1335       APInt RA = Rem->getValue().abs();
1336       if (RA.isPowerOf2()) {
1337         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1338           return I->getOperand(0);
1339
1340         APInt LowBits = RA - 1;
1341         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1342         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1343                                  LHSKnownZero, LHSKnownOne, Depth+1))
1344           return I;
1345
1346         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1347           LHSKnownZero |= ~LowBits;
1348
1349         KnownZero |= LHSKnownZero & DemandedMask;
1350
1351         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1352       }
1353     }
1354     break;
1355   case Instruction::URem: {
1356     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1357     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1358     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1359                              KnownZero2, KnownOne2, Depth+1) ||
1360         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1361                              KnownZero2, KnownOne2, Depth+1))
1362       return I;
1363
1364     unsigned Leaders = KnownZero2.countLeadingOnes();
1365     Leaders = std::max(Leaders,
1366                        KnownZero2.countLeadingOnes());
1367     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1368     break;
1369   }
1370   case Instruction::Call:
1371     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1372       switch (II->getIntrinsicID()) {
1373       default: break;
1374       case Intrinsic::bswap: {
1375         // If the only bits demanded come from one byte of the bswap result,
1376         // just shift the input byte into position to eliminate the bswap.
1377         unsigned NLZ = DemandedMask.countLeadingZeros();
1378         unsigned NTZ = DemandedMask.countTrailingZeros();
1379           
1380         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1381         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1382         // have 14 leading zeros, round to 8.
1383         NLZ &= ~7;
1384         NTZ &= ~7;
1385         // If we need exactly one byte, we can do this transformation.
1386         if (BitWidth-NLZ-NTZ == 8) {
1387           unsigned ResultBit = NTZ;
1388           unsigned InputBit = BitWidth-NTZ-8;
1389           
1390           // Replace this with either a left or right shift to get the byte into
1391           // the right place.
1392           Instruction *NewVal;
1393           if (InputBit > ResultBit)
1394             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1395                     Context->getConstantInt(I->getType(), InputBit-ResultBit));
1396           else
1397             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1398                     Context->getConstantInt(I->getType(), ResultBit-InputBit));
1399           NewVal->takeName(I);
1400           return InsertNewInstBefore(NewVal, *I);
1401         }
1402           
1403         // TODO: Could compute known zero/one bits based on the input.
1404         break;
1405       }
1406       }
1407     }
1408     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1409     break;
1410   }
1411   
1412   // If the client is only demanding bits that we know, return the known
1413   // constant.
1414   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1415     Constant *C = Context->getConstantInt(RHSKnownOne);
1416     if (isa<PointerType>(V->getType()))
1417       C = Context->getConstantExprIntToPtr(C, V->getType());
1418     return C;
1419   }
1420   return false;
1421 }
1422
1423
1424 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1425 /// any number of elements. DemandedElts contains the set of elements that are
1426 /// actually used by the caller.  This method analyzes which elements of the
1427 /// operand are undef and returns that information in UndefElts.
1428 ///
1429 /// If the information about demanded elements can be used to simplify the
1430 /// operation, the operation is simplified, then the resultant value is
1431 /// returned.  This returns null if no change was made.
1432 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1433                                                 APInt& UndefElts,
1434                                                 unsigned Depth) {
1435   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1436   APInt EltMask(APInt::getAllOnesValue(VWidth));
1437   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1438
1439   if (isa<UndefValue>(V)) {
1440     // If the entire vector is undefined, just return this info.
1441     UndefElts = EltMask;
1442     return 0;
1443   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1444     UndefElts = EltMask;
1445     return Context->getUndef(V->getType());
1446   }
1447
1448   UndefElts = 0;
1449   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1450     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1451     Constant *Undef = Context->getUndef(EltTy);
1452
1453     std::vector<Constant*> Elts;
1454     for (unsigned i = 0; i != VWidth; ++i)
1455       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1456         Elts.push_back(Undef);
1457         UndefElts.set(i);
1458       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1459         Elts.push_back(Undef);
1460         UndefElts.set(i);
1461       } else {                               // Otherwise, defined.
1462         Elts.push_back(CP->getOperand(i));
1463       }
1464
1465     // If we changed the constant, return it.
1466     Constant *NewCP = Context->getConstantVector(Elts);
1467     return NewCP != CP ? NewCP : 0;
1468   } else if (isa<ConstantAggregateZero>(V)) {
1469     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1470     // set to undef.
1471     
1472     // Check if this is identity. If so, return 0 since we are not simplifying
1473     // anything.
1474     if (DemandedElts == ((1ULL << VWidth) -1))
1475       return 0;
1476     
1477     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1478     Constant *Zero = Context->getNullValue(EltTy);
1479     Constant *Undef = Context->getUndef(EltTy);
1480     std::vector<Constant*> Elts;
1481     for (unsigned i = 0; i != VWidth; ++i) {
1482       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1483       Elts.push_back(Elt);
1484     }
1485     UndefElts = DemandedElts ^ EltMask;
1486     return Context->getConstantVector(Elts);
1487   }
1488   
1489   // Limit search depth.
1490   if (Depth == 10)
1491     return 0;
1492
1493   // If multiple users are using the root value, procede with
1494   // simplification conservatively assuming that all elements
1495   // are needed.
1496   if (!V->hasOneUse()) {
1497     // Quit if we find multiple users of a non-root value though.
1498     // They'll be handled when it's their turn to be visited by
1499     // the main instcombine process.
1500     if (Depth != 0)
1501       // TODO: Just compute the UndefElts information recursively.
1502       return 0;
1503
1504     // Conservatively assume that all elements are needed.
1505     DemandedElts = EltMask;
1506   }
1507   
1508   Instruction *I = dyn_cast<Instruction>(V);
1509   if (!I) return 0;        // Only analyze instructions.
1510   
1511   bool MadeChange = false;
1512   APInt UndefElts2(VWidth, 0);
1513   Value *TmpV;
1514   switch (I->getOpcode()) {
1515   default: break;
1516     
1517   case Instruction::InsertElement: {
1518     // If this is a variable index, we don't know which element it overwrites.
1519     // demand exactly the same input as we produce.
1520     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1521     if (Idx == 0) {
1522       // Note that we can't propagate undef elt info, because we don't know
1523       // which elt is getting updated.
1524       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1525                                         UndefElts2, Depth+1);
1526       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1527       break;
1528     }
1529     
1530     // If this is inserting an element that isn't demanded, remove this
1531     // insertelement.
1532     unsigned IdxNo = Idx->getZExtValue();
1533     if (IdxNo >= VWidth || !DemandedElts[IdxNo])
1534       return AddSoonDeadInstToWorklist(*I, 0);
1535     
1536     // Otherwise, the element inserted overwrites whatever was there, so the
1537     // input demanded set is simpler than the output set.
1538     APInt DemandedElts2 = DemandedElts;
1539     DemandedElts2.clear(IdxNo);
1540     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1541                                       UndefElts, Depth+1);
1542     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1543
1544     // The inserted element is defined.
1545     UndefElts.clear(IdxNo);
1546     break;
1547   }
1548   case Instruction::ShuffleVector: {
1549     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1550     uint64_t LHSVWidth =
1551       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1552     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1553     for (unsigned i = 0; i < VWidth; i++) {
1554       if (DemandedElts[i]) {
1555         unsigned MaskVal = Shuffle->getMaskValue(i);
1556         if (MaskVal != -1u) {
1557           assert(MaskVal < LHSVWidth * 2 &&
1558                  "shufflevector mask index out of range!");
1559           if (MaskVal < LHSVWidth)
1560             LeftDemanded.set(MaskVal);
1561           else
1562             RightDemanded.set(MaskVal - LHSVWidth);
1563         }
1564       }
1565     }
1566
1567     APInt UndefElts4(LHSVWidth, 0);
1568     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1569                                       UndefElts4, Depth+1);
1570     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1571
1572     APInt UndefElts3(LHSVWidth, 0);
1573     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1574                                       UndefElts3, Depth+1);
1575     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1576
1577     bool NewUndefElts = false;
1578     for (unsigned i = 0; i < VWidth; i++) {
1579       unsigned MaskVal = Shuffle->getMaskValue(i);
1580       if (MaskVal == -1u) {
1581         UndefElts.set(i);
1582       } else if (MaskVal < LHSVWidth) {
1583         if (UndefElts4[MaskVal]) {
1584           NewUndefElts = true;
1585           UndefElts.set(i);
1586         }
1587       } else {
1588         if (UndefElts3[MaskVal - LHSVWidth]) {
1589           NewUndefElts = true;
1590           UndefElts.set(i);
1591         }
1592       }
1593     }
1594
1595     if (NewUndefElts) {
1596       // Add additional discovered undefs.
1597       std::vector<Constant*> Elts;
1598       for (unsigned i = 0; i < VWidth; ++i) {
1599         if (UndefElts[i])
1600           Elts.push_back(Context->getUndef(Type::Int32Ty));
1601         else
1602           Elts.push_back(Context->getConstantInt(Type::Int32Ty,
1603                                           Shuffle->getMaskValue(i)));
1604       }
1605       I->setOperand(2, Context->getConstantVector(Elts));
1606       MadeChange = true;
1607     }
1608     break;
1609   }
1610   case Instruction::BitCast: {
1611     // Vector->vector casts only.
1612     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1613     if (!VTy) break;
1614     unsigned InVWidth = VTy->getNumElements();
1615     APInt InputDemandedElts(InVWidth, 0);
1616     unsigned Ratio;
1617
1618     if (VWidth == InVWidth) {
1619       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1620       // elements as are demanded of us.
1621       Ratio = 1;
1622       InputDemandedElts = DemandedElts;
1623     } else if (VWidth > InVWidth) {
1624       // Untested so far.
1625       break;
1626       
1627       // If there are more elements in the result than there are in the source,
1628       // then an input element is live if any of the corresponding output
1629       // elements are live.
1630       Ratio = VWidth/InVWidth;
1631       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1632         if (DemandedElts[OutIdx])
1633           InputDemandedElts.set(OutIdx/Ratio);
1634       }
1635     } else {
1636       // Untested so far.
1637       break;
1638       
1639       // If there are more elements in the source than there are in the result,
1640       // then an input element is live if the corresponding output element is
1641       // live.
1642       Ratio = InVWidth/VWidth;
1643       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1644         if (DemandedElts[InIdx/Ratio])
1645           InputDemandedElts.set(InIdx);
1646     }
1647     
1648     // div/rem demand all inputs, because they don't want divide by zero.
1649     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1650                                       UndefElts2, Depth+1);
1651     if (TmpV) {
1652       I->setOperand(0, TmpV);
1653       MadeChange = true;
1654     }
1655     
1656     UndefElts = UndefElts2;
1657     if (VWidth > InVWidth) {
1658       llvm_unreachable("Unimp");
1659       // If there are more elements in the result than there are in the source,
1660       // then an output element is undef if the corresponding input element is
1661       // undef.
1662       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1663         if (UndefElts2[OutIdx/Ratio])
1664           UndefElts.set(OutIdx);
1665     } else if (VWidth < InVWidth) {
1666       llvm_unreachable("Unimp");
1667       // If there are more elements in the source than there are in the result,
1668       // then a result element is undef if all of the corresponding input
1669       // elements are undef.
1670       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1671       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1672         if (!UndefElts2[InIdx])            // Not undef?
1673           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1674     }
1675     break;
1676   }
1677   case Instruction::And:
1678   case Instruction::Or:
1679   case Instruction::Xor:
1680   case Instruction::Add:
1681   case Instruction::Sub:
1682   case Instruction::Mul:
1683     // div/rem demand all inputs, because they don't want divide by zero.
1684     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1685                                       UndefElts, Depth+1);
1686     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1687     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1688                                       UndefElts2, Depth+1);
1689     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1690       
1691     // Output elements are undefined if both are undefined.  Consider things
1692     // like undef&0.  The result is known zero, not undef.
1693     UndefElts &= UndefElts2;
1694     break;
1695     
1696   case Instruction::Call: {
1697     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1698     if (!II) break;
1699     switch (II->getIntrinsicID()) {
1700     default: break;
1701       
1702     // Binary vector operations that work column-wise.  A dest element is a
1703     // function of the corresponding input elements from the two inputs.
1704     case Intrinsic::x86_sse_sub_ss:
1705     case Intrinsic::x86_sse_mul_ss:
1706     case Intrinsic::x86_sse_min_ss:
1707     case Intrinsic::x86_sse_max_ss:
1708     case Intrinsic::x86_sse2_sub_sd:
1709     case Intrinsic::x86_sse2_mul_sd:
1710     case Intrinsic::x86_sse2_min_sd:
1711     case Intrinsic::x86_sse2_max_sd:
1712       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1713                                         UndefElts, Depth+1);
1714       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1715       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1716                                         UndefElts2, Depth+1);
1717       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1718
1719       // If only the low elt is demanded and this is a scalarizable intrinsic,
1720       // scalarize it now.
1721       if (DemandedElts == 1) {
1722         switch (II->getIntrinsicID()) {
1723         default: break;
1724         case Intrinsic::x86_sse_sub_ss:
1725         case Intrinsic::x86_sse_mul_ss:
1726         case Intrinsic::x86_sse2_sub_sd:
1727         case Intrinsic::x86_sse2_mul_sd:
1728           // TODO: Lower MIN/MAX/ABS/etc
1729           Value *LHS = II->getOperand(1);
1730           Value *RHS = II->getOperand(2);
1731           // Extract the element as scalars.
1732           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 
1733             Context->getConstantInt(Type::Int32Ty, 0U, false), "tmp"), *II);
1734           RHS = InsertNewInstBefore(new ExtractElementInst(RHS,
1735             Context->getConstantInt(Type::Int32Ty, 0U, false), "tmp"), *II);
1736           
1737           switch (II->getIntrinsicID()) {
1738           default: llvm_unreachable("Case stmts out of sync!");
1739           case Intrinsic::x86_sse_sub_ss:
1740           case Intrinsic::x86_sse2_sub_sd:
1741             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1742                                                         II->getName()), *II);
1743             break;
1744           case Intrinsic::x86_sse_mul_ss:
1745           case Intrinsic::x86_sse2_mul_sd:
1746             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1747                                                          II->getName()), *II);
1748             break;
1749           }
1750           
1751           Instruction *New =
1752             InsertElementInst::Create(
1753               Context->getUndef(II->getType()), TmpV,
1754               Context->getConstantInt(Type::Int32Ty, 0U, false), II->getName());
1755           InsertNewInstBefore(New, *II);
1756           AddSoonDeadInstToWorklist(*II, 0);
1757           return New;
1758         }            
1759       }
1760         
1761       // Output elements are undefined if both are undefined.  Consider things
1762       // like undef&0.  The result is known zero, not undef.
1763       UndefElts &= UndefElts2;
1764       break;
1765     }
1766     break;
1767   }
1768   }
1769   return MadeChange ? I : 0;
1770 }
1771
1772
1773 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1774 /// function is designed to check a chain of associative operators for a
1775 /// potential to apply a certain optimization.  Since the optimization may be
1776 /// applicable if the expression was reassociated, this checks the chain, then
1777 /// reassociates the expression as necessary to expose the optimization
1778 /// opportunity.  This makes use of a special Functor, which must define
1779 /// 'shouldApply' and 'apply' methods.
1780 ///
1781 template<typename Functor>
1782 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F,
1783                                    LLVMContext *Context) {
1784   unsigned Opcode = Root.getOpcode();
1785   Value *LHS = Root.getOperand(0);
1786
1787   // Quick check, see if the immediate LHS matches...
1788   if (F.shouldApply(LHS))
1789     return F.apply(Root);
1790
1791   // Otherwise, if the LHS is not of the same opcode as the root, return.
1792   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1793   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1794     // Should we apply this transform to the RHS?
1795     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1796
1797     // If not to the RHS, check to see if we should apply to the LHS...
1798     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1799       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1800       ShouldApply = true;
1801     }
1802
1803     // If the functor wants to apply the optimization to the RHS of LHSI,
1804     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1805     if (ShouldApply) {
1806       // Now all of the instructions are in the current basic block, go ahead
1807       // and perform the reassociation.
1808       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1809
1810       // First move the selected RHS to the LHS of the root...
1811       Root.setOperand(0, LHSI->getOperand(1));
1812
1813       // Make what used to be the LHS of the root be the user of the root...
1814       Value *ExtraOperand = TmpLHSI->getOperand(1);
1815       if (&Root == TmpLHSI) {
1816         Root.replaceAllUsesWith(Context->getNullValue(TmpLHSI->getType()));
1817         return 0;
1818       }
1819       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1820       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1821       BasicBlock::iterator ARI = &Root; ++ARI;
1822       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1823       ARI = Root;
1824
1825       // Now propagate the ExtraOperand down the chain of instructions until we
1826       // get to LHSI.
1827       while (TmpLHSI != LHSI) {
1828         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1829         // Move the instruction to immediately before the chain we are
1830         // constructing to avoid breaking dominance properties.
1831         NextLHSI->moveBefore(ARI);
1832         ARI = NextLHSI;
1833
1834         Value *NextOp = NextLHSI->getOperand(1);
1835         NextLHSI->setOperand(1, ExtraOperand);
1836         TmpLHSI = NextLHSI;
1837         ExtraOperand = NextOp;
1838       }
1839
1840       // Now that the instructions are reassociated, have the functor perform
1841       // the transformation...
1842       return F.apply(Root);
1843     }
1844
1845     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1846   }
1847   return 0;
1848 }
1849
1850 namespace {
1851
1852 // AddRHS - Implements: X + X --> X << 1
1853 struct AddRHS {
1854   Value *RHS;
1855   LLVMContext *Context;
1856   AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
1857   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1858   Instruction *apply(BinaryOperator &Add) const {
1859     return BinaryOperator::CreateShl(Add.getOperand(0),
1860                                      Context->getConstantInt(Add.getType(), 1));
1861   }
1862 };
1863
1864 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1865 //                 iff C1&C2 == 0
1866 struct AddMaskingAnd {
1867   Constant *C2;
1868   LLVMContext *Context;
1869   AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
1870   bool shouldApply(Value *LHS) const {
1871     ConstantInt *C1;
1872     return match(LHS, m_And(m_Value(), m_ConstantInt(C1)), *Context) &&
1873            Context->getConstantExprAnd(C1, C2)->isNullValue();
1874   }
1875   Instruction *apply(BinaryOperator &Add) const {
1876     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1877   }
1878 };
1879
1880 }
1881
1882 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1883                                              InstCombiner *IC) {
1884   LLVMContext *Context = IC->getContext();
1885   
1886   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1887     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1888   }
1889
1890   // Figure out if the constant is the left or the right argument.
1891   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1892   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1893
1894   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1895     if (ConstIsRHS)
1896       return Context->getConstantExpr(I.getOpcode(), SOC, ConstOperand);
1897     return Context->getConstantExpr(I.getOpcode(), ConstOperand, SOC);
1898   }
1899
1900   Value *Op0 = SO, *Op1 = ConstOperand;
1901   if (!ConstIsRHS)
1902     std::swap(Op0, Op1);
1903   Instruction *New;
1904   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1905     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1906   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1907     New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1908                           Op0, Op1, SO->getName()+".cmp");
1909   else {
1910     llvm_unreachable("Unknown binary instruction type!");
1911   }
1912   return IC->InsertNewInstBefore(New, I);
1913 }
1914
1915 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1916 // constant as the other operand, try to fold the binary operator into the
1917 // select arguments.  This also works for Cast instructions, which obviously do
1918 // not have a second operand.
1919 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1920                                      InstCombiner *IC) {
1921   // Don't modify shared select instructions
1922   if (!SI->hasOneUse()) return 0;
1923   Value *TV = SI->getOperand(1);
1924   Value *FV = SI->getOperand(2);
1925
1926   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1927     // Bool selects with constant operands can be folded to logical ops.
1928     if (SI->getType() == Type::Int1Ty) return 0;
1929
1930     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1931     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1932
1933     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1934                               SelectFalseVal);
1935   }
1936   return 0;
1937 }
1938
1939
1940 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1941 /// node as operand #0, see if we can fold the instruction into the PHI (which
1942 /// is only possible if all operands to the PHI are constants).
1943 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1944   PHINode *PN = cast<PHINode>(I.getOperand(0));
1945   unsigned NumPHIValues = PN->getNumIncomingValues();
1946   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1947
1948   // Check to see if all of the operands of the PHI are constants.  If there is
1949   // one non-constant value, remember the BB it is.  If there is more than one
1950   // or if *it* is a PHI, bail out.
1951   BasicBlock *NonConstBB = 0;
1952   for (unsigned i = 0; i != NumPHIValues; ++i)
1953     if (!isa<Constant>(PN->getIncomingValue(i))) {
1954       if (NonConstBB) return 0;  // More than one non-const value.
1955       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1956       NonConstBB = PN->getIncomingBlock(i);
1957       
1958       // If the incoming non-constant value is in I's block, we have an infinite
1959       // loop.
1960       if (NonConstBB == I.getParent())
1961         return 0;
1962     }
1963   
1964   // If there is exactly one non-constant value, we can insert a copy of the
1965   // operation in that block.  However, if this is a critical edge, we would be
1966   // inserting the computation one some other paths (e.g. inside a loop).  Only
1967   // do this if the pred block is unconditionally branching into the phi block.
1968   if (NonConstBB) {
1969     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1970     if (!BI || !BI->isUnconditional()) return 0;
1971   }
1972
1973   // Okay, we can do the transformation: create the new PHI node.
1974   PHINode *NewPN = PHINode::Create(I.getType(), "");
1975   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1976   InsertNewInstBefore(NewPN, *PN);
1977   NewPN->takeName(PN);
1978
1979   // Next, add all of the operands to the PHI.
1980   if (I.getNumOperands() == 2) {
1981     Constant *C = cast<Constant>(I.getOperand(1));
1982     for (unsigned i = 0; i != NumPHIValues; ++i) {
1983       Value *InV = 0;
1984       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1985         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1986           InV = Context->getConstantExprCompare(CI->getPredicate(), InC, C);
1987         else
1988           InV = Context->getConstantExpr(I.getOpcode(), InC, C);
1989       } else {
1990         assert(PN->getIncomingBlock(i) == NonConstBB);
1991         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1992           InV = BinaryOperator::Create(BO->getOpcode(),
1993                                        PN->getIncomingValue(i), C, "phitmp",
1994                                        NonConstBB->getTerminator());
1995         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1996           InV = CmpInst::Create(*Context, CI->getOpcode(), 
1997                                 CI->getPredicate(),
1998                                 PN->getIncomingValue(i), C, "phitmp",
1999                                 NonConstBB->getTerminator());
2000         else
2001           llvm_unreachable("Unknown binop!");
2002         
2003         AddToWorkList(cast<Instruction>(InV));
2004       }
2005       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2006     }
2007   } else { 
2008     CastInst *CI = cast<CastInst>(&I);
2009     const Type *RetTy = CI->getType();
2010     for (unsigned i = 0; i != NumPHIValues; ++i) {
2011       Value *InV;
2012       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2013         InV = Context->getConstantExprCast(CI->getOpcode(), InC, RetTy);
2014       } else {
2015         assert(PN->getIncomingBlock(i) == NonConstBB);
2016         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2017                                I.getType(), "phitmp", 
2018                                NonConstBB->getTerminator());
2019         AddToWorkList(cast<Instruction>(InV));
2020       }
2021       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2022     }
2023   }
2024   return ReplaceInstUsesWith(I, NewPN);
2025 }
2026
2027
2028 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2029 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2030 /// This basically requires proving that the add in the original type would not
2031 /// overflow to change the sign bit or have a carry out.
2032 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2033   // There are different heuristics we can use for this.  Here are some simple
2034   // ones.
2035   
2036   // Add has the property that adding any two 2's complement numbers can only 
2037   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2038   // have at least two sign bits, we know that the addition of the two values will
2039   // sign extend fine.
2040   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2041     return true;
2042   
2043   
2044   // If one of the operands only has one non-zero bit, and if the other operand
2045   // has a known-zero bit in a more significant place than it (not including the
2046   // sign bit) the ripple may go up to and fill the zero, but won't change the
2047   // sign.  For example, (X & ~4) + 1.
2048   
2049   // TODO: Implement.
2050   
2051   return false;
2052 }
2053
2054
2055 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2056   bool Changed = SimplifyCommutative(I);
2057   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2058
2059   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2060     // X + undef -> undef
2061     if (isa<UndefValue>(RHS))
2062       return ReplaceInstUsesWith(I, RHS);
2063
2064     // X + 0 --> X
2065     if (RHSC->isNullValue())
2066       return ReplaceInstUsesWith(I, LHS);
2067
2068     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2069       // X + (signbit) --> X ^ signbit
2070       const APInt& Val = CI->getValue();
2071       uint32_t BitWidth = Val.getBitWidth();
2072       if (Val == APInt::getSignBit(BitWidth))
2073         return BinaryOperator::CreateXor(LHS, RHS);
2074       
2075       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2076       // (X & 254)+1 -> (X&254)|1
2077       if (SimplifyDemandedInstructionBits(I))
2078         return &I;
2079
2080       // zext(bool) + C -> bool ? C + 1 : C
2081       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2082         if (ZI->getSrcTy() == Type::Int1Ty)
2083           return SelectInst::Create(ZI->getOperand(0), AddOne(CI, Context), CI);
2084     }
2085
2086     if (isa<PHINode>(LHS))
2087       if (Instruction *NV = FoldOpIntoPhi(I))
2088         return NV;
2089     
2090     ConstantInt *XorRHS = 0;
2091     Value *XorLHS = 0;
2092     if (isa<ConstantInt>(RHSC) &&
2093         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)), *Context)) {
2094       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2095       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2096       
2097       uint32_t Size = TySizeBits / 2;
2098       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2099       APInt CFF80Val(-C0080Val);
2100       do {
2101         if (TySizeBits > Size) {
2102           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2103           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2104           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2105               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2106             // This is a sign extend if the top bits are known zero.
2107             if (!MaskedValueIsZero(XorLHS, 
2108                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2109               Size = 0;  // Not a sign ext, but can't be any others either.
2110             break;
2111           }
2112         }
2113         Size >>= 1;
2114         C0080Val = APIntOps::lshr(C0080Val, Size);
2115         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2116       } while (Size >= 1);
2117       
2118       // FIXME: This shouldn't be necessary. When the backends can handle types
2119       // with funny bit widths then this switch statement should be removed. It
2120       // is just here to get the size of the "middle" type back up to something
2121       // that the back ends can handle.
2122       const Type *MiddleType = 0;
2123       switch (Size) {
2124         default: break;
2125         case 32: MiddleType = Type::Int32Ty; break;
2126         case 16: MiddleType = Type::Int16Ty; break;
2127         case  8: MiddleType = Type::Int8Ty; break;
2128       }
2129       if (MiddleType) {
2130         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2131         InsertNewInstBefore(NewTrunc, I);
2132         return new SExtInst(NewTrunc, I.getType(), I.getName());
2133       }
2134     }
2135   }
2136
2137   if (I.getType() == Type::Int1Ty)
2138     return BinaryOperator::CreateXor(LHS, RHS);
2139
2140   // X + X --> X << 1
2141   if (I.getType()->isInteger()) {
2142     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2143       return Result;
2144
2145     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2146       if (RHSI->getOpcode() == Instruction::Sub)
2147         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2148           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2149     }
2150     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2151       if (LHSI->getOpcode() == Instruction::Sub)
2152         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2153           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2154     }
2155   }
2156
2157   // -A + B  -->  B - A
2158   // -A + -B  -->  -(A + B)
2159   if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
2160     if (LHS->getType()->isIntOrIntVector()) {
2161       if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
2162         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2163         InsertNewInstBefore(NewAdd, I);
2164         return BinaryOperator::CreateNeg(*Context, NewAdd);
2165       }
2166     }
2167     
2168     return BinaryOperator::CreateSub(RHS, LHSV);
2169   }
2170
2171   // A + -B  -->  A - B
2172   if (!isa<Constant>(RHS))
2173     if (Value *V = dyn_castNegVal(RHS, Context))
2174       return BinaryOperator::CreateSub(LHS, V);
2175
2176
2177   ConstantInt *C2;
2178   if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
2179     if (X == RHS)   // X*C + X --> X * (C+1)
2180       return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
2181
2182     // X*C1 + X*C2 --> X * (C1+C2)
2183     ConstantInt *C1;
2184     if (X == dyn_castFoldableMul(RHS, C1, Context))
2185       return BinaryOperator::CreateMul(X, Context->getConstantExprAdd(C1, C2));
2186   }
2187
2188   // X + X*C --> X * (C+1)
2189   if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2190     return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
2191
2192   // X + ~X --> -1   since   ~X = -X-1
2193   if (dyn_castNotVal(LHS, Context) == RHS ||
2194       dyn_castNotVal(RHS, Context) == LHS)
2195     return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
2196   
2197
2198   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2199   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)), *Context))
2200     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
2201       return R;
2202   
2203   // A+B --> A|B iff A and B have no bits set in common.
2204   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2205     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2206     APInt LHSKnownOne(IT->getBitWidth(), 0);
2207     APInt LHSKnownZero(IT->getBitWidth(), 0);
2208     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2209     if (LHSKnownZero != 0) {
2210       APInt RHSKnownOne(IT->getBitWidth(), 0);
2211       APInt RHSKnownZero(IT->getBitWidth(), 0);
2212       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2213       
2214       // No bits in common -> bitwise or.
2215       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2216         return BinaryOperator::CreateOr(LHS, RHS);
2217     }
2218   }
2219
2220   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2221   if (I.getType()->isIntOrIntVector()) {
2222     Value *W, *X, *Y, *Z;
2223     if (match(LHS, m_Mul(m_Value(W), m_Value(X)), *Context) &&
2224         match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
2225       if (W != Y) {
2226         if (W == Z) {
2227           std::swap(Y, Z);
2228         } else if (Y == X) {
2229           std::swap(W, X);
2230         } else if (X == Z) {
2231           std::swap(Y, Z);
2232           std::swap(W, X);
2233         }
2234       }
2235
2236       if (W == Y) {
2237         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2238                                                             LHS->getName()), I);
2239         return BinaryOperator::CreateMul(W, NewAdd);
2240       }
2241     }
2242   }
2243
2244   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2245     Value *X = 0;
2246     if (match(LHS, m_Not(m_Value(X)), *Context))    // ~X + C --> (C-1) - X
2247       return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
2248
2249     // (X & FF00) + xx00  -> (X+xx00) & FF00
2250     if (LHS->hasOneUse() &&
2251         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
2252       Constant *Anded = Context->getConstantExprAnd(CRHS, C2);
2253       if (Anded == CRHS) {
2254         // See if all bits from the first bit set in the Add RHS up are included
2255         // in the mask.  First, get the rightmost bit.
2256         const APInt& AddRHSV = CRHS->getValue();
2257
2258         // Form a mask of all bits from the lowest bit added through the top.
2259         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2260
2261         // See if the and mask includes all of these bits.
2262         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2263
2264         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2265           // Okay, the xform is safe.  Insert the new add pronto.
2266           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2267                                                             LHS->getName()), I);
2268           return BinaryOperator::CreateAnd(NewAdd, C2);
2269         }
2270       }
2271     }
2272
2273     // Try to fold constant add into select arguments.
2274     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2275       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2276         return R;
2277   }
2278
2279   // add (select X 0 (sub n A)) A  -->  select X A n
2280   {
2281     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2282     Value *A = RHS;
2283     if (!SI) {
2284       SI = dyn_cast<SelectInst>(RHS);
2285       A = LHS;
2286     }
2287     if (SI && SI->hasOneUse()) {
2288       Value *TV = SI->getTrueValue();
2289       Value *FV = SI->getFalseValue();
2290       Value *N;
2291
2292       // Can we fold the add into the argument of the select?
2293       // We check both true and false select arguments for a matching subtract.
2294       if (match(FV, m_Zero(), *Context) &&
2295           match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2296         // Fold the add into the true select value.
2297         return SelectInst::Create(SI->getCondition(), N, A);
2298       if (match(TV, m_Zero(), *Context) &&
2299           match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2300         // Fold the add into the false select value.
2301         return SelectInst::Create(SI->getCondition(), A, N);
2302     }
2303   }
2304
2305   // Check for (add (sext x), y), see if we can merge this into an
2306   // integer add followed by a sext.
2307   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2308     // (add (sext x), cst) --> (sext (add x, cst'))
2309     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2310       Constant *CI = 
2311         Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
2312       if (LHSConv->hasOneUse() &&
2313           Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
2314           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2315         // Insert the new, smaller add.
2316         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2317                                                         CI, "addconv");
2318         InsertNewInstBefore(NewAdd, I);
2319         return new SExtInst(NewAdd, I.getType());
2320       }
2321     }
2322     
2323     // (add (sext x), (sext y)) --> (sext (add int x, y))
2324     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2325       // Only do this if x/y have the same type, if at last one of them has a
2326       // single use (so we don't increase the number of sexts), and if the
2327       // integer add will not overflow.
2328       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2329           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2330           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2331                                    RHSConv->getOperand(0))) {
2332         // Insert the new integer add.
2333         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2334                                                         RHSConv->getOperand(0),
2335                                                         "addconv");
2336         InsertNewInstBefore(NewAdd, I);
2337         return new SExtInst(NewAdd, I.getType());
2338       }
2339     }
2340   }
2341
2342   return Changed ? &I : 0;
2343 }
2344
2345 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2346   bool Changed = SimplifyCommutative(I);
2347   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2348
2349   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2350     // X + 0 --> X
2351     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2352       if (CFP->isExactlyValue(Context->getConstantFPNegativeZero
2353                               (I.getType())->getValueAPF()))
2354         return ReplaceInstUsesWith(I, LHS);
2355     }
2356
2357     if (isa<PHINode>(LHS))
2358       if (Instruction *NV = FoldOpIntoPhi(I))
2359         return NV;
2360   }
2361
2362   // -A + B  -->  B - A
2363   // -A + -B  -->  -(A + B)
2364   if (Value *LHSV = dyn_castFNegVal(LHS, Context))
2365     return BinaryOperator::CreateFSub(RHS, LHSV);
2366
2367   // A + -B  -->  A - B
2368   if (!isa<Constant>(RHS))
2369     if (Value *V = dyn_castFNegVal(RHS, Context))
2370       return BinaryOperator::CreateFSub(LHS, V);
2371
2372   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2373   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2374     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2375       return ReplaceInstUsesWith(I, LHS);
2376
2377   // Check for (add double (sitofp x), y), see if we can merge this into an
2378   // integer add followed by a promotion.
2379   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2380     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2381     // ... if the constant fits in the integer value.  This is useful for things
2382     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2383     // requires a constant pool load, and generally allows the add to be better
2384     // instcombined.
2385     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2386       Constant *CI = 
2387       Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
2388       if (LHSConv->hasOneUse() &&
2389           Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
2390           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2391         // Insert the new integer add.
2392         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2393                                                         CI, "addconv");
2394         InsertNewInstBefore(NewAdd, I);
2395         return new SIToFPInst(NewAdd, I.getType());
2396       }
2397     }
2398     
2399     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2400     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2401       // Only do this if x/y have the same type, if at last one of them has a
2402       // single use (so we don't increase the number of int->fp conversions),
2403       // and if the integer add will not overflow.
2404       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2405           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2406           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2407                                    RHSConv->getOperand(0))) {
2408         // Insert the new integer add.
2409         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2410                                                         RHSConv->getOperand(0),
2411                                                         "addconv");
2412         InsertNewInstBefore(NewAdd, I);
2413         return new SIToFPInst(NewAdd, I.getType());
2414       }
2415     }
2416   }
2417   
2418   return Changed ? &I : 0;
2419 }
2420
2421 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2422   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2423
2424   if (Op0 == Op1)                        // sub X, X  -> 0
2425     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2426
2427   // If this is a 'B = x-(-A)', change to B = x+A...
2428   if (Value *V = dyn_castNegVal(Op1, Context))
2429     return BinaryOperator::CreateAdd(Op0, V);
2430
2431   if (isa<UndefValue>(Op0))
2432     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2433   if (isa<UndefValue>(Op1))
2434     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2435
2436   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2437     // Replace (-1 - A) with (~A)...
2438     if (C->isAllOnesValue())
2439       return BinaryOperator::CreateNot(*Context, Op1);
2440
2441     // C - ~X == X + (1+C)
2442     Value *X = 0;
2443     if (match(Op1, m_Not(m_Value(X)), *Context))
2444       return BinaryOperator::CreateAdd(X, AddOne(C, Context));
2445
2446     // -(X >>u 31) -> (X >>s 31)
2447     // -(X >>s 31) -> (X >>u 31)
2448     if (C->isZero()) {
2449       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2450         if (SI->getOpcode() == Instruction::LShr) {
2451           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2452             // Check to see if we are shifting out everything but the sign bit.
2453             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2454                 SI->getType()->getPrimitiveSizeInBits()-1) {
2455               // Ok, the transformation is safe.  Insert AShr.
2456               return BinaryOperator::Create(Instruction::AShr, 
2457                                           SI->getOperand(0), CU, SI->getName());
2458             }
2459           }
2460         }
2461         else if (SI->getOpcode() == Instruction::AShr) {
2462           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2463             // Check to see if we are shifting out everything but the sign bit.
2464             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2465                 SI->getType()->getPrimitiveSizeInBits()-1) {
2466               // Ok, the transformation is safe.  Insert LShr. 
2467               return BinaryOperator::CreateLShr(
2468                                           SI->getOperand(0), CU, SI->getName());
2469             }
2470           }
2471         }
2472       }
2473     }
2474
2475     // Try to fold constant sub into select arguments.
2476     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2477       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2478         return R;
2479
2480     // C - zext(bool) -> bool ? C - 1 : C
2481     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2482       if (ZI->getSrcTy() == Type::Int1Ty)
2483         return SelectInst::Create(ZI->getOperand(0), SubOne(C, Context), C);
2484   }
2485
2486   if (I.getType() == Type::Int1Ty)
2487     return BinaryOperator::CreateXor(Op0, Op1);
2488
2489   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2490     if (Op1I->getOpcode() == Instruction::Add) {
2491       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2492         return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(1),
2493                                          I.getName());
2494       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2495         return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(0), 
2496                                          I.getName());
2497       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2498         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2499           // C1-(X+C2) --> (C1-C2)-X
2500           return BinaryOperator::CreateSub(
2501             Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
2502       }
2503     }
2504
2505     if (Op1I->hasOneUse()) {
2506       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2507       // is not used by anyone else...
2508       //
2509       if (Op1I->getOpcode() == Instruction::Sub) {
2510         // Swap the two operands of the subexpr...
2511         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2512         Op1I->setOperand(0, IIOp1);
2513         Op1I->setOperand(1, IIOp0);
2514
2515         // Create the new top level add instruction...
2516         return BinaryOperator::CreateAdd(Op0, Op1);
2517       }
2518
2519       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2520       //
2521       if (Op1I->getOpcode() == Instruction::And &&
2522           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2523         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2524
2525         Value *NewNot =
2526           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, 
2527                                                         OtherOp, "B.not"), I);
2528         return BinaryOperator::CreateAnd(Op0, NewNot);
2529       }
2530
2531       // 0 - (X sdiv C)  -> (X sdiv -C)
2532       if (Op1I->getOpcode() == Instruction::SDiv)
2533         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2534           if (CSI->isZero())
2535             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2536               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2537                                           Context->getConstantExprNeg(DivRHS));
2538
2539       // X - X*C --> X * (1-C)
2540       ConstantInt *C2 = 0;
2541       if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2542         Constant *CP1 = 
2543           Context->getConstantExprSub(Context->getConstantInt(I.getType(), 1),
2544                                              C2);
2545         return BinaryOperator::CreateMul(Op0, CP1);
2546       }
2547     }
2548   }
2549
2550   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2551     if (Op0I->getOpcode() == Instruction::Add) {
2552       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2553         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2554       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2555         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2556     } else if (Op0I->getOpcode() == Instruction::Sub) {
2557       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2558         return BinaryOperator::CreateNeg(*Context, Op0I->getOperand(1),
2559                                          I.getName());
2560     }
2561   }
2562
2563   ConstantInt *C1;
2564   if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
2565     if (X == Op1)  // X*C - X --> X * (C-1)
2566       return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
2567
2568     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2569     if (X == dyn_castFoldableMul(Op1, C2, Context))
2570       return BinaryOperator::CreateMul(X, Context->getConstantExprSub(C1, C2));
2571   }
2572   return 0;
2573 }
2574
2575 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2576   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2577
2578   // If this is a 'B = x-(-A)', change to B = x+A...
2579   if (Value *V = dyn_castFNegVal(Op1, Context))
2580     return BinaryOperator::CreateFAdd(Op0, V);
2581
2582   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2583     if (Op1I->getOpcode() == Instruction::FAdd) {
2584       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2585         return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(1),
2586                                           I.getName());
2587       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2588         return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(0),
2589                                           I.getName());
2590     }
2591   }
2592
2593   return 0;
2594 }
2595
2596 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2597 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2598 /// TrueIfSigned if the result of the comparison is true when the input value is
2599 /// signed.
2600 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2601                            bool &TrueIfSigned) {
2602   switch (pred) {
2603   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2604     TrueIfSigned = true;
2605     return RHS->isZero();
2606   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2607     TrueIfSigned = true;
2608     return RHS->isAllOnesValue();
2609   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2610     TrueIfSigned = false;
2611     return RHS->isAllOnesValue();
2612   case ICmpInst::ICMP_UGT:
2613     // True if LHS u> RHS and RHS == high-bit-mask - 1
2614     TrueIfSigned = true;
2615     return RHS->getValue() ==
2616       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2617   case ICmpInst::ICMP_UGE: 
2618     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2619     TrueIfSigned = true;
2620     return RHS->getValue().isSignBit();
2621   default:
2622     return false;
2623   }
2624 }
2625
2626 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2627   bool Changed = SimplifyCommutative(I);
2628   Value *Op0 = I.getOperand(0);
2629
2630   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2631     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2632
2633   // Simplify mul instructions with a constant RHS...
2634   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2635     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2636
2637       // ((X << C1)*C2) == (X * (C2 << C1))
2638       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2639         if (SI->getOpcode() == Instruction::Shl)
2640           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2641             return BinaryOperator::CreateMul(SI->getOperand(0),
2642                                         Context->getConstantExprShl(CI, ShOp));
2643
2644       if (CI->isZero())
2645         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2646       if (CI->equalsInt(1))                  // X * 1  == X
2647         return ReplaceInstUsesWith(I, Op0);
2648       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2649         return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2650
2651       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2652       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2653         return BinaryOperator::CreateShl(Op0,
2654                  Context->getConstantInt(Op0->getType(), Val.logBase2()));
2655       }
2656     } else if (isa<VectorType>(Op1->getType())) {
2657       if (Op1->isNullValue())
2658         return ReplaceInstUsesWith(I, Op1);
2659
2660       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2661         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2662           return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2663
2664         // As above, vector X*splat(1.0) -> X in all defined cases.
2665         if (Constant *Splat = Op1V->getSplatValue()) {
2666           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2667             if (CI->equalsInt(1))
2668               return ReplaceInstUsesWith(I, Op0);
2669         }
2670       }
2671     }
2672     
2673     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2674       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2675           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2676         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2677         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2678                                                      Op1, "tmp");
2679         InsertNewInstBefore(Add, I);
2680         Value *C1C2 = Context->getConstantExprMul(Op1, 
2681                                            cast<Constant>(Op0I->getOperand(1)));
2682         return BinaryOperator::CreateAdd(Add, C1C2);
2683         
2684       }
2685
2686     // Try to fold constant mul into select arguments.
2687     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2688       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2689         return R;
2690
2691     if (isa<PHINode>(Op0))
2692       if (Instruction *NV = FoldOpIntoPhi(I))
2693         return NV;
2694   }
2695
2696   if (Value *Op0v = dyn_castNegVal(Op0, Context))     // -X * -Y = X*Y
2697     if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
2698       return BinaryOperator::CreateMul(Op0v, Op1v);
2699
2700   // (X / Y) *  Y = X - (X % Y)
2701   // (X / Y) * -Y = (X % Y) - X
2702   {
2703     Value *Op1 = I.getOperand(1);
2704     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2705     if (!BO ||
2706         (BO->getOpcode() != Instruction::UDiv && 
2707          BO->getOpcode() != Instruction::SDiv)) {
2708       Op1 = Op0;
2709       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2710     }
2711     Value *Neg = dyn_castNegVal(Op1, Context);
2712     if (BO && BO->hasOneUse() &&
2713         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2714         (BO->getOpcode() == Instruction::UDiv ||
2715          BO->getOpcode() == Instruction::SDiv)) {
2716       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2717
2718       Instruction *Rem;
2719       if (BO->getOpcode() == Instruction::UDiv)
2720         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2721       else
2722         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2723
2724       InsertNewInstBefore(Rem, I);
2725       Rem->takeName(BO);
2726
2727       if (Op1BO == Op1)
2728         return BinaryOperator::CreateSub(Op0BO, Rem);
2729       else
2730         return BinaryOperator::CreateSub(Rem, Op0BO);
2731     }
2732   }
2733
2734   if (I.getType() == Type::Int1Ty)
2735     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2736
2737   // If one of the operands of the multiply is a cast from a boolean value, then
2738   // we know the bool is either zero or one, so this is a 'masking' multiply.
2739   // See if we can simplify things based on how the boolean was originally
2740   // formed.
2741   CastInst *BoolCast = 0;
2742   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2743     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2744       BoolCast = CI;
2745   if (!BoolCast)
2746     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2747       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2748         BoolCast = CI;
2749   if (BoolCast) {
2750     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2751       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2752       const Type *SCOpTy = SCIOp0->getType();
2753       bool TIS = false;
2754       
2755       // If the icmp is true iff the sign bit of X is set, then convert this
2756       // multiply into a shift/and combination.
2757       if (isa<ConstantInt>(SCIOp1) &&
2758           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2759           TIS) {
2760         // Shift the X value right to turn it into "all signbits".
2761         Constant *Amt = Context->getConstantInt(SCIOp0->getType(),
2762                                           SCOpTy->getPrimitiveSizeInBits()-1);
2763         Value *V =
2764           InsertNewInstBefore(
2765             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2766                                             BoolCast->getOperand(0)->getName()+
2767                                             ".mask"), I);
2768
2769         // If the multiply type is not the same as the source type, sign extend
2770         // or truncate to the multiply type.
2771         if (I.getType() != V->getType()) {
2772           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2773           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2774           Instruction::CastOps opcode = 
2775             (SrcBits == DstBits ? Instruction::BitCast : 
2776              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2777           V = InsertCastBefore(opcode, V, I.getType(), I);
2778         }
2779
2780         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2781         return BinaryOperator::CreateAnd(V, OtherOp);
2782       }
2783     }
2784   }
2785
2786   return Changed ? &I : 0;
2787 }
2788
2789 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2790   bool Changed = SimplifyCommutative(I);
2791   Value *Op0 = I.getOperand(0);
2792
2793   // Simplify mul instructions with a constant RHS...
2794   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2795     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2796       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2797       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2798       if (Op1F->isExactlyValue(1.0))
2799         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2800     } else if (isa<VectorType>(Op1->getType())) {
2801       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2802         // As above, vector X*splat(1.0) -> X in all defined cases.
2803         if (Constant *Splat = Op1V->getSplatValue()) {
2804           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2805             if (F->isExactlyValue(1.0))
2806               return ReplaceInstUsesWith(I, Op0);
2807         }
2808       }
2809     }
2810
2811     // Try to fold constant mul into select arguments.
2812     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2813       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2814         return R;
2815
2816     if (isa<PHINode>(Op0))
2817       if (Instruction *NV = FoldOpIntoPhi(I))
2818         return NV;
2819   }
2820
2821   if (Value *Op0v = dyn_castFNegVal(Op0, Context))     // -X * -Y = X*Y
2822     if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
2823       return BinaryOperator::CreateFMul(Op0v, Op1v);
2824
2825   return Changed ? &I : 0;
2826 }
2827
2828 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2829 /// instruction.
2830 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2831   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2832   
2833   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2834   int NonNullOperand = -1;
2835   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2836     if (ST->isNullValue())
2837       NonNullOperand = 2;
2838   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2839   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2840     if (ST->isNullValue())
2841       NonNullOperand = 1;
2842   
2843   if (NonNullOperand == -1)
2844     return false;
2845   
2846   Value *SelectCond = SI->getOperand(0);
2847   
2848   // Change the div/rem to use 'Y' instead of the select.
2849   I.setOperand(1, SI->getOperand(NonNullOperand));
2850   
2851   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2852   // problem.  However, the select, or the condition of the select may have
2853   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2854   // propagate the known value for the select into other uses of it, and
2855   // propagate a known value of the condition into its other users.
2856   
2857   // If the select and condition only have a single use, don't bother with this,
2858   // early exit.
2859   if (SI->use_empty() && SelectCond->hasOneUse())
2860     return true;
2861   
2862   // Scan the current block backward, looking for other uses of SI.
2863   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2864   
2865   while (BBI != BBFront) {
2866     --BBI;
2867     // If we found a call to a function, we can't assume it will return, so
2868     // information from below it cannot be propagated above it.
2869     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2870       break;
2871     
2872     // Replace uses of the select or its condition with the known values.
2873     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2874          I != E; ++I) {
2875       if (*I == SI) {
2876         *I = SI->getOperand(NonNullOperand);
2877         AddToWorkList(BBI);
2878       } else if (*I == SelectCond) {
2879         *I = NonNullOperand == 1 ? Context->getTrue() :
2880                                    Context->getFalse();
2881         AddToWorkList(BBI);
2882       }
2883     }
2884     
2885     // If we past the instruction, quit looking for it.
2886     if (&*BBI == SI)
2887       SI = 0;
2888     if (&*BBI == SelectCond)
2889       SelectCond = 0;
2890     
2891     // If we ran out of things to eliminate, break out of the loop.
2892     if (SelectCond == 0 && SI == 0)
2893       break;
2894     
2895   }
2896   return true;
2897 }
2898
2899
2900 /// This function implements the transforms on div instructions that work
2901 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2902 /// used by the visitors to those instructions.
2903 /// @brief Transforms common to all three div instructions
2904 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2905   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2906
2907   // undef / X -> 0        for integer.
2908   // undef / X -> undef    for FP (the undef could be a snan).
2909   if (isa<UndefValue>(Op0)) {
2910     if (Op0->getType()->isFPOrFPVector())
2911       return ReplaceInstUsesWith(I, Op0);
2912     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2913   }
2914
2915   // X / undef -> undef
2916   if (isa<UndefValue>(Op1))
2917     return ReplaceInstUsesWith(I, Op1);
2918
2919   return 0;
2920 }
2921
2922 /// This function implements the transforms common to both integer division
2923 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2924 /// division instructions.
2925 /// @brief Common integer divide transforms
2926 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2927   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2928
2929   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2930   if (Op0 == Op1) {
2931     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2932       Constant *CI = Context->getConstantInt(Ty->getElementType(), 1);
2933       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2934       return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
2935     }
2936
2937     Constant *CI = Context->getConstantInt(I.getType(), 1);
2938     return ReplaceInstUsesWith(I, CI);
2939   }
2940   
2941   if (Instruction *Common = commonDivTransforms(I))
2942     return Common;
2943   
2944   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2945   // This does not apply for fdiv.
2946   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2947     return &I;
2948
2949   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2950     // div X, 1 == X
2951     if (RHS->equalsInt(1))
2952       return ReplaceInstUsesWith(I, Op0);
2953
2954     // (X / C1) / C2  -> X / (C1*C2)
2955     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2956       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2957         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2958           if (MultiplyOverflows(RHS, LHSRHS,
2959                                 I.getOpcode()==Instruction::SDiv, Context))
2960             return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2961           else 
2962             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2963                                       Context->getConstantExprMul(RHS, LHSRHS));
2964         }
2965
2966     if (!RHS->isZero()) { // avoid X udiv 0
2967       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2968         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2969           return R;
2970       if (isa<PHINode>(Op0))
2971         if (Instruction *NV = FoldOpIntoPhi(I))
2972           return NV;
2973     }
2974   }
2975
2976   // 0 / X == 0, we don't need to preserve faults!
2977   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2978     if (LHS->equalsInt(0))
2979       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2980
2981   // It can't be division by zero, hence it must be division by one.
2982   if (I.getType() == Type::Int1Ty)
2983     return ReplaceInstUsesWith(I, Op0);
2984
2985   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2986     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2987       // div X, 1 == X
2988       if (X->isOne())
2989         return ReplaceInstUsesWith(I, Op0);
2990   }
2991
2992   return 0;
2993 }
2994
2995 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2996   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2997
2998   // Handle the integer div common cases
2999   if (Instruction *Common = commonIDivTransforms(I))
3000     return Common;
3001
3002   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3003     // X udiv C^2 -> X >> C
3004     // Check to see if this is an unsigned division with an exact power of 2,
3005     // if so, convert to a right shift.
3006     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3007       return BinaryOperator::CreateLShr(Op0, 
3008             Context->getConstantInt(Op0->getType(), C->getValue().logBase2()));
3009
3010     // X udiv C, where C >= signbit
3011     if (C->getValue().isNegative()) {
3012       Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3013                                                     ICmpInst::ICMP_ULT, Op0, C),
3014                                       I);
3015       return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3016                                 Context->getConstantInt(I.getType(), 1));
3017     }
3018   }
3019
3020   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3021   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3022     if (RHSI->getOpcode() == Instruction::Shl &&
3023         isa<ConstantInt>(RHSI->getOperand(0))) {
3024       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3025       if (C1.isPowerOf2()) {
3026         Value *N = RHSI->getOperand(1);
3027         const Type *NTy = N->getType();
3028         if (uint32_t C2 = C1.logBase2()) {
3029           Constant *C2V = Context->getConstantInt(NTy, C2);
3030           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3031         }
3032         return BinaryOperator::CreateLShr(Op0, N);
3033       }
3034     }
3035   }
3036   
3037   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3038   // where C1&C2 are powers of two.
3039   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3040     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3041       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3042         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3043         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3044           // Compute the shift amounts
3045           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3046           // Construct the "on true" case of the select
3047           Constant *TC = Context->getConstantInt(Op0->getType(), TSA);
3048           Instruction *TSI = BinaryOperator::CreateLShr(
3049                                                  Op0, TC, SI->getName()+".t");
3050           TSI = InsertNewInstBefore(TSI, I);
3051   
3052           // Construct the "on false" case of the select
3053           Constant *FC = Context->getConstantInt(Op0->getType(), FSA); 
3054           Instruction *FSI = BinaryOperator::CreateLShr(
3055                                                  Op0, FC, SI->getName()+".f");
3056           FSI = InsertNewInstBefore(FSI, I);
3057
3058           // construct the select instruction and return it.
3059           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3060         }
3061       }
3062   return 0;
3063 }
3064
3065 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3066   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3067
3068   // Handle the integer div common cases
3069   if (Instruction *Common = commonIDivTransforms(I))
3070     return Common;
3071
3072   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3073     // sdiv X, -1 == -X
3074     if (RHS->isAllOnesValue())
3075       return BinaryOperator::CreateNeg(*Context, Op0);
3076   }
3077
3078   // If the sign bits of both operands are zero (i.e. we can prove they are
3079   // unsigned inputs), turn this into a udiv.
3080   if (I.getType()->isInteger()) {
3081     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3082     if (MaskedValueIsZero(Op0, Mask)) {
3083       if (MaskedValueIsZero(Op1, Mask)) {
3084         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3085         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3086       }
3087       ConstantInt *ShiftedInt;
3088       if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value()), *Context) &&
3089           ShiftedInt->getValue().isPowerOf2()) {
3090         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3091         // Safe because the only negative value (1 << Y) can take on is
3092         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3093         // the sign bit set.
3094         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3095       }
3096     }
3097   }
3098   
3099   return 0;
3100 }
3101
3102 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3103   return commonDivTransforms(I);
3104 }
3105
3106 /// This function implements the transforms on rem instructions that work
3107 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3108 /// is used by the visitors to those instructions.
3109 /// @brief Transforms common to all three rem instructions
3110 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3111   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3112
3113   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3114     if (I.getType()->isFPOrFPVector())
3115       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3116     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3117   }
3118   if (isa<UndefValue>(Op1))
3119     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3120
3121   // Handle cases involving: rem X, (select Cond, Y, Z)
3122   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3123     return &I;
3124
3125   return 0;
3126 }
3127
3128 /// This function implements the transforms common to both integer remainder
3129 /// instructions (urem and srem). It is called by the visitors to those integer
3130 /// remainder instructions.
3131 /// @brief Common integer remainder transforms
3132 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3133   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3134
3135   if (Instruction *common = commonRemTransforms(I))
3136     return common;
3137
3138   // 0 % X == 0 for integer, we don't need to preserve faults!
3139   if (Constant *LHS = dyn_cast<Constant>(Op0))
3140     if (LHS->isNullValue())
3141       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3142
3143   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3144     // X % 0 == undef, we don't need to preserve faults!
3145     if (RHS->equalsInt(0))
3146       return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
3147     
3148     if (RHS->equalsInt(1))  // X % 1 == 0
3149       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3150
3151     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3152       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3153         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3154           return R;
3155       } else if (isa<PHINode>(Op0I)) {
3156         if (Instruction *NV = FoldOpIntoPhi(I))
3157           return NV;
3158       }
3159
3160       // See if we can fold away this rem instruction.
3161       if (SimplifyDemandedInstructionBits(I))
3162         return &I;
3163     }
3164   }
3165
3166   return 0;
3167 }
3168
3169 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3170   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3171
3172   if (Instruction *common = commonIRemTransforms(I))
3173     return common;
3174   
3175   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3176     // X urem C^2 -> X and C
3177     // Check to see if this is an unsigned remainder with an exact power of 2,
3178     // if so, convert to a bitwise and.
3179     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3180       if (C->getValue().isPowerOf2())
3181         return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
3182   }
3183
3184   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3185     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3186     if (RHSI->getOpcode() == Instruction::Shl &&
3187         isa<ConstantInt>(RHSI->getOperand(0))) {
3188       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3189         Constant *N1 = Context->getAllOnesValue(I.getType());
3190         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3191                                                                    "tmp"), I);
3192         return BinaryOperator::CreateAnd(Op0, Add);
3193       }
3194     }
3195   }
3196
3197   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3198   // where C1&C2 are powers of two.
3199   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3200     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3201       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3202         // STO == 0 and SFO == 0 handled above.
3203         if ((STO->getValue().isPowerOf2()) && 
3204             (SFO->getValue().isPowerOf2())) {
3205           Value *TrueAnd = InsertNewInstBefore(
3206             BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3207                                       SI->getName()+".t"), I);
3208           Value *FalseAnd = InsertNewInstBefore(
3209             BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3210                                       SI->getName()+".f"), I);
3211           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3212         }
3213       }
3214   }
3215   
3216   return 0;
3217 }
3218
3219 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3220   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3221
3222   // Handle the integer rem common cases
3223   if (Instruction *common = commonIRemTransforms(I))
3224     return common;
3225   
3226   if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
3227     if (!isa<Constant>(RHSNeg) ||
3228         (isa<ConstantInt>(RHSNeg) &&
3229          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3230       // X % -Y -> X % Y
3231       AddUsesToWorkList(I);
3232       I.setOperand(1, RHSNeg);
3233       return &I;
3234     }
3235
3236   // If the sign bits of both operands are zero (i.e. we can prove they are
3237   // unsigned inputs), turn this into a urem.
3238   if (I.getType()->isInteger()) {
3239     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3240     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3241       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3242       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3243     }
3244   }
3245
3246   // If it's a constant vector, flip any negative values positive.
3247   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3248     unsigned VWidth = RHSV->getNumOperands();
3249
3250     bool hasNegative = false;
3251     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3252       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3253         if (RHS->getValue().isNegative())
3254           hasNegative = true;
3255
3256     if (hasNegative) {
3257       std::vector<Constant *> Elts(VWidth);
3258       for (unsigned i = 0; i != VWidth; ++i) {
3259         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3260           if (RHS->getValue().isNegative())
3261             Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
3262           else
3263             Elts[i] = RHS;
3264         }
3265       }
3266
3267       Constant *NewRHSV = Context->getConstantVector(Elts);
3268       if (NewRHSV != RHSV) {
3269         AddUsesToWorkList(I);
3270         I.setOperand(1, NewRHSV);
3271         return &I;
3272       }
3273     }
3274   }
3275
3276   return 0;
3277 }
3278
3279 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3280   return commonRemTransforms(I);
3281 }
3282
3283 // isOneBitSet - Return true if there is exactly one bit set in the specified
3284 // constant.
3285 static bool isOneBitSet(const ConstantInt *CI) {
3286   return CI->getValue().isPowerOf2();
3287 }
3288
3289 // isHighOnes - Return true if the constant is of the form 1+0+.
3290 // This is the same as lowones(~X).
3291 static bool isHighOnes(const ConstantInt *CI) {
3292   return (~CI->getValue() + 1).isPowerOf2();
3293 }
3294
3295 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3296 /// are carefully arranged to allow folding of expressions such as:
3297 ///
3298 ///      (A < B) | (A > B) --> (A != B)
3299 ///
3300 /// Note that this is only valid if the first and second predicates have the
3301 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3302 ///
3303 /// Three bits are used to represent the condition, as follows:
3304 ///   0  A > B
3305 ///   1  A == B
3306 ///   2  A < B
3307 ///
3308 /// <=>  Value  Definition
3309 /// 000     0   Always false
3310 /// 001     1   A >  B
3311 /// 010     2   A == B
3312 /// 011     3   A >= B
3313 /// 100     4   A <  B
3314 /// 101     5   A != B
3315 /// 110     6   A <= B
3316 /// 111     7   Always true
3317 ///  
3318 static unsigned getICmpCode(const ICmpInst *ICI) {
3319   switch (ICI->getPredicate()) {
3320     // False -> 0
3321   case ICmpInst::ICMP_UGT: return 1;  // 001
3322   case ICmpInst::ICMP_SGT: return 1;  // 001
3323   case ICmpInst::ICMP_EQ:  return 2;  // 010
3324   case ICmpInst::ICMP_UGE: return 3;  // 011
3325   case ICmpInst::ICMP_SGE: return 3;  // 011
3326   case ICmpInst::ICMP_ULT: return 4;  // 100
3327   case ICmpInst::ICMP_SLT: return 4;  // 100
3328   case ICmpInst::ICMP_NE:  return 5;  // 101
3329   case ICmpInst::ICMP_ULE: return 6;  // 110
3330   case ICmpInst::ICMP_SLE: return 6;  // 110
3331     // True -> 7
3332   default:
3333     llvm_unreachable("Invalid ICmp predicate!");
3334     return 0;
3335   }
3336 }
3337
3338 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3339 /// predicate into a three bit mask. It also returns whether it is an ordered
3340 /// predicate by reference.
3341 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3342   isOrdered = false;
3343   switch (CC) {
3344   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3345   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3346   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3347   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3348   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3349   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3350   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3351   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3352   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3353   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3354   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3355   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3356   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3357   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3358     // True -> 7
3359   default:
3360     // Not expecting FCMP_FALSE and FCMP_TRUE;
3361     llvm_unreachable("Unexpected FCmp predicate!");
3362     return 0;
3363   }
3364 }
3365
3366 /// getICmpValue - This is the complement of getICmpCode, which turns an
3367 /// opcode and two operands into either a constant true or false, or a brand 
3368 /// new ICmp instruction. The sign is passed in to determine which kind
3369 /// of predicate to use in the new icmp instruction.
3370 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3371                            LLVMContext *Context) {
3372   switch (code) {
3373   default: llvm_unreachable("Illegal ICmp code!");
3374   case  0: return Context->getFalse();
3375   case  1: 
3376     if (sign)
3377       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
3378     else
3379       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3380   case  2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ,  LHS, RHS);
3381   case  3: 
3382     if (sign)
3383       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
3384     else
3385       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
3386   case  4: 
3387     if (sign)
3388       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
3389     else
3390       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3391   case  5: return new ICmpInst(*Context, ICmpInst::ICMP_NE,  LHS, RHS);
3392   case  6: 
3393     if (sign)
3394       return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
3395     else
3396       return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
3397   case  7: return Context->getTrue();
3398   }
3399 }
3400
3401 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3402 /// opcode and two operands into either a FCmp instruction. isordered is passed
3403 /// in to determine which kind of predicate to use in the new fcmp instruction.
3404 static Value *getFCmpValue(bool isordered, unsigned code,
3405                            Value *LHS, Value *RHS, LLVMContext *Context) {
3406   switch (code) {
3407   default: llvm_unreachable("Illegal FCmp code!");
3408   case  0:
3409     if (isordered)
3410       return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
3411     else
3412       return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
3413   case  1: 
3414     if (isordered)
3415       return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
3416     else
3417       return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
3418   case  2: 
3419     if (isordered)
3420       return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
3421     else
3422       return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
3423   case  3: 
3424     if (isordered)
3425       return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
3426     else
3427       return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
3428   case  4: 
3429     if (isordered)
3430       return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
3431     else
3432       return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
3433   case  5: 
3434     if (isordered)
3435       return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
3436     else
3437       return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
3438   case  6: 
3439     if (isordered)
3440       return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
3441     else
3442       return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
3443   case  7: return Context->getTrue();
3444   }
3445 }
3446
3447 /// PredicatesFoldable - Return true if both predicates match sign or if at
3448 /// least one of them is an equality comparison (which is signless).
3449 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3450   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3451          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3452          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3453 }
3454
3455 namespace { 
3456 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3457 struct FoldICmpLogical {
3458   InstCombiner &IC;
3459   Value *LHS, *RHS;
3460   ICmpInst::Predicate pred;
3461   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3462     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3463       pred(ICI->getPredicate()) {}
3464   bool shouldApply(Value *V) const {
3465     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3466       if (PredicatesFoldable(pred, ICI->getPredicate()))
3467         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3468                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3469     return false;
3470   }
3471   Instruction *apply(Instruction &Log) const {
3472     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3473     if (ICI->getOperand(0) != LHS) {
3474       assert(ICI->getOperand(1) == LHS);
3475       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3476     }
3477
3478     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3479     unsigned LHSCode = getICmpCode(ICI);
3480     unsigned RHSCode = getICmpCode(RHSICI);
3481     unsigned Code;
3482     switch (Log.getOpcode()) {
3483     case Instruction::And: Code = LHSCode & RHSCode; break;
3484     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3485     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3486     default: llvm_unreachable("Illegal logical opcode!"); return 0;
3487     }
3488
3489     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3490                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3491       
3492     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3493     if (Instruction *I = dyn_cast<Instruction>(RV))
3494       return I;
3495     // Otherwise, it's a constant boolean value...
3496     return IC.ReplaceInstUsesWith(Log, RV);
3497   }
3498 };
3499 } // end anonymous namespace
3500
3501 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3502 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3503 // guaranteed to be a binary operator.
3504 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3505                                     ConstantInt *OpRHS,
3506                                     ConstantInt *AndRHS,
3507                                     BinaryOperator &TheAnd) {
3508   Value *X = Op->getOperand(0);
3509   Constant *Together = 0;
3510   if (!Op->isShift())
3511     Together = Context->getConstantExprAnd(AndRHS, OpRHS);
3512
3513   switch (Op->getOpcode()) {
3514   case Instruction::Xor:
3515     if (Op->hasOneUse()) {
3516       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3517       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3518       InsertNewInstBefore(And, TheAnd);
3519       And->takeName(Op);
3520       return BinaryOperator::CreateXor(And, Together);
3521     }
3522     break;
3523   case Instruction::Or:
3524     if (Together == AndRHS) // (X | C) & C --> C
3525       return ReplaceInstUsesWith(TheAnd, AndRHS);
3526
3527     if (Op->hasOneUse() && Together != OpRHS) {
3528       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3529       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3530       InsertNewInstBefore(Or, TheAnd);
3531       Or->takeName(Op);
3532       return BinaryOperator::CreateAnd(Or, AndRHS);
3533     }
3534     break;
3535   case Instruction::Add:
3536     if (Op->hasOneUse()) {
3537       // Adding a one to a single bit bit-field should be turned into an XOR
3538       // of the bit.  First thing to check is to see if this AND is with a
3539       // single bit constant.
3540       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3541
3542       // If there is only one bit set...
3543       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3544         // Ok, at this point, we know that we are masking the result of the
3545         // ADD down to exactly one bit.  If the constant we are adding has
3546         // no bits set below this bit, then we can eliminate the ADD.
3547         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3548
3549         // Check to see if any bits below the one bit set in AndRHSV are set.
3550         if ((AddRHS & (AndRHSV-1)) == 0) {
3551           // If not, the only thing that can effect the output of the AND is
3552           // the bit specified by AndRHSV.  If that bit is set, the effect of
3553           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3554           // no effect.
3555           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3556             TheAnd.setOperand(0, X);
3557             return &TheAnd;
3558           } else {
3559             // Pull the XOR out of the AND.
3560             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3561             InsertNewInstBefore(NewAnd, TheAnd);
3562             NewAnd->takeName(Op);
3563             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3564           }
3565         }
3566       }
3567     }
3568     break;
3569
3570   case Instruction::Shl: {
3571     // We know that the AND will not produce any of the bits shifted in, so if
3572     // the anded constant includes them, clear them now!
3573     //
3574     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3575     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3576     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3577     ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShlMask);
3578
3579     if (CI->getValue() == ShlMask) { 
3580     // Masking out bits that the shift already masks
3581       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3582     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3583       TheAnd.setOperand(1, CI);
3584       return &TheAnd;
3585     }
3586     break;
3587   }
3588   case Instruction::LShr:
3589   {
3590     // We know that the AND will not produce any of the bits shifted in, so if
3591     // the anded constant includes them, clear them now!  This only applies to
3592     // unsigned shifts, because a signed shr may bring in set bits!
3593     //
3594     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3595     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3596     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3597     ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3598
3599     if (CI->getValue() == ShrMask) {   
3600     // Masking out bits that the shift already masks.
3601       return ReplaceInstUsesWith(TheAnd, Op);
3602     } else if (CI != AndRHS) {
3603       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3604       return &TheAnd;
3605     }
3606     break;
3607   }
3608   case Instruction::AShr:
3609     // Signed shr.
3610     // See if this is shifting in some sign extension, then masking it out
3611     // with an and.
3612     if (Op->hasOneUse()) {
3613       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3614       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3615       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3616       Constant *C = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3617       if (C == AndRHS) {          // Masking out bits shifted in.
3618         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3619         // Make the argument unsigned.
3620         Value *ShVal = Op->getOperand(0);
3621         ShVal = InsertNewInstBefore(
3622             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3623                                    Op->getName()), TheAnd);
3624         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3625       }
3626     }
3627     break;
3628   }
3629   return 0;
3630 }
3631
3632
3633 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3634 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3635 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3636 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3637 /// insert new instructions.
3638 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3639                                            bool isSigned, bool Inside, 
3640                                            Instruction &IB) {
3641   assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ? 
3642             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3643          "Lo is not <= Hi in range emission code!");
3644     
3645   if (Inside) {
3646     if (Lo == Hi)  // Trivially false.
3647       return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
3648
3649     // V >= Min && V < Hi --> V < Hi
3650     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3651       ICmpInst::Predicate pred = (isSigned ? 
3652         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3653       return new ICmpInst(*Context, pred, V, Hi);
3654     }
3655
3656     // Emit V-Lo <u Hi-Lo
3657     Constant *NegLo = Context->getConstantExprNeg(Lo);
3658     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3659     InsertNewInstBefore(Add, IB);
3660     Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
3661     return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
3662   }
3663
3664   if (Lo == Hi)  // Trivially true.
3665     return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
3666
3667   // V < Min || V >= Hi -> V > Hi-1
3668   Hi = SubOne(cast<ConstantInt>(Hi), Context);
3669   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3670     ICmpInst::Predicate pred = (isSigned ? 
3671         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3672     return new ICmpInst(*Context, pred, V, Hi);
3673   }
3674
3675   // Emit V-Lo >u Hi-1-Lo
3676   // Note that Hi has already had one subtracted from it, above.
3677   ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
3678   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3679   InsertNewInstBefore(Add, IB);
3680   Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
3681   return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
3682 }
3683
3684 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3685 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3686 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3687 // not, since all 1s are not contiguous.
3688 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3689   const APInt& V = Val->getValue();
3690   uint32_t BitWidth = Val->getType()->getBitWidth();
3691   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3692
3693   // look for the first zero bit after the run of ones
3694   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3695   // look for the first non-zero bit
3696   ME = V.getActiveBits(); 
3697   return true;
3698 }
3699
3700 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3701 /// where isSub determines whether the operator is a sub.  If we can fold one of
3702 /// the following xforms:
3703 /// 
3704 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3705 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3706 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3707 ///
3708 /// return (A +/- B).
3709 ///
3710 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3711                                         ConstantInt *Mask, bool isSub,
3712                                         Instruction &I) {
3713   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3714   if (!LHSI || LHSI->getNumOperands() != 2 ||
3715       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3716
3717   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3718
3719   switch (LHSI->getOpcode()) {
3720   default: return 0;
3721   case Instruction::And:
3722     if (Context->getConstantExprAnd(N, Mask) == Mask) {
3723       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3724       if ((Mask->getValue().countLeadingZeros() + 
3725            Mask->getValue().countPopulation()) == 
3726           Mask->getValue().getBitWidth())
3727         break;
3728
3729       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3730       // part, we don't need any explicit masks to take them out of A.  If that
3731       // is all N is, ignore it.
3732       uint32_t MB = 0, ME = 0;
3733       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3734         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3735         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3736         if (MaskedValueIsZero(RHS, Mask))
3737           break;
3738       }
3739     }
3740     return 0;
3741   case Instruction::Or:
3742   case Instruction::Xor:
3743     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3744     if ((Mask->getValue().countLeadingZeros() + 
3745          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3746         && Context->getConstantExprAnd(N, Mask)->isNullValue())
3747       break;
3748     return 0;
3749   }
3750   
3751   Instruction *New;
3752   if (isSub)
3753     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3754   else
3755     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3756   return InsertNewInstBefore(New, I);
3757 }
3758
3759 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3760 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3761                                           ICmpInst *LHS, ICmpInst *RHS) {
3762   Value *Val, *Val2;
3763   ConstantInt *LHSCst, *RHSCst;
3764   ICmpInst::Predicate LHSCC, RHSCC;
3765   
3766   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3767   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3768                          m_ConstantInt(LHSCst)), *Context) ||
3769       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3770                          m_ConstantInt(RHSCst)), *Context))
3771     return 0;
3772   
3773   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3774   // where C is a power of 2
3775   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3776       LHSCst->getValue().isPowerOf2()) {
3777     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3778     InsertNewInstBefore(NewOr, I);
3779     return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
3780   }
3781   
3782   // From here on, we only handle:
3783   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3784   if (Val != Val2) return 0;
3785   
3786   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3787   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3788       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3789       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3790       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3791     return 0;
3792   
3793   // We can't fold (ugt x, C) & (sgt x, C2).
3794   if (!PredicatesFoldable(LHSCC, RHSCC))
3795     return 0;
3796     
3797   // Ensure that the larger constant is on the RHS.
3798   bool ShouldSwap;
3799   if (ICmpInst::isSignedPredicate(LHSCC) ||
3800       (ICmpInst::isEquality(LHSCC) && 
3801        ICmpInst::isSignedPredicate(RHSCC)))
3802     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3803   else
3804     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3805     
3806   if (ShouldSwap) {
3807     std::swap(LHS, RHS);
3808     std::swap(LHSCst, RHSCst);
3809     std::swap(LHSCC, RHSCC);
3810   }
3811
3812   // At this point, we know we have have two icmp instructions
3813   // comparing a value against two constants and and'ing the result
3814   // together.  Because of the above check, we know that we only have
3815   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3816   // (from the FoldICmpLogical check above), that the two constants 
3817   // are not equal and that the larger constant is on the RHS
3818   assert(LHSCst != RHSCst && "Compares not folded above?");
3819
3820   switch (LHSCC) {
3821   default: llvm_unreachable("Unknown integer condition code!");
3822   case ICmpInst::ICMP_EQ:
3823     switch (RHSCC) {
3824     default: llvm_unreachable("Unknown integer condition code!");
3825     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3826     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3827     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3828       return ReplaceInstUsesWith(I, Context->getFalse());
3829     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3830     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3831     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3832       return ReplaceInstUsesWith(I, LHS);
3833     }
3834   case ICmpInst::ICMP_NE:
3835     switch (RHSCC) {
3836     default: llvm_unreachable("Unknown integer condition code!");
3837     case ICmpInst::ICMP_ULT:
3838       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
3839         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
3840       break;                        // (X != 13 & X u< 15) -> no change
3841     case ICmpInst::ICMP_SLT:
3842       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
3843         return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
3844       break;                        // (X != 13 & X s< 15) -> no change
3845     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3846     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3847     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3848       return ReplaceInstUsesWith(I, RHS);
3849     case ICmpInst::ICMP_NE:
3850       if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3851         Constant *AddCST = Context->getConstantExprNeg(LHSCst);
3852         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3853                                                      Val->getName()+".off");
3854         InsertNewInstBefore(Add, I);
3855         return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
3856                             Context->getConstantInt(Add->getType(), 1));
3857       }
3858       break;                        // (X != 13 & X != 15) -> no change
3859     }
3860     break;
3861   case ICmpInst::ICMP_ULT:
3862     switch (RHSCC) {
3863     default: llvm_unreachable("Unknown integer condition code!");
3864     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3865     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3866       return ReplaceInstUsesWith(I, Context->getFalse());
3867     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3868       break;
3869     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3870     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3871       return ReplaceInstUsesWith(I, LHS);
3872     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3873       break;
3874     }
3875     break;
3876   case ICmpInst::ICMP_SLT:
3877     switch (RHSCC) {
3878     default: llvm_unreachable("Unknown integer condition code!");
3879     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3880     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3881       return ReplaceInstUsesWith(I, Context->getFalse());
3882     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3883       break;
3884     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3885     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3886       return ReplaceInstUsesWith(I, LHS);
3887     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3888       break;
3889     }
3890     break;
3891   case ICmpInst::ICMP_UGT:
3892     switch (RHSCC) {
3893     default: llvm_unreachable("Unknown integer condition code!");
3894     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3895     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3896       return ReplaceInstUsesWith(I, RHS);
3897     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3898       break;
3899     case ICmpInst::ICMP_NE:
3900       if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
3901         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3902       break;                        // (X u> 13 & X != 15) -> no change
3903     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3904       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3905                              RHSCst, false, true, I);
3906     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3907       break;
3908     }
3909     break;
3910   case ICmpInst::ICMP_SGT:
3911     switch (RHSCC) {
3912     default: llvm_unreachable("Unknown integer condition code!");
3913     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3914     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3915       return ReplaceInstUsesWith(I, RHS);
3916     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3917       break;
3918     case ICmpInst::ICMP_NE:
3919       if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
3920         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3921       break;                        // (X s> 13 & X != 15) -> no change
3922     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3923       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3924                              RHSCst, true, true, I);
3925     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3926       break;
3927     }
3928     break;
3929   }
3930  
3931   return 0;
3932 }
3933
3934
3935 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3936   bool Changed = SimplifyCommutative(I);
3937   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3938
3939   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3940     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3941
3942   // and X, X = X
3943   if (Op0 == Op1)
3944     return ReplaceInstUsesWith(I, Op1);
3945
3946   // See if we can simplify any instructions used by the instruction whose sole 
3947   // purpose is to compute bits we don't care about.
3948   if (SimplifyDemandedInstructionBits(I))
3949     return &I;
3950   if (isa<VectorType>(I.getType())) {
3951     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3952       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3953         return ReplaceInstUsesWith(I, I.getOperand(0));
3954     } else if (isa<ConstantAggregateZero>(Op1)) {
3955       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3956     }
3957   }
3958
3959   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3960     const APInt& AndRHSMask = AndRHS->getValue();
3961     APInt NotAndRHS(~AndRHSMask);
3962
3963     // Optimize a variety of ((val OP C1) & C2) combinations...
3964     if (isa<BinaryOperator>(Op0)) {
3965       Instruction *Op0I = cast<Instruction>(Op0);
3966       Value *Op0LHS = Op0I->getOperand(0);
3967       Value *Op0RHS = Op0I->getOperand(1);
3968       switch (Op0I->getOpcode()) {
3969       case Instruction::Xor:
3970       case Instruction::Or:
3971         // If the mask is only needed on one incoming arm, push it up.
3972         if (Op0I->hasOneUse()) {
3973           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3974             // Not masking anything out for the LHS, move to RHS.
3975             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3976                                                    Op0RHS->getName()+".masked");
3977             InsertNewInstBefore(NewRHS, I);
3978             return BinaryOperator::Create(
3979                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3980           }
3981           if (!isa<Constant>(Op0RHS) &&
3982               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3983             // Not masking anything out for the RHS, move to LHS.
3984             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3985                                                    Op0LHS->getName()+".masked");
3986             InsertNewInstBefore(NewLHS, I);
3987             return BinaryOperator::Create(
3988                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3989           }
3990         }
3991
3992         break;
3993       case Instruction::Add:
3994         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3995         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3996         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3997         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3998           return BinaryOperator::CreateAnd(V, AndRHS);
3999         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4000           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4001         break;
4002
4003       case Instruction::Sub:
4004         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4005         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4006         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4007         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4008           return BinaryOperator::CreateAnd(V, AndRHS);
4009
4010         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4011         // has 1's for all bits that the subtraction with A might affect.
4012         if (Op0I->hasOneUse()) {
4013           uint32_t BitWidth = AndRHSMask.getBitWidth();
4014           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4015           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4016
4017           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4018           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4019               MaskedValueIsZero(Op0LHS, Mask)) {
4020             Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
4021             InsertNewInstBefore(NewNeg, I);
4022             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4023           }
4024         }
4025         break;
4026
4027       case Instruction::Shl:
4028       case Instruction::LShr:
4029         // (1 << x) & 1 --> zext(x == 0)
4030         // (1 >> x) & 1 --> zext(x == 0)
4031         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4032           Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4033                                     Op0RHS, Context->getNullValue(I.getType()));
4034           InsertNewInstBefore(NewICmp, I);
4035           return new ZExtInst(NewICmp, I.getType());
4036         }
4037         break;
4038       }
4039
4040       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4041         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4042           return Res;
4043     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4044       // If this is an integer truncation or change from signed-to-unsigned, and
4045       // if the source is an and/or with immediate, transform it.  This
4046       // frequently occurs for bitfield accesses.
4047       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4048         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4049             CastOp->getNumOperands() == 2)
4050           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4051             if (CastOp->getOpcode() == Instruction::And) {
4052               // Change: and (cast (and X, C1) to T), C2
4053               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4054               // This will fold the two constants together, which may allow 
4055               // other simplifications.
4056               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4057                 CastOp->getOperand(0), I.getType(), 
4058                 CastOp->getName()+".shrunk");
4059               NewCast = InsertNewInstBefore(NewCast, I);
4060               // trunc_or_bitcast(C1)&C2
4061               Constant *C3 =
4062                       Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4063               C3 = Context->getConstantExprAnd(C3, AndRHS);
4064               return BinaryOperator::CreateAnd(NewCast, C3);
4065             } else if (CastOp->getOpcode() == Instruction::Or) {
4066               // Change: and (cast (or X, C1) to T), C2
4067               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4068               Constant *C3 =
4069                       Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4070               if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4071                 // trunc(C1)&C2
4072                 return ReplaceInstUsesWith(I, AndRHS);
4073             }
4074           }
4075       }
4076     }
4077
4078     // Try to fold constant and into select arguments.
4079     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4080       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4081         return R;
4082     if (isa<PHINode>(Op0))
4083       if (Instruction *NV = FoldOpIntoPhi(I))
4084         return NV;
4085   }
4086
4087   Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4088   Value *Op1NotVal = dyn_castNotVal(Op1, Context);
4089
4090   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4091     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
4092
4093   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4094   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4095     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4096                                                I.getName()+".demorgan");
4097     InsertNewInstBefore(Or, I);
4098     return BinaryOperator::CreateNot(*Context, Or);
4099   }
4100   
4101   {
4102     Value *A = 0, *B = 0, *C = 0, *D = 0;
4103     if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
4104       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4105         return ReplaceInstUsesWith(I, Op1);
4106     
4107       // (A|B) & ~(A&B) -> A^B
4108       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4109         if ((A == C && B == D) || (A == D && B == C))
4110           return BinaryOperator::CreateXor(A, B);
4111       }
4112     }
4113     
4114     if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
4115       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4116         return ReplaceInstUsesWith(I, Op0);
4117
4118       // ~(A&B) & (A|B) -> A^B
4119       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4120         if ((A == C && B == D) || (A == D && B == C))
4121           return BinaryOperator::CreateXor(A, B);
4122       }
4123     }
4124     
4125     if (Op0->hasOneUse() &&
4126         match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4127       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4128         I.swapOperands();     // Simplify below
4129         std::swap(Op0, Op1);
4130       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4131         cast<BinaryOperator>(Op0)->swapOperands();
4132         I.swapOperands();     // Simplify below
4133         std::swap(Op0, Op1);
4134       }
4135     }
4136
4137     if (Op1->hasOneUse() &&
4138         match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4139       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4140         cast<BinaryOperator>(Op1)->swapOperands();
4141         std::swap(A, B);
4142       }
4143       if (A == Op0) {                                // A&(A^B) -> A & ~B
4144         Instruction *NotB = BinaryOperator::CreateNot(*Context, B, "tmp");
4145         InsertNewInstBefore(NotB, I);
4146         return BinaryOperator::CreateAnd(A, NotB);
4147       }
4148     }
4149
4150     // (A&((~A)|B)) -> A&B
4151     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4152         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
4153       return BinaryOperator::CreateAnd(A, Op1);
4154     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4155         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
4156       return BinaryOperator::CreateAnd(A, Op0);
4157   }
4158   
4159   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4160     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4161     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4162       return R;
4163
4164     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4165       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4166         return Res;
4167   }
4168
4169   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4170   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4171     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4172       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4173         const Type *SrcTy = Op0C->getOperand(0)->getType();
4174         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4175             // Only do this if the casts both really cause code to be generated.
4176             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4177                               I.getType(), TD) &&
4178             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4179                               I.getType(), TD)) {
4180           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4181                                                          Op1C->getOperand(0),
4182                                                          I.getName());
4183           InsertNewInstBefore(NewOp, I);
4184           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4185         }
4186       }
4187     
4188   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4189   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4190     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4191       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4192           SI0->getOperand(1) == SI1->getOperand(1) &&
4193           (SI0->hasOneUse() || SI1->hasOneUse())) {
4194         Instruction *NewOp =
4195           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4196                                                         SI1->getOperand(0),
4197                                                         SI0->getName()), I);
4198         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4199                                       SI1->getOperand(1));
4200       }
4201   }
4202
4203   // If and'ing two fcmp, try combine them into one.
4204   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4205     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4206       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4207           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4208         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4209         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4210           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4211             // If either of the constants are nans, then the whole thing returns
4212             // false.
4213             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4214               return ReplaceInstUsesWith(I, Context->getFalse());
4215             return new FCmpInst(*Context, FCmpInst::FCMP_ORD, 
4216                                 LHS->getOperand(0), RHS->getOperand(0));
4217           }
4218       } else {
4219         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4220         FCmpInst::Predicate Op0CC, Op1CC;
4221         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4222                   m_Value(Op0RHS)), *Context) &&
4223             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4224                   m_Value(Op1RHS)), *Context)) {
4225           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4226             // Swap RHS operands to match LHS.
4227             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4228             std::swap(Op1LHS, Op1RHS);
4229           }
4230           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4231             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4232             if (Op0CC == Op1CC)
4233               return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4234                                   Op0LHS, Op0RHS);
4235             else if (Op0CC == FCmpInst::FCMP_FALSE ||
4236                      Op1CC == FCmpInst::FCMP_FALSE)
4237               return ReplaceInstUsesWith(I, Context->getFalse());
4238             else if (Op0CC == FCmpInst::FCMP_TRUE)
4239               return ReplaceInstUsesWith(I, Op1);
4240             else if (Op1CC == FCmpInst::FCMP_TRUE)
4241               return ReplaceInstUsesWith(I, Op0);
4242             bool Op0Ordered;
4243             bool Op1Ordered;
4244             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4245             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4246             if (Op1Pred == 0) {
4247               std::swap(Op0, Op1);
4248               std::swap(Op0Pred, Op1Pred);
4249               std::swap(Op0Ordered, Op1Ordered);
4250             }
4251             if (Op0Pred == 0) {
4252               // uno && ueq -> uno && (uno || eq) -> ueq
4253               // ord && olt -> ord && (ord && lt) -> olt
4254               if (Op0Ordered == Op1Ordered)
4255                 return ReplaceInstUsesWith(I, Op1);
4256               // uno && oeq -> uno && (ord && eq) -> false
4257               // uno && ord -> false
4258               if (!Op0Ordered)
4259                 return ReplaceInstUsesWith(I, Context->getFalse());
4260               // ord && ueq -> ord && (uno || eq) -> oeq
4261               return cast<Instruction>(getFCmpValue(true, Op1Pred,
4262                                                     Op0LHS, Op0RHS, Context));
4263             }
4264           }
4265         }
4266       }
4267     }
4268   }
4269
4270   return Changed ? &I : 0;
4271 }
4272
4273 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4274 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4275 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4276 /// the expression came from the corresponding "byte swapped" byte in some other
4277 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4278 /// we know that the expression deposits the low byte of %X into the high byte
4279 /// of the bswap result and that all other bytes are zero.  This expression is
4280 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4281 /// match.
4282 ///
4283 /// This function returns true if the match was unsuccessful and false if so.
4284 /// On entry to the function the "OverallLeftShift" is a signed integer value
4285 /// indicating the number of bytes that the subexpression is later shifted.  For
4286 /// example, if the expression is later right shifted by 16 bits, the
4287 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4288 /// byte of ByteValues is actually being set.
4289 ///
4290 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4291 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4292 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4293 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4294 /// always in the local (OverallLeftShift) coordinate space.
4295 ///
4296 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4297                               SmallVector<Value*, 8> &ByteValues) {
4298   if (Instruction *I = dyn_cast<Instruction>(V)) {
4299     // If this is an or instruction, it may be an inner node of the bswap.
4300     if (I->getOpcode() == Instruction::Or) {
4301       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4302                                ByteValues) ||
4303              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4304                                ByteValues);
4305     }
4306   
4307     // If this is a logical shift by a constant multiple of 8, recurse with
4308     // OverallLeftShift and ByteMask adjusted.
4309     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4310       unsigned ShAmt = 
4311         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4312       // Ensure the shift amount is defined and of a byte value.
4313       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4314         return true;
4315
4316       unsigned ByteShift = ShAmt >> 3;
4317       if (I->getOpcode() == Instruction::Shl) {
4318         // X << 2 -> collect(X, +2)
4319         OverallLeftShift += ByteShift;
4320         ByteMask >>= ByteShift;
4321       } else {
4322         // X >>u 2 -> collect(X, -2)
4323         OverallLeftShift -= ByteShift;
4324         ByteMask <<= ByteShift;
4325         ByteMask &= (~0U >> (32-ByteValues.size()));
4326       }
4327
4328       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4329       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4330
4331       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4332                                ByteValues);
4333     }
4334
4335     // If this is a logical 'and' with a mask that clears bytes, clear the
4336     // corresponding bytes in ByteMask.
4337     if (I->getOpcode() == Instruction::And &&
4338         isa<ConstantInt>(I->getOperand(1))) {
4339       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4340       unsigned NumBytes = ByteValues.size();
4341       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4342       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4343       
4344       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4345         // If this byte is masked out by a later operation, we don't care what
4346         // the and mask is.
4347         if ((ByteMask & (1 << i)) == 0)
4348           continue;
4349         
4350         // If the AndMask is all zeros for this byte, clear the bit.
4351         APInt MaskB = AndMask & Byte;
4352         if (MaskB == 0) {
4353           ByteMask &= ~(1U << i);
4354           continue;
4355         }
4356         
4357         // If the AndMask is not all ones for this byte, it's not a bytezap.
4358         if (MaskB != Byte)
4359           return true;
4360
4361         // Otherwise, this byte is kept.
4362       }
4363
4364       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4365                                ByteValues);
4366     }
4367   }
4368   
4369   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4370   // the input value to the bswap.  Some observations: 1) if more than one byte
4371   // is demanded from this input, then it could not be successfully assembled
4372   // into a byteswap.  At least one of the two bytes would not be aligned with
4373   // their ultimate destination.
4374   if (!isPowerOf2_32(ByteMask)) return true;
4375   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4376   
4377   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4378   // is demanded, it needs to go into byte 0 of the result.  This means that the
4379   // byte needs to be shifted until it lands in the right byte bucket.  The
4380   // shift amount depends on the position: if the byte is coming from the high
4381   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4382   // low part, it must be shifted left.
4383   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4384   if (InputByteNo < ByteValues.size()/2) {
4385     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4386       return true;
4387   } else {
4388     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4389       return true;
4390   }
4391   
4392   // If the destination byte value is already defined, the values are or'd
4393   // together, which isn't a bswap (unless it's an or of the same bits).
4394   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4395     return true;
4396   ByteValues[DestByteNo] = V;
4397   return false;
4398 }
4399
4400 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4401 /// If so, insert the new bswap intrinsic and return it.
4402 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4403   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4404   if (!ITy || ITy->getBitWidth() % 16 || 
4405       // ByteMask only allows up to 32-byte values.
4406       ITy->getBitWidth() > 32*8) 
4407     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4408   
4409   /// ByteValues - For each byte of the result, we keep track of which value
4410   /// defines each byte.
4411   SmallVector<Value*, 8> ByteValues;
4412   ByteValues.resize(ITy->getBitWidth()/8);
4413     
4414   // Try to find all the pieces corresponding to the bswap.
4415   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4416   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4417     return 0;
4418   
4419   // Check to see if all of the bytes come from the same value.
4420   Value *V = ByteValues[0];
4421   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4422   
4423   // Check to make sure that all of the bytes come from the same value.
4424   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4425     if (ByteValues[i] != V)
4426       return 0;
4427   const Type *Tys[] = { ITy };
4428   Module *M = I.getParent()->getParent()->getParent();
4429   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4430   return CallInst::Create(F, V);
4431 }
4432
4433 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4434 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4435 /// we can simplify this expression to "cond ? C : D or B".
4436 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4437                                          Value *C, Value *D,
4438                                          LLVMContext *Context) {
4439   // If A is not a select of -1/0, this cannot match.
4440   Value *Cond = 0;
4441   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
4442     return 0;
4443
4444   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4445   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4446     return SelectInst::Create(Cond, C, B);
4447   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4448     return SelectInst::Create(Cond, C, B);
4449   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4450   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4451     return SelectInst::Create(Cond, C, D);
4452   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4453     return SelectInst::Create(Cond, C, D);
4454   return 0;
4455 }
4456
4457 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4458 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4459                                          ICmpInst *LHS, ICmpInst *RHS) {
4460   Value *Val, *Val2;
4461   ConstantInt *LHSCst, *RHSCst;
4462   ICmpInst::Predicate LHSCC, RHSCC;
4463   
4464   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4465   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4466              m_ConstantInt(LHSCst)), *Context) ||
4467       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4468              m_ConstantInt(RHSCst)), *Context))
4469     return 0;
4470   
4471   // From here on, we only handle:
4472   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4473   if (Val != Val2) return 0;
4474   
4475   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4476   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4477       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4478       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4479       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4480     return 0;
4481   
4482   // We can't fold (ugt x, C) | (sgt x, C2).
4483   if (!PredicatesFoldable(LHSCC, RHSCC))
4484     return 0;
4485   
4486   // Ensure that the larger constant is on the RHS.
4487   bool ShouldSwap;
4488   if (ICmpInst::isSignedPredicate(LHSCC) ||
4489       (ICmpInst::isEquality(LHSCC) && 
4490        ICmpInst::isSignedPredicate(RHSCC)))
4491     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4492   else
4493     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4494   
4495   if (ShouldSwap) {
4496     std::swap(LHS, RHS);
4497     std::swap(LHSCst, RHSCst);
4498     std::swap(LHSCC, RHSCC);
4499   }
4500   
4501   // At this point, we know we have have two icmp instructions
4502   // comparing a value against two constants and or'ing the result
4503   // together.  Because of the above check, we know that we only have
4504   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4505   // FoldICmpLogical check above), that the two constants are not
4506   // equal.
4507   assert(LHSCst != RHSCst && "Compares not folded above?");
4508
4509   switch (LHSCC) {
4510   default: llvm_unreachable("Unknown integer condition code!");
4511   case ICmpInst::ICMP_EQ:
4512     switch (RHSCC) {
4513     default: llvm_unreachable("Unknown integer condition code!");
4514     case ICmpInst::ICMP_EQ:
4515       if (LHSCst == SubOne(RHSCst, Context)) {
4516         // (X == 13 | X == 14) -> X-13 <u 2
4517         Constant *AddCST = Context->getConstantExprNeg(LHSCst);
4518         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4519                                                      Val->getName()+".off");
4520         InsertNewInstBefore(Add, I);
4521         AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
4522         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
4523       }
4524       break;                         // (X == 13 | X == 15) -> no change
4525     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4526     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4527       break;
4528     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4529     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4530     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4531       return ReplaceInstUsesWith(I, RHS);
4532     }
4533     break;
4534   case ICmpInst::ICMP_NE:
4535     switch (RHSCC) {
4536     default: llvm_unreachable("Unknown integer condition code!");
4537     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4538     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4539     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4540       return ReplaceInstUsesWith(I, LHS);
4541     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4542     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4543     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4544       return ReplaceInstUsesWith(I, Context->getTrue());
4545     }
4546     break;
4547   case ICmpInst::ICMP_ULT:
4548     switch (RHSCC) {
4549     default: llvm_unreachable("Unknown integer condition code!");
4550     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4551       break;
4552     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4553       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4554       // this can cause overflow.
4555       if (RHSCst->isMaxValue(false))
4556         return ReplaceInstUsesWith(I, LHS);
4557       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4558                              false, false, I);
4559     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4560       break;
4561     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4562     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4563       return ReplaceInstUsesWith(I, RHS);
4564     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4565       break;
4566     }
4567     break;
4568   case ICmpInst::ICMP_SLT:
4569     switch (RHSCC) {
4570     default: llvm_unreachable("Unknown integer condition code!");
4571     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4572       break;
4573     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4574       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4575       // this can cause overflow.
4576       if (RHSCst->isMaxValue(true))
4577         return ReplaceInstUsesWith(I, LHS);
4578       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4579                              true, false, I);
4580     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4581       break;
4582     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4583     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4584       return ReplaceInstUsesWith(I, RHS);
4585     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4586       break;
4587     }
4588     break;
4589   case ICmpInst::ICMP_UGT:
4590     switch (RHSCC) {
4591     default: llvm_unreachable("Unknown integer condition code!");
4592     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4593     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4594       return ReplaceInstUsesWith(I, LHS);
4595     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4596       break;
4597     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4598     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4599       return ReplaceInstUsesWith(I, Context->getTrue());
4600     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4601       break;
4602     }
4603     break;
4604   case ICmpInst::ICMP_SGT:
4605     switch (RHSCC) {
4606     default: llvm_unreachable("Unknown integer condition code!");
4607     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4608     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4609       return ReplaceInstUsesWith(I, LHS);
4610     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4611       break;
4612     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4613     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4614       return ReplaceInstUsesWith(I, Context->getTrue());
4615     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4616       break;
4617     }
4618     break;
4619   }
4620   return 0;
4621 }
4622
4623 /// FoldOrWithConstants - This helper function folds:
4624 ///
4625 ///     ((A | B) & C1) | (B & C2)
4626 ///
4627 /// into:
4628 /// 
4629 ///     (A & C1) | B
4630 ///
4631 /// when the XOR of the two constants is "all ones" (-1).
4632 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4633                                                Value *A, Value *B, Value *C) {
4634   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4635   if (!CI1) return 0;
4636
4637   Value *V1 = 0;
4638   ConstantInt *CI2 = 0;
4639   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
4640
4641   APInt Xor = CI1->getValue() ^ CI2->getValue();
4642   if (!Xor.isAllOnesValue()) return 0;
4643
4644   if (V1 == A || V1 == B) {
4645     Instruction *NewOp =
4646       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4647     return BinaryOperator::CreateOr(NewOp, V1);
4648   }
4649
4650   return 0;
4651 }
4652
4653 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4654   bool Changed = SimplifyCommutative(I);
4655   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4656
4657   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4658     return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4659
4660   // or X, X = X
4661   if (Op0 == Op1)
4662     return ReplaceInstUsesWith(I, Op0);
4663
4664   // See if we can simplify any instructions used by the instruction whose sole 
4665   // purpose is to compute bits we don't care about.
4666   if (SimplifyDemandedInstructionBits(I))
4667     return &I;
4668   if (isa<VectorType>(I.getType())) {
4669     if (isa<ConstantAggregateZero>(Op1)) {
4670       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4671     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4672       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4673         return ReplaceInstUsesWith(I, I.getOperand(1));
4674     }
4675   }
4676
4677   // or X, -1 == -1
4678   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4679     ConstantInt *C1 = 0; Value *X = 0;
4680     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4681     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) && 
4682         isOnlyUse(Op0)) {
4683       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4684       InsertNewInstBefore(Or, I);
4685       Or->takeName(Op0);
4686       return BinaryOperator::CreateAnd(Or, 
4687                Context->getConstantInt(RHS->getValue() | C1->getValue()));
4688     }
4689
4690     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4691     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) && 
4692         isOnlyUse(Op0)) {
4693       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4694       InsertNewInstBefore(Or, I);
4695       Or->takeName(Op0);
4696       return BinaryOperator::CreateXor(Or,
4697                  Context->getConstantInt(C1->getValue() & ~RHS->getValue()));
4698     }
4699
4700     // Try to fold constant and into select arguments.
4701     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4702       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4703         return R;
4704     if (isa<PHINode>(Op0))
4705       if (Instruction *NV = FoldOpIntoPhi(I))
4706         return NV;
4707   }
4708
4709   Value *A = 0, *B = 0;
4710   ConstantInt *C1 = 0, *C2 = 0;
4711
4712   if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
4713     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4714       return ReplaceInstUsesWith(I, Op1);
4715   if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
4716     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4717       return ReplaceInstUsesWith(I, Op0);
4718
4719   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4720   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4721   if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4722       match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4723       (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4724        match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
4725     if (Instruction *BSwap = MatchBSwap(I))
4726       return BSwap;
4727   }
4728   
4729   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4730   if (Op0->hasOneUse() &&
4731       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4732       MaskedValueIsZero(Op1, C1->getValue())) {
4733     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4734     InsertNewInstBefore(NOr, I);
4735     NOr->takeName(Op0);
4736     return BinaryOperator::CreateXor(NOr, C1);
4737   }
4738
4739   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4740   if (Op1->hasOneUse() &&
4741       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4742       MaskedValueIsZero(Op0, C1->getValue())) {
4743     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4744     InsertNewInstBefore(NOr, I);
4745     NOr->takeName(Op0);
4746     return BinaryOperator::CreateXor(NOr, C1);
4747   }
4748
4749   // (A & C)|(B & D)
4750   Value *C = 0, *D = 0;
4751   if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4752       match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
4753     Value *V1 = 0, *V2 = 0, *V3 = 0;
4754     C1 = dyn_cast<ConstantInt>(C);
4755     C2 = dyn_cast<ConstantInt>(D);
4756     if (C1 && C2) {  // (A & C1)|(B & C2)
4757       // If we have: ((V + N) & C1) | (V & C2)
4758       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4759       // replace with V+N.
4760       if (C1->getValue() == ~C2->getValue()) {
4761         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4762             match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4763           // Add commutes, try both ways.
4764           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4765             return ReplaceInstUsesWith(I, A);
4766           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4767             return ReplaceInstUsesWith(I, A);
4768         }
4769         // Or commutes, try both ways.
4770         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4771             match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4772           // Add commutes, try both ways.
4773           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4774             return ReplaceInstUsesWith(I, B);
4775           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4776             return ReplaceInstUsesWith(I, B);
4777         }
4778       }
4779       V1 = 0; V2 = 0; V3 = 0;
4780     }
4781     
4782     // Check to see if we have any common things being and'ed.  If so, find the
4783     // terms for V1 & (V2|V3).
4784     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4785       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4786         V1 = A, V2 = C, V3 = D;
4787       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4788         V1 = A, V2 = B, V3 = C;
4789       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4790         V1 = C, V2 = A, V3 = D;
4791       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4792         V1 = C, V2 = A, V3 = B;
4793       
4794       if (V1) {
4795         Value *Or =
4796           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4797         return BinaryOperator::CreateAnd(V1, Or);
4798       }
4799     }
4800
4801     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4802     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4803       return Match;
4804     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4805       return Match;
4806     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4807       return Match;
4808     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4809       return Match;
4810
4811     // ((A&~B)|(~A&B)) -> A^B
4812     if ((match(C, m_Not(m_Specific(D)), *Context) &&
4813          match(B, m_Not(m_Specific(A)), *Context)))
4814       return BinaryOperator::CreateXor(A, D);
4815     // ((~B&A)|(~A&B)) -> A^B
4816     if ((match(A, m_Not(m_Specific(D)), *Context) &&
4817          match(B, m_Not(m_Specific(C)), *Context)))
4818       return BinaryOperator::CreateXor(C, D);
4819     // ((A&~B)|(B&~A)) -> A^B
4820     if ((match(C, m_Not(m_Specific(B)), *Context) &&
4821          match(D, m_Not(m_Specific(A)), *Context)))
4822       return BinaryOperator::CreateXor(A, B);
4823     // ((~B&A)|(B&~A)) -> A^B
4824     if ((match(A, m_Not(m_Specific(B)), *Context) &&
4825          match(D, m_Not(m_Specific(C)), *Context)))
4826       return BinaryOperator::CreateXor(C, B);
4827   }
4828   
4829   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4830   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4831     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4832       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4833           SI0->getOperand(1) == SI1->getOperand(1) &&
4834           (SI0->hasOneUse() || SI1->hasOneUse())) {
4835         Instruction *NewOp =
4836         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4837                                                      SI1->getOperand(0),
4838                                                      SI0->getName()), I);
4839         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4840                                       SI1->getOperand(1));
4841       }
4842   }
4843
4844   // ((A|B)&1)|(B&-2) -> (A&1) | B
4845   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4846       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4847     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4848     if (Ret) return Ret;
4849   }
4850   // (B&-2)|((A|B)&1) -> (A&1) | B
4851   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4852       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4853     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4854     if (Ret) return Ret;
4855   }
4856
4857   if (match(Op0, m_Not(m_Value(A)), *Context)) {   // ~A | Op1
4858     if (A == Op1)   // ~A | A == -1
4859       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4860   } else {
4861     A = 0;
4862   }
4863   // Note, A is still live here!
4864   if (match(Op1, m_Not(m_Value(B)), *Context)) {   // Op0 | ~B
4865     if (Op0 == B)
4866       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4867
4868     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4869     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4870       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4871                                               I.getName()+".demorgan"), I);
4872       return BinaryOperator::CreateNot(*Context, And);
4873     }
4874   }
4875
4876   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4877   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4878     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4879       return R;
4880
4881     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4882       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4883         return Res;
4884   }
4885     
4886   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4887   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4888     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4889       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4890         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4891             !isa<ICmpInst>(Op1C->getOperand(0))) {
4892           const Type *SrcTy = Op0C->getOperand(0)->getType();
4893           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4894               // Only do this if the casts both really cause code to be
4895               // generated.
4896               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4897                                 I.getType(), TD) &&
4898               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4899                                 I.getType(), TD)) {
4900             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4901                                                           Op1C->getOperand(0),
4902                                                           I.getName());
4903             InsertNewInstBefore(NewOp, I);
4904             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4905           }
4906         }
4907       }
4908   }
4909   
4910     
4911   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4912   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4913     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4914       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4915           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4916           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4917         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4918           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4919             // If either of the constants are nans, then the whole thing returns
4920             // true.
4921             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4922               return ReplaceInstUsesWith(I, Context->getTrue());
4923             
4924             // Otherwise, no need to compare the two constants, compare the
4925             // rest.
4926             return new FCmpInst(*Context, FCmpInst::FCMP_UNO, 
4927                                 LHS->getOperand(0), RHS->getOperand(0));
4928           }
4929       } else {
4930         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4931         FCmpInst::Predicate Op0CC, Op1CC;
4932         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4933                   m_Value(Op0RHS)), *Context) &&
4934             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4935                   m_Value(Op1RHS)), *Context)) {
4936           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4937             // Swap RHS operands to match LHS.
4938             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4939             std::swap(Op1LHS, Op1RHS);
4940           }
4941           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4942             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4943             if (Op0CC == Op1CC)
4944               return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4945                                   Op0LHS, Op0RHS);
4946             else if (Op0CC == FCmpInst::FCMP_TRUE ||
4947                      Op1CC == FCmpInst::FCMP_TRUE)
4948               return ReplaceInstUsesWith(I, Context->getTrue());
4949             else if (Op0CC == FCmpInst::FCMP_FALSE)
4950               return ReplaceInstUsesWith(I, Op1);
4951             else if (Op1CC == FCmpInst::FCMP_FALSE)
4952               return ReplaceInstUsesWith(I, Op0);
4953             bool Op0Ordered;
4954             bool Op1Ordered;
4955             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4956             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4957             if (Op0Ordered == Op1Ordered) {
4958               // If both are ordered or unordered, return a new fcmp with
4959               // or'ed predicates.
4960               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4961                                        Op0LHS, Op0RHS, Context);
4962               if (Instruction *I = dyn_cast<Instruction>(RV))
4963                 return I;
4964               // Otherwise, it's a constant boolean value...
4965               return ReplaceInstUsesWith(I, RV);
4966             }
4967           }
4968         }
4969       }
4970     }
4971   }
4972
4973   return Changed ? &I : 0;
4974 }
4975
4976 namespace {
4977
4978 // XorSelf - Implements: X ^ X --> 0
4979 struct XorSelf {
4980   Value *RHS;
4981   XorSelf(Value *rhs) : RHS(rhs) {}
4982   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4983   Instruction *apply(BinaryOperator &Xor) const {
4984     return &Xor;
4985   }
4986 };
4987
4988 }
4989
4990 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4991   bool Changed = SimplifyCommutative(I);
4992   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4993
4994   if (isa<UndefValue>(Op1)) {
4995     if (isa<UndefValue>(Op0))
4996       // Handle undef ^ undef -> 0 special case. This is a common
4997       // idiom (misuse).
4998       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
4999     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5000   }
5001
5002   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5003   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
5004     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5005     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5006   }
5007   
5008   // See if we can simplify any instructions used by the instruction whose sole 
5009   // purpose is to compute bits we don't care about.
5010   if (SimplifyDemandedInstructionBits(I))
5011     return &I;
5012   if (isa<VectorType>(I.getType()))
5013     if (isa<ConstantAggregateZero>(Op1))
5014       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5015
5016   // Is this a ~ operation?
5017   if (Value *NotOp = dyn_castNotVal(&I, Context)) {
5018     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5019     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5020     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5021       if (Op0I->getOpcode() == Instruction::And || 
5022           Op0I->getOpcode() == Instruction::Or) {
5023         if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5024         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
5025           Instruction *NotY =
5026             BinaryOperator::CreateNot(*Context, Op0I->getOperand(1),
5027                                       Op0I->getOperand(1)->getName()+".not");
5028           InsertNewInstBefore(NotY, I);
5029           if (Op0I->getOpcode() == Instruction::And)
5030             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5031           else
5032             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5033         }
5034       }
5035     }
5036   }
5037   
5038   
5039   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5040     if (RHS == Context->getTrue() && Op0->hasOneUse()) {
5041       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5042       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5043         return new ICmpInst(*Context, ICI->getInversePredicate(),
5044                             ICI->getOperand(0), ICI->getOperand(1));
5045
5046       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5047         return new FCmpInst(*Context, FCI->getInversePredicate(),
5048                             FCI->getOperand(0), FCI->getOperand(1));
5049     }
5050
5051     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5052     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5053       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5054         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5055           Instruction::CastOps Opcode = Op0C->getOpcode();
5056           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5057             if (RHS == Context->getConstantExprCast(Opcode, 
5058                                              Context->getTrue(),
5059                                              Op0C->getDestTy())) {
5060               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5061                                      *Context,
5062                                      CI->getOpcode(), CI->getInversePredicate(),
5063                                      CI->getOperand(0), CI->getOperand(1)), I);
5064               NewCI->takeName(CI);
5065               return CastInst::Create(Opcode, NewCI, Op0C->getType());
5066             }
5067           }
5068         }
5069       }
5070     }
5071
5072     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5073       // ~(c-X) == X-c-1 == X+(-c-1)
5074       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5075         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5076           Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5077           Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
5078                                       Context->getConstantInt(I.getType(), 1));
5079           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5080         }
5081           
5082       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5083         if (Op0I->getOpcode() == Instruction::Add) {
5084           // ~(X-c) --> (-c-1)-X
5085           if (RHS->isAllOnesValue()) {
5086             Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
5087             return BinaryOperator::CreateSub(
5088                            Context->getConstantExprSub(NegOp0CI,
5089                                       Context->getConstantInt(I.getType(), 1)),
5090                                       Op0I->getOperand(0));
5091           } else if (RHS->getValue().isSignBit()) {
5092             // (X + C) ^ signbit -> (X + C + signbit)
5093             Constant *C =
5094                    Context->getConstantInt(RHS->getValue() + Op0CI->getValue());
5095             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5096
5097           }
5098         } else if (Op0I->getOpcode() == Instruction::Or) {
5099           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5100           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5101             Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
5102             // Anything in both C1 and C2 is known to be zero, remove it from
5103             // NewRHS.
5104             Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5105             NewRHS = Context->getConstantExprAnd(NewRHS, 
5106                                        Context->getConstantExprNot(CommonBits));
5107             AddToWorkList(Op0I);
5108             I.setOperand(0, Op0I->getOperand(0));
5109             I.setOperand(1, NewRHS);
5110             return &I;
5111           }
5112         }
5113       }
5114     }
5115
5116     // Try to fold constant and into select arguments.
5117     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5118       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5119         return R;
5120     if (isa<PHINode>(Op0))
5121       if (Instruction *NV = FoldOpIntoPhi(I))
5122         return NV;
5123   }
5124
5125   if (Value *X = dyn_castNotVal(Op0, Context))   // ~A ^ A == -1
5126     if (X == Op1)
5127       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5128
5129   if (Value *X = dyn_castNotVal(Op1, Context))   // A ^ ~A == -1
5130     if (X == Op0)
5131       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5132
5133   
5134   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5135   if (Op1I) {
5136     Value *A, *B;
5137     if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
5138       if (A == Op0) {              // B^(B|A) == (A|B)^B
5139         Op1I->swapOperands();
5140         I.swapOperands();
5141         std::swap(Op0, Op1);
5142       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5143         I.swapOperands();     // Simplified below.
5144         std::swap(Op0, Op1);
5145       }
5146     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
5147       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5148     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
5149       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5150     } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) && 
5151                Op1I->hasOneUse()){
5152       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5153         Op1I->swapOperands();
5154         std::swap(A, B);
5155       }
5156       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5157         I.swapOperands();     // Simplified below.
5158         std::swap(Op0, Op1);
5159       }
5160     }
5161   }
5162   
5163   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5164   if (Op0I) {
5165     Value *A, *B;
5166     if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5167         Op0I->hasOneUse()) {
5168       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5169         std::swap(A, B);
5170       if (B == Op1) {                                // (A|B)^B == A & ~B
5171         Instruction *NotB =
5172           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, 
5173                                                         Op1, "tmp"), I);
5174         return BinaryOperator::CreateAnd(A, NotB);
5175       }
5176     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
5177       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5178     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
5179       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5180     } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) && 
5181                Op0I->hasOneUse()){
5182       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5183         std::swap(A, B);
5184       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5185           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5186         Instruction *N =
5187           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, A, "tmp"), I);
5188         return BinaryOperator::CreateAnd(N, Op1);
5189       }
5190     }
5191   }
5192   
5193   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5194   if (Op0I && Op1I && Op0I->isShift() && 
5195       Op0I->getOpcode() == Op1I->getOpcode() && 
5196       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5197       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5198     Instruction *NewOp =
5199       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5200                                                     Op1I->getOperand(0),
5201                                                     Op0I->getName()), I);
5202     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5203                                   Op1I->getOperand(1));
5204   }
5205     
5206   if (Op0I && Op1I) {
5207     Value *A, *B, *C, *D;
5208     // (A & B)^(A | B) -> A ^ B
5209     if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5210         match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
5211       if ((A == C && B == D) || (A == D && B == C)) 
5212         return BinaryOperator::CreateXor(A, B);
5213     }
5214     // (A | B)^(A & B) -> A ^ B
5215     if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5216         match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5217       if ((A == C && B == D) || (A == D && B == C)) 
5218         return BinaryOperator::CreateXor(A, B);
5219     }
5220     
5221     // (A & B)^(C & D)
5222     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5223         match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5224         match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5225       // (X & Y)^(X & Y) -> (Y^Z) & X
5226       Value *X = 0, *Y = 0, *Z = 0;
5227       if (A == C)
5228         X = A, Y = B, Z = D;
5229       else if (A == D)
5230         X = A, Y = B, Z = C;
5231       else if (B == C)
5232         X = B, Y = A, Z = D;
5233       else if (B == D)
5234         X = B, Y = A, Z = C;
5235       
5236       if (X) {
5237         Instruction *NewOp =
5238         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5239         return BinaryOperator::CreateAnd(NewOp, X);
5240       }
5241     }
5242   }
5243     
5244   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5245   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5246     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
5247       return R;
5248
5249   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5250   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5251     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5252       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5253         const Type *SrcTy = Op0C->getOperand(0)->getType();
5254         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5255             // Only do this if the casts both really cause code to be generated.
5256             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5257                               I.getType(), TD) &&
5258             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5259                               I.getType(), TD)) {
5260           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5261                                                          Op1C->getOperand(0),
5262                                                          I.getName());
5263           InsertNewInstBefore(NewOp, I);
5264           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5265         }
5266       }
5267   }
5268
5269   return Changed ? &I : 0;
5270 }
5271
5272 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5273                                    LLVMContext *Context) {
5274   return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
5275 }
5276
5277 static bool HasAddOverflow(ConstantInt *Result,
5278                            ConstantInt *In1, ConstantInt *In2,
5279                            bool IsSigned) {
5280   if (IsSigned)
5281     if (In2->getValue().isNegative())
5282       return Result->getValue().sgt(In1->getValue());
5283     else
5284       return Result->getValue().slt(In1->getValue());
5285   else
5286     return Result->getValue().ult(In1->getValue());
5287 }
5288
5289 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5290 /// overflowed for this type.
5291 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5292                             Constant *In2, LLVMContext *Context,
5293                             bool IsSigned = false) {
5294   Result = Context->getConstantExprAdd(In1, In2);
5295
5296   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5297     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5298       Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5299       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5300                          ExtractElement(In1, Idx, Context),
5301                          ExtractElement(In2, Idx, Context),
5302                          IsSigned))
5303         return true;
5304     }
5305     return false;
5306   }
5307
5308   return HasAddOverflow(cast<ConstantInt>(Result),
5309                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5310                         IsSigned);
5311 }
5312
5313 static bool HasSubOverflow(ConstantInt *Result,
5314                            ConstantInt *In1, ConstantInt *In2,
5315                            bool IsSigned) {
5316   if (IsSigned)
5317     if (In2->getValue().isNegative())
5318       return Result->getValue().slt(In1->getValue());
5319     else
5320       return Result->getValue().sgt(In1->getValue());
5321   else
5322     return Result->getValue().ugt(In1->getValue());
5323 }
5324
5325 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5326 /// overflowed for this type.
5327 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5328                             Constant *In2, LLVMContext *Context,
5329                             bool IsSigned = false) {
5330   Result = Context->getConstantExprSub(In1, In2);
5331
5332   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5333     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5334       Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5335       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5336                          ExtractElement(In1, Idx, Context),
5337                          ExtractElement(In2, Idx, Context),
5338                          IsSigned))
5339         return true;
5340     }
5341     return false;
5342   }
5343
5344   return HasSubOverflow(cast<ConstantInt>(Result),
5345                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5346                         IsSigned);
5347 }
5348
5349 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5350 /// code necessary to compute the offset from the base pointer (without adding
5351 /// in the base pointer).  Return the result as a signed integer of intptr size.
5352 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5353   TargetData &TD = IC.getTargetData();
5354   gep_type_iterator GTI = gep_type_begin(GEP);
5355   const Type *IntPtrTy = TD.getIntPtrType();
5356   LLVMContext *Context = IC.getContext();
5357   Value *Result = Context->getNullValue(IntPtrTy);
5358
5359   // Build a mask for high order bits.
5360   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5361   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5362
5363   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5364        ++i, ++GTI) {
5365     Value *Op = *i;
5366     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5367     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5368       if (OpC->isZero()) continue;
5369       
5370       // Handle a struct index, which adds its field offset to the pointer.
5371       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5372         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5373         
5374         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5375           Result = 
5376              Context->getConstantInt(RC->getValue() + APInt(IntPtrWidth, Size));
5377         else
5378           Result = IC.InsertNewInstBefore(
5379                    BinaryOperator::CreateAdd(Result,
5380                                         Context->getConstantInt(IntPtrTy, Size),
5381                                              GEP->getName()+".offs"), I);
5382         continue;
5383       }
5384       
5385       Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5386       Constant *OC =
5387               Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5388       Scale = Context->getConstantExprMul(OC, Scale);
5389       if (Constant *RC = dyn_cast<Constant>(Result))
5390         Result = Context->getConstantExprAdd(RC, Scale);
5391       else {
5392         // Emit an add instruction.
5393         Result = IC.InsertNewInstBefore(
5394            BinaryOperator::CreateAdd(Result, Scale,
5395                                      GEP->getName()+".offs"), I);
5396       }
5397       continue;
5398     }
5399     // Convert to correct type.
5400     if (Op->getType() != IntPtrTy) {
5401       if (Constant *OpC = dyn_cast<Constant>(Op))
5402         Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
5403       else
5404         Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5405                                                                 true,
5406                                                       Op->getName()+".c"), I);
5407     }
5408     if (Size != 1) {
5409       Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5410       if (Constant *OpC = dyn_cast<Constant>(Op))
5411         Op = Context->getConstantExprMul(OpC, Scale);
5412       else    // We'll let instcombine(mul) convert this to a shl if possible.
5413         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5414                                                   GEP->getName()+".idx"), I);
5415     }
5416
5417     // Emit an add instruction.
5418     if (isa<Constant>(Op) && isa<Constant>(Result))
5419       Result = Context->getConstantExprAdd(cast<Constant>(Op),
5420                                     cast<Constant>(Result));
5421     else
5422       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5423                                                   GEP->getName()+".offs"), I);
5424   }
5425   return Result;
5426 }
5427
5428
5429 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5430 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
5431 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
5432 /// be complex, and scales are involved.  The above expression would also be
5433 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5434 /// This later form is less amenable to optimization though, and we are allowed
5435 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5436 ///
5437 /// If we can't emit an optimized form for this expression, this returns null.
5438 /// 
5439 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5440                                           InstCombiner &IC) {
5441   TargetData &TD = IC.getTargetData();
5442   gep_type_iterator GTI = gep_type_begin(GEP);
5443
5444   // Check to see if this gep only has a single variable index.  If so, and if
5445   // any constant indices are a multiple of its scale, then we can compute this
5446   // in terms of the scale of the variable index.  For example, if the GEP
5447   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5448   // because the expression will cross zero at the same point.
5449   unsigned i, e = GEP->getNumOperands();
5450   int64_t Offset = 0;
5451   for (i = 1; i != e; ++i, ++GTI) {
5452     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5453       // Compute the aggregate offset of constant indices.
5454       if (CI->isZero()) continue;
5455
5456       // Handle a struct index, which adds its field offset to the pointer.
5457       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5458         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5459       } else {
5460         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5461         Offset += Size*CI->getSExtValue();
5462       }
5463     } else {
5464       // Found our variable index.
5465       break;
5466     }
5467   }
5468   
5469   // If there are no variable indices, we must have a constant offset, just
5470   // evaluate it the general way.
5471   if (i == e) return 0;
5472   
5473   Value *VariableIdx = GEP->getOperand(i);
5474   // Determine the scale factor of the variable element.  For example, this is
5475   // 4 if the variable index is into an array of i32.
5476   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5477   
5478   // Verify that there are no other variable indices.  If so, emit the hard way.
5479   for (++i, ++GTI; i != e; ++i, ++GTI) {
5480     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5481     if (!CI) return 0;
5482    
5483     // Compute the aggregate offset of constant indices.
5484     if (CI->isZero()) continue;
5485     
5486     // Handle a struct index, which adds its field offset to the pointer.
5487     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5488       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5489     } else {
5490       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5491       Offset += Size*CI->getSExtValue();
5492     }
5493   }
5494   
5495   // Okay, we know we have a single variable index, which must be a
5496   // pointer/array/vector index.  If there is no offset, life is simple, return
5497   // the index.
5498   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5499   if (Offset == 0) {
5500     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5501     // we don't need to bother extending: the extension won't affect where the
5502     // computation crosses zero.
5503     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5504       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5505                                   VariableIdx->getNameStart(), &I);
5506     return VariableIdx;
5507   }
5508   
5509   // Otherwise, there is an index.  The computation we will do will be modulo
5510   // the pointer size, so get it.
5511   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5512   
5513   Offset &= PtrSizeMask;
5514   VariableScale &= PtrSizeMask;
5515
5516   // To do this transformation, any constant index must be a multiple of the
5517   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5518   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5519   // multiple of the variable scale.
5520   int64_t NewOffs = Offset / (int64_t)VariableScale;
5521   if (Offset != NewOffs*(int64_t)VariableScale)
5522     return 0;
5523
5524   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5525   const Type *IntPtrTy = TD.getIntPtrType();
5526   if (VariableIdx->getType() != IntPtrTy)
5527     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5528                                               true /*SExt*/, 
5529                                               VariableIdx->getNameStart(), &I);
5530   Constant *OffsetVal = IC.getContext()->getConstantInt(IntPtrTy, NewOffs);
5531   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5532 }
5533
5534
5535 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5536 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5537 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5538                                        ICmpInst::Predicate Cond,
5539                                        Instruction &I) {
5540   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5541
5542   // Look through bitcasts.
5543   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5544     RHS = BCI->getOperand(0);
5545
5546   Value *PtrBase = GEPLHS->getOperand(0);
5547   if (PtrBase == RHS) {
5548     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5549     // This transformation (ignoring the base and scales) is valid because we
5550     // know pointers can't overflow.  See if we can output an optimized form.
5551     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5552     
5553     // If not, synthesize the offset the hard way.
5554     if (Offset == 0)
5555       Offset = EmitGEPOffset(GEPLHS, I, *this);
5556     return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
5557                         Context->getNullValue(Offset->getType()));
5558   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5559     // If the base pointers are different, but the indices are the same, just
5560     // compare the base pointer.
5561     if (PtrBase != GEPRHS->getOperand(0)) {
5562       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5563       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5564                         GEPRHS->getOperand(0)->getType();
5565       if (IndicesTheSame)
5566         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5567           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5568             IndicesTheSame = false;
5569             break;
5570           }
5571
5572       // If all indices are the same, just compare the base pointers.
5573       if (IndicesTheSame)
5574         return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), 
5575                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5576
5577       // Otherwise, the base pointers are different and the indices are
5578       // different, bail out.
5579       return 0;
5580     }
5581
5582     // If one of the GEPs has all zero indices, recurse.
5583     bool AllZeros = true;
5584     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5585       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5586           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5587         AllZeros = false;
5588         break;
5589       }
5590     if (AllZeros)
5591       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5592                           ICmpInst::getSwappedPredicate(Cond), I);
5593
5594     // If the other GEP has all zero indices, recurse.
5595     AllZeros = true;
5596     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5597       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5598           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5599         AllZeros = false;
5600         break;
5601       }
5602     if (AllZeros)
5603       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5604
5605     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5606       // If the GEPs only differ by one index, compare it.
5607       unsigned NumDifferences = 0;  // Keep track of # differences.
5608       unsigned DiffOperand = 0;     // The operand that differs.
5609       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5610         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5611           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5612                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5613             // Irreconcilable differences.
5614             NumDifferences = 2;
5615             break;
5616           } else {
5617             if (NumDifferences++) break;
5618             DiffOperand = i;
5619           }
5620         }
5621
5622       if (NumDifferences == 0)   // SAME GEP?
5623         return ReplaceInstUsesWith(I, // No comparison is needed here.
5624                                    Context->getConstantInt(Type::Int1Ty,
5625                                              ICmpInst::isTrueWhenEqual(Cond)));
5626
5627       else if (NumDifferences == 1) {
5628         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5629         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5630         // Make sure we do a signed comparison here.
5631         return new ICmpInst(*Context,
5632                             ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5633       }
5634     }
5635
5636     // Only lower this if the icmp is the only user of the GEP or if we expect
5637     // the result to fold to a constant!
5638     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5639         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5640       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5641       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5642       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5643       return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
5644     }
5645   }
5646   return 0;
5647 }
5648
5649 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5650 ///
5651 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5652                                                 Instruction *LHSI,
5653                                                 Constant *RHSC) {
5654   if (!isa<ConstantFP>(RHSC)) return 0;
5655   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5656   
5657   // Get the width of the mantissa.  We don't want to hack on conversions that
5658   // might lose information from the integer, e.g. "i64 -> float"
5659   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5660   if (MantissaWidth == -1) return 0;  // Unknown.
5661   
5662   // Check to see that the input is converted from an integer type that is small
5663   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5664   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5665   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5666   
5667   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5668   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5669   if (LHSUnsigned)
5670     ++InputSize;
5671   
5672   // If the conversion would lose info, don't hack on this.
5673   if ((int)InputSize > MantissaWidth)
5674     return 0;
5675   
5676   // Otherwise, we can potentially simplify the comparison.  We know that it
5677   // will always come through as an integer value and we know the constant is
5678   // not a NAN (it would have been previously simplified).
5679   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5680   
5681   ICmpInst::Predicate Pred;
5682   switch (I.getPredicate()) {
5683   default: llvm_unreachable("Unexpected predicate!");
5684   case FCmpInst::FCMP_UEQ:
5685   case FCmpInst::FCMP_OEQ:
5686     Pred = ICmpInst::ICMP_EQ;
5687     break;
5688   case FCmpInst::FCMP_UGT:
5689   case FCmpInst::FCMP_OGT:
5690     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5691     break;
5692   case FCmpInst::FCMP_UGE:
5693   case FCmpInst::FCMP_OGE:
5694     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5695     break;
5696   case FCmpInst::FCMP_ULT:
5697   case FCmpInst::FCMP_OLT:
5698     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5699     break;
5700   case FCmpInst::FCMP_ULE:
5701   case FCmpInst::FCMP_OLE:
5702     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5703     break;
5704   case FCmpInst::FCMP_UNE:
5705   case FCmpInst::FCMP_ONE:
5706     Pred = ICmpInst::ICMP_NE;
5707     break;
5708   case FCmpInst::FCMP_ORD:
5709     return ReplaceInstUsesWith(I, Context->getTrue());
5710   case FCmpInst::FCMP_UNO:
5711     return ReplaceInstUsesWith(I, Context->getFalse());
5712   }
5713   
5714   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5715   
5716   // Now we know that the APFloat is a normal number, zero or inf.
5717   
5718   // See if the FP constant is too large for the integer.  For example,
5719   // comparing an i8 to 300.0.
5720   unsigned IntWidth = IntTy->getScalarSizeInBits();
5721   
5722   if (!LHSUnsigned) {
5723     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5724     // and large values.
5725     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5726     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5727                           APFloat::rmNearestTiesToEven);
5728     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5729       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5730           Pred == ICmpInst::ICMP_SLE)
5731         return ReplaceInstUsesWith(I, Context->getTrue());
5732       return ReplaceInstUsesWith(I, Context->getFalse());
5733     }
5734   } else {
5735     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5736     // +INF and large values.
5737     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5738     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5739                           APFloat::rmNearestTiesToEven);
5740     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5741       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5742           Pred == ICmpInst::ICMP_ULE)
5743         return ReplaceInstUsesWith(I, Context->getTrue());
5744       return ReplaceInstUsesWith(I, Context->getFalse());
5745     }
5746   }
5747   
5748   if (!LHSUnsigned) {
5749     // See if the RHS value is < SignedMin.
5750     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5751     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5752                           APFloat::rmNearestTiesToEven);
5753     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5754       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5755           Pred == ICmpInst::ICMP_SGE)
5756         return ReplaceInstUsesWith(I, Context->getTrue());
5757       return ReplaceInstUsesWith(I, Context->getFalse());
5758     }
5759   }
5760
5761   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5762   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5763   // casting the FP value to the integer value and back, checking for equality.
5764   // Don't do this for zero, because -0.0 is not fractional.
5765   Constant *RHSInt = LHSUnsigned
5766     ? Context->getConstantExprFPToUI(RHSC, IntTy)
5767     : Context->getConstantExprFPToSI(RHSC, IntTy);
5768   if (!RHS.isZero()) {
5769     bool Equal = LHSUnsigned
5770       ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5771       : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
5772     if (!Equal) {
5773       // If we had a comparison against a fractional value, we have to adjust
5774       // the compare predicate and sometimes the value.  RHSC is rounded towards
5775       // zero at this point.
5776       switch (Pred) {
5777       default: llvm_unreachable("Unexpected integer comparison!");
5778       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5779         return ReplaceInstUsesWith(I, Context->getTrue());
5780       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5781         return ReplaceInstUsesWith(I, Context->getFalse());
5782       case ICmpInst::ICMP_ULE:
5783         // (float)int <= 4.4   --> int <= 4
5784         // (float)int <= -4.4  --> false
5785         if (RHS.isNegative())
5786           return ReplaceInstUsesWith(I, Context->getFalse());
5787         break;
5788       case ICmpInst::ICMP_SLE:
5789         // (float)int <= 4.4   --> int <= 4
5790         // (float)int <= -4.4  --> int < -4
5791         if (RHS.isNegative())
5792           Pred = ICmpInst::ICMP_SLT;
5793         break;
5794       case ICmpInst::ICMP_ULT:
5795         // (float)int < -4.4   --> false
5796         // (float)int < 4.4    --> int <= 4
5797         if (RHS.isNegative())
5798           return ReplaceInstUsesWith(I, Context->getFalse());
5799         Pred = ICmpInst::ICMP_ULE;
5800         break;
5801       case ICmpInst::ICMP_SLT:
5802         // (float)int < -4.4   --> int < -4
5803         // (float)int < 4.4    --> int <= 4
5804         if (!RHS.isNegative())
5805           Pred = ICmpInst::ICMP_SLE;
5806         break;
5807       case ICmpInst::ICMP_UGT:
5808         // (float)int > 4.4    --> int > 4
5809         // (float)int > -4.4   --> true
5810         if (RHS.isNegative())
5811           return ReplaceInstUsesWith(I, Context->getTrue());
5812         break;
5813       case ICmpInst::ICMP_SGT:
5814         // (float)int > 4.4    --> int > 4
5815         // (float)int > -4.4   --> int >= -4
5816         if (RHS.isNegative())
5817           Pred = ICmpInst::ICMP_SGE;
5818         break;
5819       case ICmpInst::ICMP_UGE:
5820         // (float)int >= -4.4   --> true
5821         // (float)int >= 4.4    --> int > 4
5822         if (!RHS.isNegative())
5823           return ReplaceInstUsesWith(I, Context->getTrue());
5824         Pred = ICmpInst::ICMP_UGT;
5825         break;
5826       case ICmpInst::ICMP_SGE:
5827         // (float)int >= -4.4   --> int >= -4
5828         // (float)int >= 4.4    --> int > 4
5829         if (!RHS.isNegative())
5830           Pred = ICmpInst::ICMP_SGT;
5831         break;
5832       }
5833     }
5834   }
5835
5836   // Lower this FP comparison into an appropriate integer version of the
5837   // comparison.
5838   return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
5839 }
5840
5841 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5842   bool Changed = SimplifyCompare(I);
5843   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5844
5845   // Fold trivial predicates.
5846   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5847     return ReplaceInstUsesWith(I, Context->getFalse());
5848   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5849     return ReplaceInstUsesWith(I, Context->getTrue());
5850   
5851   // Simplify 'fcmp pred X, X'
5852   if (Op0 == Op1) {
5853     switch (I.getPredicate()) {
5854     default: llvm_unreachable("Unknown predicate!");
5855     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5856     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5857     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5858       return ReplaceInstUsesWith(I, Context->getTrue());
5859     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5860     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5861     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5862       return ReplaceInstUsesWith(I, Context->getFalse());
5863       
5864     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5865     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5866     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5867     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5868       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5869       I.setPredicate(FCmpInst::FCMP_UNO);
5870       I.setOperand(1, Context->getNullValue(Op0->getType()));
5871       return &I;
5872       
5873     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5874     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5875     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5876     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5877       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5878       I.setPredicate(FCmpInst::FCMP_ORD);
5879       I.setOperand(1, Context->getNullValue(Op0->getType()));
5880       return &I;
5881     }
5882   }
5883     
5884   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5885     return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5886
5887   // Handle fcmp with constant RHS
5888   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5889     // If the constant is a nan, see if we can fold the comparison based on it.
5890     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5891       if (CFP->getValueAPF().isNaN()) {
5892         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5893           return ReplaceInstUsesWith(I, Context->getFalse());
5894         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5895                "Comparison must be either ordered or unordered!");
5896         // True if unordered.
5897         return ReplaceInstUsesWith(I, Context->getTrue());
5898       }
5899     }
5900     
5901     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5902       switch (LHSI->getOpcode()) {
5903       case Instruction::PHI:
5904         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5905         // block.  If in the same block, we're encouraging jump threading.  If
5906         // not, we are just pessimizing the code by making an i1 phi.
5907         if (LHSI->getParent() == I.getParent())
5908           if (Instruction *NV = FoldOpIntoPhi(I))
5909             return NV;
5910         break;
5911       case Instruction::SIToFP:
5912       case Instruction::UIToFP:
5913         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5914           return NV;
5915         break;
5916       case Instruction::Select:
5917         // If either operand of the select is a constant, we can fold the
5918         // comparison into the select arms, which will cause one to be
5919         // constant folded and the select turned into a bitwise or.
5920         Value *Op1 = 0, *Op2 = 0;
5921         if (LHSI->hasOneUse()) {
5922           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5923             // Fold the known value into the constant operand.
5924             Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5925             // Insert a new FCmp of the other select operand.
5926             Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5927                                                       LHSI->getOperand(2), RHSC,
5928                                                       I.getName()), I);
5929           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5930             // Fold the known value into the constant operand.
5931             Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5932             // Insert a new FCmp of the other select operand.
5933             Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5934                                                       LHSI->getOperand(1), RHSC,
5935                                                       I.getName()), I);
5936           }
5937         }
5938
5939         if (Op1)
5940           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5941         break;
5942       }
5943   }
5944
5945   return Changed ? &I : 0;
5946 }
5947
5948 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5949   bool Changed = SimplifyCompare(I);
5950   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5951   const Type *Ty = Op0->getType();
5952
5953   // icmp X, X
5954   if (Op0 == Op1)
5955     return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty, 
5956                                                    I.isTrueWhenEqual()));
5957
5958   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5959     return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5960   
5961   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5962   // addresses never equal each other!  We already know that Op0 != Op1.
5963   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5964        isa<ConstantPointerNull>(Op0)) &&
5965       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5966        isa<ConstantPointerNull>(Op1)))
5967     return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty, 
5968                                                    !I.isTrueWhenEqual()));
5969
5970   // icmp's with boolean values can always be turned into bitwise operations
5971   if (Ty == Type::Int1Ty) {
5972     switch (I.getPredicate()) {
5973     default: llvm_unreachable("Invalid icmp instruction!");
5974     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5975       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5976       InsertNewInstBefore(Xor, I);
5977       return BinaryOperator::CreateNot(*Context, Xor);
5978     }
5979     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5980       return BinaryOperator::CreateXor(Op0, Op1);
5981
5982     case ICmpInst::ICMP_UGT:
5983       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5984       // FALL THROUGH
5985     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5986       Instruction *Not = BinaryOperator::CreateNot(*Context,
5987                                                    Op0, I.getName()+"tmp");
5988       InsertNewInstBefore(Not, I);
5989       return BinaryOperator::CreateAnd(Not, Op1);
5990     }
5991     case ICmpInst::ICMP_SGT:
5992       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5993       // FALL THROUGH
5994     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5995       Instruction *Not = BinaryOperator::CreateNot(*Context, 
5996                                                    Op1, I.getName()+"tmp");
5997       InsertNewInstBefore(Not, I);
5998       return BinaryOperator::CreateAnd(Not, Op0);
5999     }
6000     case ICmpInst::ICMP_UGE:
6001       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6002       // FALL THROUGH
6003     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6004       Instruction *Not = BinaryOperator::CreateNot(*Context,
6005                                                    Op0, I.getName()+"tmp");
6006       InsertNewInstBefore(Not, I);
6007       return BinaryOperator::CreateOr(Not, Op1);
6008     }
6009     case ICmpInst::ICMP_SGE:
6010       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6011       // FALL THROUGH
6012     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6013       Instruction *Not = BinaryOperator::CreateNot(*Context,
6014                                                    Op1, I.getName()+"tmp");
6015       InsertNewInstBefore(Not, I);
6016       return BinaryOperator::CreateOr(Not, Op0);
6017     }
6018     }
6019   }
6020
6021   unsigned BitWidth = 0;
6022   if (TD)
6023     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6024   else if (Ty->isIntOrIntVector())
6025     BitWidth = Ty->getScalarSizeInBits();
6026
6027   bool isSignBit = false;
6028
6029   // See if we are doing a comparison with a constant.
6030   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6031     Value *A = 0, *B = 0;
6032     
6033     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6034     if (I.isEquality() && CI->isNullValue() &&
6035         match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
6036       // (icmp cond A B) if cond is equality
6037       return new ICmpInst(*Context, I.getPredicate(), A, B);
6038     }
6039     
6040     // If we have an icmp le or icmp ge instruction, turn it into the
6041     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6042     // them being folded in the code below.
6043     switch (I.getPredicate()) {
6044     default: break;
6045     case ICmpInst::ICMP_ULE:
6046       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
6047         return ReplaceInstUsesWith(I, Context->getTrue());
6048       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6049                           AddOne(CI, Context));
6050     case ICmpInst::ICMP_SLE:
6051       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
6052         return ReplaceInstUsesWith(I, Context->getTrue());
6053       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6054                           AddOne(CI, Context));
6055     case ICmpInst::ICMP_UGE:
6056       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
6057         return ReplaceInstUsesWith(I, Context->getTrue());
6058       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6059                           SubOne(CI, Context));
6060     case ICmpInst::ICMP_SGE:
6061       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
6062         return ReplaceInstUsesWith(I, Context->getTrue());
6063       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6064                           SubOne(CI, Context));
6065     }
6066     
6067     // If this comparison is a normal comparison, it demands all
6068     // bits, if it is a sign bit comparison, it only demands the sign bit.
6069     bool UnusedBit;
6070     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6071   }
6072
6073   // See if we can fold the comparison based on range information we can get
6074   // by checking whether bits are known to be zero or one in the input.
6075   if (BitWidth != 0) {
6076     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6077     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6078
6079     if (SimplifyDemandedBits(I.getOperandUse(0),
6080                              isSignBit ? APInt::getSignBit(BitWidth)
6081                                        : APInt::getAllOnesValue(BitWidth),
6082                              Op0KnownZero, Op0KnownOne, 0))
6083       return &I;
6084     if (SimplifyDemandedBits(I.getOperandUse(1),
6085                              APInt::getAllOnesValue(BitWidth),
6086                              Op1KnownZero, Op1KnownOne, 0))
6087       return &I;
6088
6089     // Given the known and unknown bits, compute a range that the LHS could be
6090     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6091     // EQ and NE we use unsigned values.
6092     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6093     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6094     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6095       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6096                                              Op0Min, Op0Max);
6097       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6098                                              Op1Min, Op1Max);
6099     } else {
6100       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6101                                                Op0Min, Op0Max);
6102       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6103                                                Op1Min, Op1Max);
6104     }
6105
6106     // If Min and Max are known to be the same, then SimplifyDemandedBits
6107     // figured out that the LHS is a constant.  Just constant fold this now so
6108     // that code below can assume that Min != Max.
6109     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6110       return new ICmpInst(*Context, I.getPredicate(),
6111                           Context->getConstantInt(Op0Min), Op1);
6112     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6113       return new ICmpInst(*Context, I.getPredicate(), Op0, 
6114                           Context->getConstantInt(Op1Min));
6115
6116     // Based on the range information we know about the LHS, see if we can
6117     // simplify this comparison.  For example, (x&4) < 8  is always true.
6118     switch (I.getPredicate()) {
6119     default: llvm_unreachable("Unknown icmp opcode!");
6120     case ICmpInst::ICMP_EQ:
6121       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6122         return ReplaceInstUsesWith(I, Context->getFalse());
6123       break;
6124     case ICmpInst::ICMP_NE:
6125       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6126         return ReplaceInstUsesWith(I, Context->getTrue());
6127       break;
6128     case ICmpInst::ICMP_ULT:
6129       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6130         return ReplaceInstUsesWith(I, Context->getTrue());
6131       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6132         return ReplaceInstUsesWith(I, Context->getFalse());
6133       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6134         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6135       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6136         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6137           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6138                               SubOne(CI, Context));
6139
6140         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6141         if (CI->isMinValue(true))
6142           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6143                            Context->getAllOnesValue(Op0->getType()));
6144       }
6145       break;
6146     case ICmpInst::ICMP_UGT:
6147       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6148         return ReplaceInstUsesWith(I, Context->getTrue());
6149       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6150         return ReplaceInstUsesWith(I, Context->getFalse());
6151
6152       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6153         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6154       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6155         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6156           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6157                               AddOne(CI, Context));
6158
6159         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6160         if (CI->isMaxValue(true))
6161           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6162                               Context->getNullValue(Op0->getType()));
6163       }
6164       break;
6165     case ICmpInst::ICMP_SLT:
6166       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6167         return ReplaceInstUsesWith(I, Context->getTrue());
6168       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6169         return ReplaceInstUsesWith(I, Context->getFalse());
6170       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6171         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6172       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6173         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6174           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6175                               SubOne(CI, Context));
6176       }
6177       break;
6178     case ICmpInst::ICMP_SGT:
6179       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6180         return ReplaceInstUsesWith(I, Context->getTrue());
6181       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6182         return ReplaceInstUsesWith(I, Context->getFalse());
6183
6184       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6185         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6186       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6187         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6188           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6189                               AddOne(CI, Context));
6190       }
6191       break;
6192     case ICmpInst::ICMP_SGE:
6193       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6194       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6195         return ReplaceInstUsesWith(I, Context->getTrue());
6196       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6197         return ReplaceInstUsesWith(I, Context->getFalse());
6198       break;
6199     case ICmpInst::ICMP_SLE:
6200       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6201       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6202         return ReplaceInstUsesWith(I, Context->getTrue());
6203       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6204         return ReplaceInstUsesWith(I, Context->getFalse());
6205       break;
6206     case ICmpInst::ICMP_UGE:
6207       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6208       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6209         return ReplaceInstUsesWith(I, Context->getTrue());
6210       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6211         return ReplaceInstUsesWith(I, Context->getFalse());
6212       break;
6213     case ICmpInst::ICMP_ULE:
6214       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6215       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6216         return ReplaceInstUsesWith(I, Context->getTrue());
6217       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6218         return ReplaceInstUsesWith(I, Context->getFalse());
6219       break;
6220     }
6221
6222     // Turn a signed comparison into an unsigned one if both operands
6223     // are known to have the same sign.
6224     if (I.isSignedPredicate() &&
6225         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6226          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6227       return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
6228   }
6229
6230   // Test if the ICmpInst instruction is used exclusively by a select as
6231   // part of a minimum or maximum operation. If so, refrain from doing
6232   // any other folding. This helps out other analyses which understand
6233   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6234   // and CodeGen. And in this case, at least one of the comparison
6235   // operands has at least one user besides the compare (the select),
6236   // which would often largely negate the benefit of folding anyway.
6237   if (I.hasOneUse())
6238     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6239       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6240           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6241         return 0;
6242
6243   // See if we are doing a comparison between a constant and an instruction that
6244   // can be folded into the comparison.
6245   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6246     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6247     // instruction, see if that instruction also has constants so that the 
6248     // instruction can be folded into the icmp 
6249     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6250       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6251         return Res;
6252   }
6253
6254   // Handle icmp with constant (but not simple integer constant) RHS
6255   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6256     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6257       switch (LHSI->getOpcode()) {
6258       case Instruction::GetElementPtr:
6259         if (RHSC->isNullValue()) {
6260           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6261           bool isAllZeros = true;
6262           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6263             if (!isa<Constant>(LHSI->getOperand(i)) ||
6264                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6265               isAllZeros = false;
6266               break;
6267             }
6268           if (isAllZeros)
6269             return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
6270                     Context->getNullValue(LHSI->getOperand(0)->getType()));
6271         }
6272         break;
6273
6274       case Instruction::PHI:
6275         // Only fold icmp into the PHI if the phi and fcmp are in the same
6276         // block.  If in the same block, we're encouraging jump threading.  If
6277         // not, we are just pessimizing the code by making an i1 phi.
6278         if (LHSI->getParent() == I.getParent())
6279           if (Instruction *NV = FoldOpIntoPhi(I))
6280             return NV;
6281         break;
6282       case Instruction::Select: {
6283         // If either operand of the select is a constant, we can fold the
6284         // comparison into the select arms, which will cause one to be
6285         // constant folded and the select turned into a bitwise or.
6286         Value *Op1 = 0, *Op2 = 0;
6287         if (LHSI->hasOneUse()) {
6288           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6289             // Fold the known value into the constant operand.
6290             Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6291             // Insert a new ICmp of the other select operand.
6292             Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6293                                                    LHSI->getOperand(2), RHSC,
6294                                                    I.getName()), I);
6295           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6296             // Fold the known value into the constant operand.
6297             Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6298             // Insert a new ICmp of the other select operand.
6299             Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6300                                                    LHSI->getOperand(1), RHSC,
6301                                                    I.getName()), I);
6302           }
6303         }
6304
6305         if (Op1)
6306           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6307         break;
6308       }
6309       case Instruction::Malloc:
6310         // If we have (malloc != null), and if the malloc has a single use, we
6311         // can assume it is successful and remove the malloc.
6312         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6313           AddToWorkList(LHSI);
6314           return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
6315                                                          !I.isTrueWhenEqual()));
6316         }
6317         break;
6318       }
6319   }
6320
6321   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6322   if (User *GEP = dyn_castGetElementPtr(Op0))
6323     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6324       return NI;
6325   if (User *GEP = dyn_castGetElementPtr(Op1))
6326     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6327                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6328       return NI;
6329
6330   // Test to see if the operands of the icmp are casted versions of other
6331   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6332   // now.
6333   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6334     if (isa<PointerType>(Op0->getType()) && 
6335         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6336       // We keep moving the cast from the left operand over to the right
6337       // operand, where it can often be eliminated completely.
6338       Op0 = CI->getOperand(0);
6339
6340       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6341       // so eliminate it as well.
6342       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6343         Op1 = CI2->getOperand(0);
6344
6345       // If Op1 is a constant, we can fold the cast into the constant.
6346       if (Op0->getType() != Op1->getType()) {
6347         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6348           Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
6349         } else {
6350           // Otherwise, cast the RHS right before the icmp
6351           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6352         }
6353       }
6354       return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
6355     }
6356   }
6357   
6358   if (isa<CastInst>(Op0)) {
6359     // Handle the special case of: icmp (cast bool to X), <cst>
6360     // This comes up when you have code like
6361     //   int X = A < B;
6362     //   if (X) ...
6363     // For generality, we handle any zero-extension of any operand comparison
6364     // with a constant or another cast from the same type.
6365     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6366       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6367         return R;
6368   }
6369   
6370   // See if it's the same type of instruction on the left and right.
6371   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6372     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6373       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6374           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6375         switch (Op0I->getOpcode()) {
6376         default: break;
6377         case Instruction::Add:
6378         case Instruction::Sub:
6379         case Instruction::Xor:
6380           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6381             return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
6382                                 Op1I->getOperand(0));
6383           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6384           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6385             if (CI->getValue().isSignBit()) {
6386               ICmpInst::Predicate Pred = I.isSignedPredicate()
6387                                              ? I.getUnsignedPredicate()
6388                                              : I.getSignedPredicate();
6389               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6390                                   Op1I->getOperand(0));
6391             }
6392             
6393             if (CI->getValue().isMaxSignedValue()) {
6394               ICmpInst::Predicate Pred = I.isSignedPredicate()
6395                                              ? I.getUnsignedPredicate()
6396                                              : I.getSignedPredicate();
6397               Pred = I.getSwappedPredicate(Pred);
6398               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6399                                   Op1I->getOperand(0));
6400             }
6401           }
6402           break;
6403         case Instruction::Mul:
6404           if (!I.isEquality())
6405             break;
6406
6407           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6408             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6409             // Mask = -1 >> count-trailing-zeros(Cst).
6410             if (!CI->isZero() && !CI->isOne()) {
6411               const APInt &AP = CI->getValue();
6412               ConstantInt *Mask = Context->getConstantInt(
6413                                       APInt::getLowBitsSet(AP.getBitWidth(),
6414                                                            AP.getBitWidth() -
6415                                                       AP.countTrailingZeros()));
6416               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6417                                                             Mask);
6418               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6419                                                             Mask);
6420               InsertNewInstBefore(And1, I);
6421               InsertNewInstBefore(And2, I);
6422               return new ICmpInst(*Context, I.getPredicate(), And1, And2);
6423             }
6424           }
6425           break;
6426         }
6427       }
6428     }
6429   }
6430   
6431   // ~x < ~y --> y < x
6432   { Value *A, *B;
6433     if (match(Op0, m_Not(m_Value(A)), *Context) &&
6434         match(Op1, m_Not(m_Value(B)), *Context))
6435       return new ICmpInst(*Context, I.getPredicate(), B, A);
6436   }
6437   
6438   if (I.isEquality()) {
6439     Value *A, *B, *C, *D;
6440     
6441     // -x == -y --> x == y
6442     if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6443         match(Op1, m_Neg(m_Value(B)), *Context))
6444       return new ICmpInst(*Context, I.getPredicate(), A, B);
6445     
6446     if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
6447       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6448         Value *OtherVal = A == Op1 ? B : A;
6449         return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6450                             Context->getNullValue(A->getType()));
6451       }
6452
6453       if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
6454         // A^c1 == C^c2 --> A == C^(c1^c2)
6455         ConstantInt *C1, *C2;
6456         if (match(B, m_ConstantInt(C1), *Context) &&
6457             match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
6458           Constant *NC = 
6459                        Context->getConstantInt(C1->getValue() ^ C2->getValue());
6460           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6461           return new ICmpInst(*Context, I.getPredicate(), A,
6462                               InsertNewInstBefore(Xor, I));
6463         }
6464         
6465         // A^B == A^D -> B == D
6466         if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6467         if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6468         if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6469         if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
6470       }
6471     }
6472     
6473     if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
6474         (A == Op0 || B == Op0)) {
6475       // A == (A^B)  ->  B == 0
6476       Value *OtherVal = A == Op0 ? B : A;
6477       return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6478                           Context->getNullValue(A->getType()));
6479     }
6480
6481     // (A-B) == A  ->  B == 0
6482     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
6483       return new ICmpInst(*Context, I.getPredicate(), B, 
6484                           Context->getNullValue(B->getType()));
6485
6486     // A == (A-B)  ->  B == 0
6487     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
6488       return new ICmpInst(*Context, I.getPredicate(), B,
6489                           Context->getNullValue(B->getType()));
6490     
6491     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6492     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6493         match(Op0, m_And(m_Value(A), m_Value(B)), *Context) && 
6494         match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
6495       Value *X = 0, *Y = 0, *Z = 0;
6496       
6497       if (A == C) {
6498         X = B; Y = D; Z = A;
6499       } else if (A == D) {
6500         X = B; Y = C; Z = A;
6501       } else if (B == C) {
6502         X = A; Y = D; Z = B;
6503       } else if (B == D) {
6504         X = A; Y = C; Z = B;
6505       }
6506       
6507       if (X) {   // Build (X^Y) & Z
6508         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6509         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6510         I.setOperand(0, Op1);
6511         I.setOperand(1, Context->getNullValue(Op1->getType()));
6512         return &I;
6513       }
6514     }
6515   }
6516   return Changed ? &I : 0;
6517 }
6518
6519
6520 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6521 /// and CmpRHS are both known to be integer constants.
6522 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6523                                           ConstantInt *DivRHS) {
6524   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6525   const APInt &CmpRHSV = CmpRHS->getValue();
6526   
6527   // FIXME: If the operand types don't match the type of the divide 
6528   // then don't attempt this transform. The code below doesn't have the
6529   // logic to deal with a signed divide and an unsigned compare (and
6530   // vice versa). This is because (x /s C1) <s C2  produces different 
6531   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6532   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6533   // work. :(  The if statement below tests that condition and bails 
6534   // if it finds it. 
6535   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6536   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6537     return 0;
6538   if (DivRHS->isZero())
6539     return 0; // The ProdOV computation fails on divide by zero.
6540   if (DivIsSigned && DivRHS->isAllOnesValue())
6541     return 0; // The overflow computation also screws up here
6542   if (DivRHS->isOne())
6543     return 0; // Not worth bothering, and eliminates some funny cases
6544               // with INT_MIN.
6545
6546   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6547   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6548   // C2 (CI). By solving for X we can turn this into a range check 
6549   // instead of computing a divide. 
6550   Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
6551
6552   // Determine if the product overflows by seeing if the product is
6553   // not equal to the divide. Make sure we do the same kind of divide
6554   // as in the LHS instruction that we're folding. 
6555   bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6556                  Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
6557
6558   // Get the ICmp opcode
6559   ICmpInst::Predicate Pred = ICI.getPredicate();
6560
6561   // Figure out the interval that is being checked.  For example, a comparison
6562   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6563   // Compute this interval based on the constants involved and the signedness of
6564   // the compare/divide.  This computes a half-open interval, keeping track of
6565   // whether either value in the interval overflows.  After analysis each
6566   // overflow variable is set to 0 if it's corresponding bound variable is valid
6567   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6568   int LoOverflow = 0, HiOverflow = 0;
6569   Constant *LoBound = 0, *HiBound = 0;
6570   
6571   if (!DivIsSigned) {  // udiv
6572     // e.g. X/5 op 3  --> [15, 20)
6573     LoBound = Prod;
6574     HiOverflow = LoOverflow = ProdOV;
6575     if (!HiOverflow)
6576       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6577   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6578     if (CmpRHSV == 0) {       // (X / pos) op 0
6579       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6580       LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS, 
6581                                                                     Context)));
6582       HiBound = DivRHS;
6583     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6584       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6585       HiOverflow = LoOverflow = ProdOV;
6586       if (!HiOverflow)
6587         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6588     } else {                       // (X / pos) op neg
6589       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6590       HiBound = AddOne(Prod, Context);
6591       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6592       if (!LoOverflow) {
6593         ConstantInt* DivNeg =
6594                          cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6595         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6596                                      true) ? -1 : 0;
6597        }
6598     }
6599   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6600     if (CmpRHSV == 0) {       // (X / neg) op 0
6601       // e.g. X/-5 op 0  --> [-4, 5)
6602       LoBound = AddOne(DivRHS, Context);
6603       HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6604       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6605         HiOverflow = 1;            // [INTMIN+1, overflow)
6606         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6607       }
6608     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6609       // e.g. X/-5 op 3  --> [-19, -14)
6610       HiBound = AddOne(Prod, Context);
6611       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6612       if (!LoOverflow)
6613         LoOverflow = AddWithOverflow(LoBound, HiBound,
6614                                      DivRHS, Context, true) ? -1 : 0;
6615     } else {                       // (X / neg) op neg
6616       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6617       LoOverflow = HiOverflow = ProdOV;
6618       if (!HiOverflow)
6619         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6620     }
6621     
6622     // Dividing by a negative swaps the condition.  LT <-> GT
6623     Pred = ICmpInst::getSwappedPredicate(Pred);
6624   }
6625
6626   Value *X = DivI->getOperand(0);
6627   switch (Pred) {
6628   default: llvm_unreachable("Unhandled icmp opcode!");
6629   case ICmpInst::ICMP_EQ:
6630     if (LoOverflow && HiOverflow)
6631       return ReplaceInstUsesWith(ICI, Context->getFalse());
6632     else if (HiOverflow)
6633       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6634                           ICmpInst::ICMP_UGE, X, LoBound);
6635     else if (LoOverflow)
6636       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6637                           ICmpInst::ICMP_ULT, X, HiBound);
6638     else
6639       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6640   case ICmpInst::ICMP_NE:
6641     if (LoOverflow && HiOverflow)
6642       return ReplaceInstUsesWith(ICI, Context->getTrue());
6643     else if (HiOverflow)
6644       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6645                           ICmpInst::ICMP_ULT, X, LoBound);
6646     else if (LoOverflow)
6647       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6648                           ICmpInst::ICMP_UGE, X, HiBound);
6649     else
6650       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6651   case ICmpInst::ICMP_ULT:
6652   case ICmpInst::ICMP_SLT:
6653     if (LoOverflow == +1)   // Low bound is greater than input range.
6654       return ReplaceInstUsesWith(ICI, Context->getTrue());
6655     if (LoOverflow == -1)   // Low bound is less than input range.
6656       return ReplaceInstUsesWith(ICI, Context->getFalse());
6657     return new ICmpInst(*Context, Pred, X, LoBound);
6658   case ICmpInst::ICMP_UGT:
6659   case ICmpInst::ICMP_SGT:
6660     if (HiOverflow == +1)       // High bound greater than input range.
6661       return ReplaceInstUsesWith(ICI, Context->getFalse());
6662     else if (HiOverflow == -1)  // High bound less than input range.
6663       return ReplaceInstUsesWith(ICI, Context->getTrue());
6664     if (Pred == ICmpInst::ICMP_UGT)
6665       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
6666     else
6667       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
6668   }
6669 }
6670
6671
6672 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6673 ///
6674 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6675                                                           Instruction *LHSI,
6676                                                           ConstantInt *RHS) {
6677   const APInt &RHSV = RHS->getValue();
6678   
6679   switch (LHSI->getOpcode()) {
6680   case Instruction::Trunc:
6681     if (ICI.isEquality() && LHSI->hasOneUse()) {
6682       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6683       // of the high bits truncated out of x are known.
6684       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6685              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6686       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6687       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6688       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6689       
6690       // If all the high bits are known, we can do this xform.
6691       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6692         // Pull in the high bits from known-ones set.
6693         APInt NewRHS(RHS->getValue());
6694         NewRHS.zext(SrcBits);
6695         NewRHS |= KnownOne;
6696         return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
6697                             Context->getConstantInt(NewRHS));
6698       }
6699     }
6700     break;
6701       
6702   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6703     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6704       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6705       // fold the xor.
6706       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6707           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6708         Value *CompareVal = LHSI->getOperand(0);
6709         
6710         // If the sign bit of the XorCST is not set, there is no change to
6711         // the operation, just stop using the Xor.
6712         if (!XorCST->getValue().isNegative()) {
6713           ICI.setOperand(0, CompareVal);
6714           AddToWorkList(LHSI);
6715           return &ICI;
6716         }
6717         
6718         // Was the old condition true if the operand is positive?
6719         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6720         
6721         // If so, the new one isn't.
6722         isTrueIfPositive ^= true;
6723         
6724         if (isTrueIfPositive)
6725           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
6726                               SubOne(RHS, Context));
6727         else
6728           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
6729                               AddOne(RHS, Context));
6730       }
6731
6732       if (LHSI->hasOneUse()) {
6733         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6734         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6735           const APInt &SignBit = XorCST->getValue();
6736           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6737                                          ? ICI.getUnsignedPredicate()
6738                                          : ICI.getSignedPredicate();
6739           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6740                               Context->getConstantInt(RHSV ^ SignBit));
6741         }
6742
6743         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6744         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6745           const APInt &NotSignBit = XorCST->getValue();
6746           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6747                                          ? ICI.getUnsignedPredicate()
6748                                          : ICI.getSignedPredicate();
6749           Pred = ICI.getSwappedPredicate(Pred);
6750           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6751                               Context->getConstantInt(RHSV ^ NotSignBit));
6752         }
6753       }
6754     }
6755     break;
6756   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6757     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6758         LHSI->getOperand(0)->hasOneUse()) {
6759       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6760       
6761       // If the LHS is an AND of a truncating cast, we can widen the
6762       // and/compare to be the input width without changing the value
6763       // produced, eliminating a cast.
6764       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6765         // We can do this transformation if either the AND constant does not
6766         // have its sign bit set or if it is an equality comparison. 
6767         // Extending a relational comparison when we're checking the sign
6768         // bit would not work.
6769         if (Cast->hasOneUse() &&
6770             (ICI.isEquality() ||
6771              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6772           uint32_t BitWidth = 
6773             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6774           APInt NewCST = AndCST->getValue();
6775           NewCST.zext(BitWidth);
6776           APInt NewCI = RHSV;
6777           NewCI.zext(BitWidth);
6778           Instruction *NewAnd = 
6779             BinaryOperator::CreateAnd(Cast->getOperand(0),
6780                                Context->getConstantInt(NewCST),LHSI->getName());
6781           InsertNewInstBefore(NewAnd, ICI);
6782           return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
6783                               Context->getConstantInt(NewCI));
6784         }
6785       }
6786       
6787       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6788       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6789       // happens a LOT in code produced by the C front-end, for bitfield
6790       // access.
6791       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6792       if (Shift && !Shift->isShift())
6793         Shift = 0;
6794       
6795       ConstantInt *ShAmt;
6796       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6797       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6798       const Type *AndTy = AndCST->getType();          // Type of the and.
6799       
6800       // We can fold this as long as we can't shift unknown bits
6801       // into the mask.  This can only happen with signed shift
6802       // rights, as they sign-extend.
6803       if (ShAmt) {
6804         bool CanFold = Shift->isLogicalShift();
6805         if (!CanFold) {
6806           // To test for the bad case of the signed shr, see if any
6807           // of the bits shifted in could be tested after the mask.
6808           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6809           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6810           
6811           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6812           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6813                AndCST->getValue()) == 0)
6814             CanFold = true;
6815         }
6816         
6817         if (CanFold) {
6818           Constant *NewCst;
6819           if (Shift->getOpcode() == Instruction::Shl)
6820             NewCst = Context->getConstantExprLShr(RHS, ShAmt);
6821           else
6822             NewCst = Context->getConstantExprShl(RHS, ShAmt);
6823           
6824           // Check to see if we are shifting out any of the bits being
6825           // compared.
6826           if (Context->getConstantExpr(Shift->getOpcode(),
6827                                        NewCst, ShAmt) != RHS) {
6828             // If we shifted bits out, the fold is not going to work out.
6829             // As a special case, check to see if this means that the
6830             // result is always true or false now.
6831             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6832               return ReplaceInstUsesWith(ICI, Context->getFalse());
6833             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6834               return ReplaceInstUsesWith(ICI, Context->getTrue());
6835           } else {
6836             ICI.setOperand(1, NewCst);
6837             Constant *NewAndCST;
6838             if (Shift->getOpcode() == Instruction::Shl)
6839               NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
6840             else
6841               NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
6842             LHSI->setOperand(1, NewAndCST);
6843             LHSI->setOperand(0, Shift->getOperand(0));
6844             AddToWorkList(Shift); // Shift is dead.
6845             AddUsesToWorkList(ICI);
6846             return &ICI;
6847           }
6848         }
6849       }
6850       
6851       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6852       // preferable because it allows the C<<Y expression to be hoisted out
6853       // of a loop if Y is invariant and X is not.
6854       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6855           ICI.isEquality() && !Shift->isArithmeticShift() &&
6856           !isa<Constant>(Shift->getOperand(0))) {
6857         // Compute C << Y.
6858         Value *NS;
6859         if (Shift->getOpcode() == Instruction::LShr) {
6860           NS = BinaryOperator::CreateShl(AndCST, 
6861                                          Shift->getOperand(1), "tmp");
6862         } else {
6863           // Insert a logical shift.
6864           NS = BinaryOperator::CreateLShr(AndCST,
6865                                           Shift->getOperand(1), "tmp");
6866         }
6867         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6868         
6869         // Compute X & (C << Y).
6870         Instruction *NewAnd = 
6871           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6872         InsertNewInstBefore(NewAnd, ICI);
6873         
6874         ICI.setOperand(0, NewAnd);
6875         return &ICI;
6876       }
6877     }
6878     break;
6879     
6880   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6881     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6882     if (!ShAmt) break;
6883     
6884     uint32_t TypeBits = RHSV.getBitWidth();
6885     
6886     // Check that the shift amount is in range.  If not, don't perform
6887     // undefined shifts.  When the shift is visited it will be
6888     // simplified.
6889     if (ShAmt->uge(TypeBits))
6890       break;
6891     
6892     if (ICI.isEquality()) {
6893       // If we are comparing against bits always shifted out, the
6894       // comparison cannot succeed.
6895       Constant *Comp =
6896         Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6897                                                                  ShAmt);
6898       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6899         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6900         Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
6901         return ReplaceInstUsesWith(ICI, Cst);
6902       }
6903       
6904       if (LHSI->hasOneUse()) {
6905         // Otherwise strength reduce the shift into an and.
6906         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6907         Constant *Mask =
6908           Context->getConstantInt(APInt::getLowBitsSet(TypeBits, 
6909                                                        TypeBits-ShAmtVal));
6910         
6911         Instruction *AndI =
6912           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6913                                     Mask, LHSI->getName()+".mask");
6914         Value *And = InsertNewInstBefore(AndI, ICI);
6915         return new ICmpInst(*Context, ICI.getPredicate(), And,
6916                             Context->getConstantInt(RHSV.lshr(ShAmtVal)));
6917       }
6918     }
6919     
6920     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6921     bool TrueIfSigned = false;
6922     if (LHSI->hasOneUse() &&
6923         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6924       // (X << 31) <s 0  --> (X&1) != 0
6925       Constant *Mask = Context->getConstantInt(APInt(TypeBits, 1) <<
6926                                            (TypeBits-ShAmt->getZExtValue()-1));
6927       Instruction *AndI =
6928         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6929                                   Mask, LHSI->getName()+".mask");
6930       Value *And = InsertNewInstBefore(AndI, ICI);
6931       
6932       return new ICmpInst(*Context,
6933                           TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6934                           And, Context->getNullValue(And->getType()));
6935     }
6936     break;
6937   }
6938     
6939   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6940   case Instruction::AShr: {
6941     // Only handle equality comparisons of shift-by-constant.
6942     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6943     if (!ShAmt || !ICI.isEquality()) break;
6944
6945     // Check that the shift amount is in range.  If not, don't perform
6946     // undefined shifts.  When the shift is visited it will be
6947     // simplified.
6948     uint32_t TypeBits = RHSV.getBitWidth();
6949     if (ShAmt->uge(TypeBits))
6950       break;
6951     
6952     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6953       
6954     // If we are comparing against bits always shifted out, the
6955     // comparison cannot succeed.
6956     APInt Comp = RHSV << ShAmtVal;
6957     if (LHSI->getOpcode() == Instruction::LShr)
6958       Comp = Comp.lshr(ShAmtVal);
6959     else
6960       Comp = Comp.ashr(ShAmtVal);
6961     
6962     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6963       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6964       Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
6965       return ReplaceInstUsesWith(ICI, Cst);
6966     }
6967     
6968     // Otherwise, check to see if the bits shifted out are known to be zero.
6969     // If so, we can compare against the unshifted value:
6970     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6971     if (LHSI->hasOneUse() &&
6972         MaskedValueIsZero(LHSI->getOperand(0), 
6973                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6974       return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
6975                           Context->getConstantExprShl(RHS, ShAmt));
6976     }
6977       
6978     if (LHSI->hasOneUse()) {
6979       // Otherwise strength reduce the shift into an and.
6980       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6981       Constant *Mask = Context->getConstantInt(Val);
6982       
6983       Instruction *AndI =
6984         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6985                                   Mask, LHSI->getName()+".mask");
6986       Value *And = InsertNewInstBefore(AndI, ICI);
6987       return new ICmpInst(*Context, ICI.getPredicate(), And,
6988                           Context->getConstantExprShl(RHS, ShAmt));
6989     }
6990     break;
6991   }
6992     
6993   case Instruction::SDiv:
6994   case Instruction::UDiv:
6995     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6996     // Fold this div into the comparison, producing a range check. 
6997     // Determine, based on the divide type, what the range is being 
6998     // checked.  If there is an overflow on the low or high side, remember 
6999     // it, otherwise compute the range [low, hi) bounding the new value.
7000     // See: InsertRangeTest above for the kinds of replacements possible.
7001     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7002       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7003                                           DivRHS))
7004         return R;
7005     break;
7006
7007   case Instruction::Add:
7008     // Fold: icmp pred (add, X, C1), C2
7009
7010     if (!ICI.isEquality()) {
7011       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7012       if (!LHSC) break;
7013       const APInt &LHSV = LHSC->getValue();
7014
7015       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7016                             .subtract(LHSV);
7017
7018       if (ICI.isSignedPredicate()) {
7019         if (CR.getLower().isSignBit()) {
7020           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7021                               Context->getConstantInt(CR.getUpper()));
7022         } else if (CR.getUpper().isSignBit()) {
7023           return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7024                               Context->getConstantInt(CR.getLower()));
7025         }
7026       } else {
7027         if (CR.getLower().isMinValue()) {
7028           return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7029                               Context->getConstantInt(CR.getUpper()));
7030         } else if (CR.getUpper().isMinValue()) {
7031           return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7032                               Context->getConstantInt(CR.getLower()));
7033         }
7034       }
7035     }
7036     break;
7037   }
7038   
7039   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7040   if (ICI.isEquality()) {
7041     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7042     
7043     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7044     // the second operand is a constant, simplify a bit.
7045     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7046       switch (BO->getOpcode()) {
7047       case Instruction::SRem:
7048         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7049         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7050           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7051           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7052             Instruction *NewRem =
7053               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
7054                                          BO->getName());
7055             InsertNewInstBefore(NewRem, ICI);
7056             return new ICmpInst(*Context, ICI.getPredicate(), NewRem, 
7057                                 Context->getNullValue(BO->getType()));
7058           }
7059         }
7060         break;
7061       case Instruction::Add:
7062         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7063         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7064           if (BO->hasOneUse())
7065             return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7066                                 Context->getConstantExprSub(RHS, BOp1C));
7067         } else if (RHSV == 0) {
7068           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7069           // efficiently invertible, or if the add has just this one use.
7070           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7071           
7072           if (Value *NegVal = dyn_castNegVal(BOp1, Context))
7073             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
7074           else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
7075             return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
7076           else if (BO->hasOneUse()) {
7077             Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
7078             InsertNewInstBefore(Neg, ICI);
7079             Neg->takeName(BO);
7080             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
7081           }
7082         }
7083         break;
7084       case Instruction::Xor:
7085         // For the xor case, we can xor two constants together, eliminating
7086         // the explicit xor.
7087         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7088           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0), 
7089                               Context->getConstantExprXor(RHS, BOC));
7090         
7091         // FALLTHROUGH
7092       case Instruction::Sub:
7093         // Replace (([sub|xor] A, B) != 0) with (A != B)
7094         if (RHSV == 0)
7095           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7096                               BO->getOperand(1));
7097         break;
7098         
7099       case Instruction::Or:
7100         // If bits are being or'd in that are not present in the constant we
7101         // are comparing against, then the comparison could never succeed!
7102         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7103           Constant *NotCI = Context->getConstantExprNot(RHS);
7104           if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7105             return ReplaceInstUsesWith(ICI,
7106                                        Context->getConstantInt(Type::Int1Ty, 
7107                                        isICMP_NE));
7108         }
7109         break;
7110         
7111       case Instruction::And:
7112         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7113           // If bits are being compared against that are and'd out, then the
7114           // comparison can never succeed!
7115           if ((RHSV & ~BOC->getValue()) != 0)
7116             return ReplaceInstUsesWith(ICI,
7117                                        Context->getConstantInt(Type::Int1Ty,
7118                                        isICMP_NE));
7119           
7120           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7121           if (RHS == BOC && RHSV.isPowerOf2())
7122             return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
7123                                 ICmpInst::ICMP_NE, LHSI,
7124                                 Context->getNullValue(RHS->getType()));
7125           
7126           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7127           if (BOC->getValue().isSignBit()) {
7128             Value *X = BO->getOperand(0);
7129             Constant *Zero = Context->getNullValue(X->getType());
7130             ICmpInst::Predicate pred = isICMP_NE ? 
7131               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7132             return new ICmpInst(*Context, pred, X, Zero);
7133           }
7134           
7135           // ((X & ~7) == 0) --> X < 8
7136           if (RHSV == 0 && isHighOnes(BOC)) {
7137             Value *X = BO->getOperand(0);
7138             Constant *NegX = Context->getConstantExprNeg(BOC);
7139             ICmpInst::Predicate pred = isICMP_NE ? 
7140               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7141             return new ICmpInst(*Context, pred, X, NegX);
7142           }
7143         }
7144       default: break;
7145       }
7146     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7147       // Handle icmp {eq|ne} <intrinsic>, intcst.
7148       if (II->getIntrinsicID() == Intrinsic::bswap) {
7149         AddToWorkList(II);
7150         ICI.setOperand(0, II->getOperand(1));
7151         ICI.setOperand(1, Context->getConstantInt(RHSV.byteSwap()));
7152         return &ICI;
7153       }
7154     }
7155   }
7156   return 0;
7157 }
7158
7159 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7160 /// We only handle extending casts so far.
7161 ///
7162 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7163   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7164   Value *LHSCIOp        = LHSCI->getOperand(0);
7165   const Type *SrcTy     = LHSCIOp->getType();
7166   const Type *DestTy    = LHSCI->getType();
7167   Value *RHSCIOp;
7168
7169   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7170   // integer type is the same size as the pointer type.
7171   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7172       getTargetData().getPointerSizeInBits() == 
7173          cast<IntegerType>(DestTy)->getBitWidth()) {
7174     Value *RHSOp = 0;
7175     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7176       RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
7177     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7178       RHSOp = RHSC->getOperand(0);
7179       // If the pointer types don't match, insert a bitcast.
7180       if (LHSCIOp->getType() != RHSOp->getType())
7181         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
7182     }
7183
7184     if (RHSOp)
7185       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
7186   }
7187   
7188   // The code below only handles extension cast instructions, so far.
7189   // Enforce this.
7190   if (LHSCI->getOpcode() != Instruction::ZExt &&
7191       LHSCI->getOpcode() != Instruction::SExt)
7192     return 0;
7193
7194   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7195   bool isSignedCmp = ICI.isSignedPredicate();
7196
7197   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7198     // Not an extension from the same type?
7199     RHSCIOp = CI->getOperand(0);
7200     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7201       return 0;
7202     
7203     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7204     // and the other is a zext), then we can't handle this.
7205     if (CI->getOpcode() != LHSCI->getOpcode())
7206       return 0;
7207
7208     // Deal with equality cases early.
7209     if (ICI.isEquality())
7210       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7211
7212     // A signed comparison of sign extended values simplifies into a
7213     // signed comparison.
7214     if (isSignedCmp && isSignedExt)
7215       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7216
7217     // The other three cases all fold into an unsigned comparison.
7218     return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7219   }
7220
7221   // If we aren't dealing with a constant on the RHS, exit early
7222   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7223   if (!CI)
7224     return 0;
7225
7226   // Compute the constant that would happen if we truncated to SrcTy then
7227   // reextended to DestTy.
7228   Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7229   Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7230                                                 Res1, DestTy);
7231
7232   // If the re-extended constant didn't change...
7233   if (Res2 == CI) {
7234     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7235     // For example, we might have:
7236     //    %A = sext i16 %X to i32
7237     //    %B = icmp ugt i32 %A, 1330
7238     // It is incorrect to transform this into 
7239     //    %B = icmp ugt i16 %X, 1330
7240     // because %A may have negative value. 
7241     //
7242     // However, we allow this when the compare is EQ/NE, because they are
7243     // signless.
7244     if (isSignedExt == isSignedCmp || ICI.isEquality())
7245       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
7246     return 0;
7247   }
7248
7249   // The re-extended constant changed so the constant cannot be represented 
7250   // in the shorter type. Consequently, we cannot emit a simple comparison.
7251
7252   // First, handle some easy cases. We know the result cannot be equal at this
7253   // point so handle the ICI.isEquality() cases
7254   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7255     return ReplaceInstUsesWith(ICI, Context->getFalse());
7256   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7257     return ReplaceInstUsesWith(ICI, Context->getTrue());
7258
7259   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7260   // should have been folded away previously and not enter in here.
7261   Value *Result;
7262   if (isSignedCmp) {
7263     // We're performing a signed comparison.
7264     if (cast<ConstantInt>(CI)->getValue().isNegative())
7265       Result = Context->getFalse();          // X < (small) --> false
7266     else
7267       Result = Context->getTrue();           // X < (large) --> true
7268   } else {
7269     // We're performing an unsigned comparison.
7270     if (isSignedExt) {
7271       // We're performing an unsigned comp with a sign extended value.
7272       // This is true if the input is >= 0. [aka >s -1]
7273       Constant *NegOne = Context->getAllOnesValue(SrcTy);
7274       Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT, 
7275                                    LHSCIOp, NegOne, ICI.getName()), ICI);
7276     } else {
7277       // Unsigned extend & unsigned compare -> always true.
7278       Result = Context->getTrue();
7279     }
7280   }
7281
7282   // Finally, return the value computed.
7283   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7284       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7285     return ReplaceInstUsesWith(ICI, Result);
7286
7287   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7288           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7289          "ICmp should be folded!");
7290   if (Constant *CI = dyn_cast<Constant>(Result))
7291     return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
7292   return BinaryOperator::CreateNot(*Context, Result);
7293 }
7294
7295 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7296   return commonShiftTransforms(I);
7297 }
7298
7299 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7300   return commonShiftTransforms(I);
7301 }
7302
7303 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7304   if (Instruction *R = commonShiftTransforms(I))
7305     return R;
7306   
7307   Value *Op0 = I.getOperand(0);
7308   
7309   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7310   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7311     if (CSI->isAllOnesValue())
7312       return ReplaceInstUsesWith(I, CSI);
7313
7314   // See if we can turn a signed shr into an unsigned shr.
7315   if (MaskedValueIsZero(Op0,
7316                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7317     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7318
7319   // Arithmetic shifting an all-sign-bit value is a no-op.
7320   unsigned NumSignBits = ComputeNumSignBits(Op0);
7321   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7322     return ReplaceInstUsesWith(I, Op0);
7323
7324   return 0;
7325 }
7326
7327 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7328   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7329   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7330
7331   // shl X, 0 == X and shr X, 0 == X
7332   // shl 0, X == 0 and shr 0, X == 0
7333   if (Op1 == Context->getNullValue(Op1->getType()) ||
7334       Op0 == Context->getNullValue(Op0->getType()))
7335     return ReplaceInstUsesWith(I, Op0);
7336   
7337   if (isa<UndefValue>(Op0)) {            
7338     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7339       return ReplaceInstUsesWith(I, Op0);
7340     else                                    // undef << X -> 0, undef >>u X -> 0
7341       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7342   }
7343   if (isa<UndefValue>(Op1)) {
7344     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7345       return ReplaceInstUsesWith(I, Op0);          
7346     else                                     // X << undef, X >>u undef -> 0
7347       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7348   }
7349
7350   // See if we can fold away this shift.
7351   if (SimplifyDemandedInstructionBits(I))
7352     return &I;
7353
7354   // Try to fold constant and into select arguments.
7355   if (isa<Constant>(Op0))
7356     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7357       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7358         return R;
7359
7360   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7361     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7362       return Res;
7363   return 0;
7364 }
7365
7366 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7367                                                BinaryOperator &I) {
7368   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7369
7370   // See if we can simplify any instructions used by the instruction whose sole 
7371   // purpose is to compute bits we don't care about.
7372   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7373   
7374   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7375   // a signed shift.
7376   //
7377   if (Op1->uge(TypeBits)) {
7378     if (I.getOpcode() != Instruction::AShr)
7379       return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
7380     else {
7381       I.setOperand(1, Context->getConstantInt(I.getType(), TypeBits-1));
7382       return &I;
7383     }
7384   }
7385   
7386   // ((X*C1) << C2) == (X * (C1 << C2))
7387   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7388     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7389       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7390         return BinaryOperator::CreateMul(BO->getOperand(0),
7391                                         Context->getConstantExprShl(BOOp, Op1));
7392   
7393   // Try to fold constant and into select arguments.
7394   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7395     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7396       return R;
7397   if (isa<PHINode>(Op0))
7398     if (Instruction *NV = FoldOpIntoPhi(I))
7399       return NV;
7400   
7401   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7402   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7403     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7404     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7405     // place.  Don't try to do this transformation in this case.  Also, we
7406     // require that the input operand is a shift-by-constant so that we have
7407     // confidence that the shifts will get folded together.  We could do this
7408     // xform in more cases, but it is unlikely to be profitable.
7409     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7410         isa<ConstantInt>(TrOp->getOperand(1))) {
7411       // Okay, we'll do this xform.  Make the shift of shift.
7412       Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
7413       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7414                                                 I.getName());
7415       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7416
7417       // For logical shifts, the truncation has the effect of making the high
7418       // part of the register be zeros.  Emulate this by inserting an AND to
7419       // clear the top bits as needed.  This 'and' will usually be zapped by
7420       // other xforms later if dead.
7421       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7422       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7423       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7424       
7425       // The mask we constructed says what the trunc would do if occurring
7426       // between the shifts.  We want to know the effect *after* the second
7427       // shift.  We know that it is a logical shift by a constant, so adjust the
7428       // mask as appropriate.
7429       if (I.getOpcode() == Instruction::Shl)
7430         MaskV <<= Op1->getZExtValue();
7431       else {
7432         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7433         MaskV = MaskV.lshr(Op1->getZExtValue());
7434       }
7435
7436       Instruction *And =
7437         BinaryOperator::CreateAnd(NSh, Context->getConstantInt(MaskV), 
7438                                   TI->getName());
7439       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7440
7441       // Return the value truncated to the interesting size.
7442       return new TruncInst(And, I.getType());
7443     }
7444   }
7445   
7446   if (Op0->hasOneUse()) {
7447     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7448       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7449       Value *V1, *V2;
7450       ConstantInt *CC;
7451       switch (Op0BO->getOpcode()) {
7452         default: break;
7453         case Instruction::Add:
7454         case Instruction::And:
7455         case Instruction::Or:
7456         case Instruction::Xor: {
7457           // These operators commute.
7458           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7459           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7460               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7461                     m_Specific(Op1)), *Context)){
7462             Instruction *YS = BinaryOperator::CreateShl(
7463                                             Op0BO->getOperand(0), Op1,
7464                                             Op0BO->getName());
7465             InsertNewInstBefore(YS, I); // (Y << C)
7466             Instruction *X = 
7467               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7468                                      Op0BO->getOperand(1)->getName());
7469             InsertNewInstBefore(X, I);  // (X + (Y << C))
7470             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7471             return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7472                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7473           }
7474           
7475           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7476           Value *Op0BOOp1 = Op0BO->getOperand(1);
7477           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7478               match(Op0BOOp1, 
7479                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7480                           m_ConstantInt(CC)), *Context) &&
7481               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7482             Instruction *YS = BinaryOperator::CreateShl(
7483                                                      Op0BO->getOperand(0), Op1,
7484                                                      Op0BO->getName());
7485             InsertNewInstBefore(YS, I); // (Y << C)
7486             Instruction *XM =
7487               BinaryOperator::CreateAnd(V1,
7488                                         Context->getConstantExprShl(CC, Op1),
7489                                         V1->getName()+".mask");
7490             InsertNewInstBefore(XM, I); // X & (CC << C)
7491             
7492             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7493           }
7494         }
7495           
7496         // FALL THROUGH.
7497         case Instruction::Sub: {
7498           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7499           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7500               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7501                     m_Specific(Op1)), *Context)){
7502             Instruction *YS = BinaryOperator::CreateShl(
7503                                                      Op0BO->getOperand(1), Op1,
7504                                                      Op0BO->getName());
7505             InsertNewInstBefore(YS, I); // (Y << C)
7506             Instruction *X =
7507               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7508                                      Op0BO->getOperand(0)->getName());
7509             InsertNewInstBefore(X, I);  // (X + (Y << C))
7510             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7511             return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7512                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7513           }
7514           
7515           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7516           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7517               match(Op0BO->getOperand(0),
7518                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7519                           m_ConstantInt(CC)), *Context) && V2 == Op1 &&
7520               cast<BinaryOperator>(Op0BO->getOperand(0))
7521                   ->getOperand(0)->hasOneUse()) {
7522             Instruction *YS = BinaryOperator::CreateShl(
7523                                                      Op0BO->getOperand(1), Op1,
7524                                                      Op0BO->getName());
7525             InsertNewInstBefore(YS, I); // (Y << C)
7526             Instruction *XM =
7527               BinaryOperator::CreateAnd(V1, 
7528                                         Context->getConstantExprShl(CC, Op1),
7529                                         V1->getName()+".mask");
7530             InsertNewInstBefore(XM, I); // X & (CC << C)
7531             
7532             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7533           }
7534           
7535           break;
7536         }
7537       }
7538       
7539       
7540       // If the operand is an bitwise operator with a constant RHS, and the
7541       // shift is the only use, we can pull it out of the shift.
7542       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7543         bool isValid = true;     // Valid only for And, Or, Xor
7544         bool highBitSet = false; // Transform if high bit of constant set?
7545         
7546         switch (Op0BO->getOpcode()) {
7547           default: isValid = false; break;   // Do not perform transform!
7548           case Instruction::Add:
7549             isValid = isLeftShift;
7550             break;
7551           case Instruction::Or:
7552           case Instruction::Xor:
7553             highBitSet = false;
7554             break;
7555           case Instruction::And:
7556             highBitSet = true;
7557             break;
7558         }
7559         
7560         // If this is a signed shift right, and the high bit is modified
7561         // by the logical operation, do not perform the transformation.
7562         // The highBitSet boolean indicates the value of the high bit of
7563         // the constant which would cause it to be modified for this
7564         // operation.
7565         //
7566         if (isValid && I.getOpcode() == Instruction::AShr)
7567           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7568         
7569         if (isValid) {
7570           Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
7571           
7572           Instruction *NewShift =
7573             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7574           InsertNewInstBefore(NewShift, I);
7575           NewShift->takeName(Op0BO);
7576           
7577           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7578                                         NewRHS);
7579         }
7580       }
7581     }
7582   }
7583   
7584   // Find out if this is a shift of a shift by a constant.
7585   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7586   if (ShiftOp && !ShiftOp->isShift())
7587     ShiftOp = 0;
7588   
7589   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7590     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7591     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7592     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7593     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7594     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7595     Value *X = ShiftOp->getOperand(0);
7596     
7597     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7598     
7599     const IntegerType *Ty = cast<IntegerType>(I.getType());
7600     
7601     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7602     if (I.getOpcode() == ShiftOp->getOpcode()) {
7603       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7604       // saturates.
7605       if (AmtSum >= TypeBits) {
7606         if (I.getOpcode() != Instruction::AShr)
7607           return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7608         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7609       }
7610       
7611       return BinaryOperator::Create(I.getOpcode(), X,
7612                                     Context->getConstantInt(Ty, AmtSum));
7613     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7614                I.getOpcode() == Instruction::AShr) {
7615       if (AmtSum >= TypeBits)
7616         return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7617       
7618       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7619       return BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, AmtSum));
7620     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7621                I.getOpcode() == Instruction::LShr) {
7622       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7623       if (AmtSum >= TypeBits)
7624         AmtSum = TypeBits-1;
7625       
7626       Instruction *Shift =
7627         BinaryOperator::CreateAShr(X, Context->getConstantInt(Ty, AmtSum));
7628       InsertNewInstBefore(Shift, I);
7629
7630       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7631       return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7632     }
7633     
7634     // Okay, if we get here, one shift must be left, and the other shift must be
7635     // right.  See if the amounts are equal.
7636     if (ShiftAmt1 == ShiftAmt2) {
7637       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7638       if (I.getOpcode() == Instruction::Shl) {
7639         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7640         return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7641       }
7642       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7643       if (I.getOpcode() == Instruction::LShr) {
7644         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7645         return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7646       }
7647       // We can simplify ((X << C) >>s C) into a trunc + sext.
7648       // NOTE: we could do this for any C, but that would make 'unusual' integer
7649       // types.  For now, just stick to ones well-supported by the code
7650       // generators.
7651       const Type *SExtType = 0;
7652       switch (Ty->getBitWidth() - ShiftAmt1) {
7653       case 1  :
7654       case 8  :
7655       case 16 :
7656       case 32 :
7657       case 64 :
7658       case 128:
7659         SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
7660         break;
7661       default: break;
7662       }
7663       if (SExtType) {
7664         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7665         InsertNewInstBefore(NewTrunc, I);
7666         return new SExtInst(NewTrunc, Ty);
7667       }
7668       // Otherwise, we can't handle it yet.
7669     } else if (ShiftAmt1 < ShiftAmt2) {
7670       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7671       
7672       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7673       if (I.getOpcode() == Instruction::Shl) {
7674         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7675                ShiftOp->getOpcode() == Instruction::AShr);
7676         Instruction *Shift =
7677           BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7678         InsertNewInstBefore(Shift, I);
7679         
7680         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7681         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7682       }
7683       
7684       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7685       if (I.getOpcode() == Instruction::LShr) {
7686         assert(ShiftOp->getOpcode() == Instruction::Shl);
7687         Instruction *Shift =
7688           BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, ShiftDiff));
7689         InsertNewInstBefore(Shift, I);
7690         
7691         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7692         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7693       }
7694       
7695       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7696     } else {
7697       assert(ShiftAmt2 < ShiftAmt1);
7698       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7699
7700       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7701       if (I.getOpcode() == Instruction::Shl) {
7702         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7703                ShiftOp->getOpcode() == Instruction::AShr);
7704         Instruction *Shift =
7705           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7706                                  Context->getConstantInt(Ty, ShiftDiff));
7707         InsertNewInstBefore(Shift, I);
7708         
7709         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7710         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7711       }
7712       
7713       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7714       if (I.getOpcode() == Instruction::LShr) {
7715         assert(ShiftOp->getOpcode() == Instruction::Shl);
7716         Instruction *Shift =
7717           BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7718         InsertNewInstBefore(Shift, I);
7719         
7720         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7721         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7722       }
7723       
7724       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7725     }
7726   }
7727   return 0;
7728 }
7729
7730
7731 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7732 /// expression.  If so, decompose it, returning some value X, such that Val is
7733 /// X*Scale+Offset.
7734 ///
7735 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7736                                         int &Offset, LLVMContext *Context) {
7737   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7738   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7739     Offset = CI->getZExtValue();
7740     Scale  = 0;
7741     return Context->getConstantInt(Type::Int32Ty, 0);
7742   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7743     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7744       if (I->getOpcode() == Instruction::Shl) {
7745         // This is a value scaled by '1 << the shift amt'.
7746         Scale = 1U << RHS->getZExtValue();
7747         Offset = 0;
7748         return I->getOperand(0);
7749       } else if (I->getOpcode() == Instruction::Mul) {
7750         // This value is scaled by 'RHS'.
7751         Scale = RHS->getZExtValue();
7752         Offset = 0;
7753         return I->getOperand(0);
7754       } else if (I->getOpcode() == Instruction::Add) {
7755         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7756         // where C1 is divisible by C2.
7757         unsigned SubScale;
7758         Value *SubVal = 
7759           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7760                                     Offset, Context);
7761         Offset += RHS->getZExtValue();
7762         Scale = SubScale;
7763         return SubVal;
7764       }
7765     }
7766   }
7767
7768   // Otherwise, we can't look past this.
7769   Scale = 1;
7770   Offset = 0;
7771   return Val;
7772 }
7773
7774
7775 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7776 /// try to eliminate the cast by moving the type information into the alloc.
7777 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7778                                                    AllocationInst &AI) {
7779   const PointerType *PTy = cast<PointerType>(CI.getType());
7780   
7781   // Remove any uses of AI that are dead.
7782   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7783   
7784   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7785     Instruction *User = cast<Instruction>(*UI++);
7786     if (isInstructionTriviallyDead(User)) {
7787       while (UI != E && *UI == User)
7788         ++UI; // If this instruction uses AI more than once, don't break UI.
7789       
7790       ++NumDeadInst;
7791       DOUT << "IC: DCE: " << *User;
7792       EraseInstFromFunction(*User);
7793     }
7794   }
7795   
7796   // Get the type really allocated and the type casted to.
7797   const Type *AllocElTy = AI.getAllocatedType();
7798   const Type *CastElTy = PTy->getElementType();
7799   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7800
7801   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7802   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7803   if (CastElTyAlign < AllocElTyAlign) return 0;
7804
7805   // If the allocation has multiple uses, only promote it if we are strictly
7806   // increasing the alignment of the resultant allocation.  If we keep it the
7807   // same, we open the door to infinite loops of various kinds.  (A reference
7808   // from a dbg.declare doesn't count as a use for this purpose.)
7809   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7810       CastElTyAlign == AllocElTyAlign) return 0;
7811
7812   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7813   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7814   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7815
7816   // See if we can satisfy the modulus by pulling a scale out of the array
7817   // size argument.
7818   unsigned ArraySizeScale;
7819   int ArrayOffset;
7820   Value *NumElements = // See if the array size is a decomposable linear expr.
7821     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7822                               ArrayOffset, Context);
7823  
7824   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7825   // do the xform.
7826   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7827       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7828
7829   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7830   Value *Amt = 0;
7831   if (Scale == 1) {
7832     Amt = NumElements;
7833   } else {
7834     // If the allocation size is constant, form a constant mul expression
7835     Amt = Context->getConstantInt(Type::Int32Ty, Scale);
7836     if (isa<ConstantInt>(NumElements))
7837       Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
7838                                  cast<ConstantInt>(Amt));
7839     // otherwise multiply the amount and the number of elements
7840     else {
7841       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7842       Amt = InsertNewInstBefore(Tmp, AI);
7843     }
7844   }
7845   
7846   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7847     Value *Off = Context->getConstantInt(Type::Int32Ty, Offset, true);
7848     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7849     Amt = InsertNewInstBefore(Tmp, AI);
7850   }
7851   
7852   AllocationInst *New;
7853   if (isa<MallocInst>(AI))
7854     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7855   else
7856     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7857   InsertNewInstBefore(New, AI);
7858   New->takeName(&AI);
7859   
7860   // If the allocation has one real use plus a dbg.declare, just remove the
7861   // declare.
7862   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7863     EraseInstFromFunction(*DI);
7864   }
7865   // If the allocation has multiple real uses, insert a cast and change all
7866   // things that used it to use the new cast.  This will also hack on CI, but it
7867   // will die soon.
7868   else if (!AI.hasOneUse()) {
7869     AddUsesToWorkList(AI);
7870     // New is the allocation instruction, pointer typed. AI is the original
7871     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7872     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7873     InsertNewInstBefore(NewCast, AI);
7874     AI.replaceAllUsesWith(NewCast);
7875   }
7876   return ReplaceInstUsesWith(CI, New);
7877 }
7878
7879 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7880 /// and return it as type Ty without inserting any new casts and without
7881 /// changing the computed value.  This is used by code that tries to decide
7882 /// whether promoting or shrinking integer operations to wider or smaller types
7883 /// will allow us to eliminate a truncate or extend.
7884 ///
7885 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7886 /// extension operation if Ty is larger.
7887 ///
7888 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7889 /// should return true if trunc(V) can be computed by computing V in the smaller
7890 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7891 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7892 /// efficiently truncated.
7893 ///
7894 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7895 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7896 /// the final result.
7897 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7898                                               unsigned CastOpc,
7899                                               int &NumCastsRemoved){
7900   // We can always evaluate constants in another type.
7901   if (isa<Constant>(V))
7902     return true;
7903   
7904   Instruction *I = dyn_cast<Instruction>(V);
7905   if (!I) return false;
7906   
7907   const Type *OrigTy = V->getType();
7908   
7909   // If this is an extension or truncate, we can often eliminate it.
7910   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7911     // If this is a cast from the destination type, we can trivially eliminate
7912     // it, and this will remove a cast overall.
7913     if (I->getOperand(0)->getType() == Ty) {
7914       // If the first operand is itself a cast, and is eliminable, do not count
7915       // this as an eliminable cast.  We would prefer to eliminate those two
7916       // casts first.
7917       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7918         ++NumCastsRemoved;
7919       return true;
7920     }
7921   }
7922
7923   // We can't extend or shrink something that has multiple uses: doing so would
7924   // require duplicating the instruction in general, which isn't profitable.
7925   if (!I->hasOneUse()) return false;
7926
7927   unsigned Opc = I->getOpcode();
7928   switch (Opc) {
7929   case Instruction::Add:
7930   case Instruction::Sub:
7931   case Instruction::Mul:
7932   case Instruction::And:
7933   case Instruction::Or:
7934   case Instruction::Xor:
7935     // These operators can all arbitrarily be extended or truncated.
7936     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7937                                       NumCastsRemoved) &&
7938            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7939                                       NumCastsRemoved);
7940
7941   case Instruction::UDiv:
7942   case Instruction::URem: {
7943     // UDiv and URem can be truncated if all the truncated bits are zero.
7944     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7945     uint32_t BitWidth = Ty->getScalarSizeInBits();
7946     if (BitWidth < OrigBitWidth) {
7947       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7948       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7949           MaskedValueIsZero(I->getOperand(1), Mask)) {
7950         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7951                                           NumCastsRemoved) &&
7952                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7953                                           NumCastsRemoved);
7954       }
7955     }
7956     break;
7957   }
7958   case Instruction::Shl:
7959     // If we are truncating the result of this SHL, and if it's a shift of a
7960     // constant amount, we can always perform a SHL in a smaller type.
7961     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7962       uint32_t BitWidth = Ty->getScalarSizeInBits();
7963       if (BitWidth < OrigTy->getScalarSizeInBits() &&
7964           CI->getLimitedValue(BitWidth) < BitWidth)
7965         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7966                                           NumCastsRemoved);
7967     }
7968     break;
7969   case Instruction::LShr:
7970     // If this is a truncate of a logical shr, we can truncate it to a smaller
7971     // lshr iff we know that the bits we would otherwise be shifting in are
7972     // already zeros.
7973     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7974       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7975       uint32_t BitWidth = Ty->getScalarSizeInBits();
7976       if (BitWidth < OrigBitWidth &&
7977           MaskedValueIsZero(I->getOperand(0),
7978             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7979           CI->getLimitedValue(BitWidth) < BitWidth) {
7980         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7981                                           NumCastsRemoved);
7982       }
7983     }
7984     break;
7985   case Instruction::ZExt:
7986   case Instruction::SExt:
7987   case Instruction::Trunc:
7988     // If this is the same kind of case as our original (e.g. zext+zext), we
7989     // can safely replace it.  Note that replacing it does not reduce the number
7990     // of casts in the input.
7991     if (Opc == CastOpc)
7992       return true;
7993
7994     // sext (zext ty1), ty2 -> zext ty2
7995     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7996       return true;
7997     break;
7998   case Instruction::Select: {
7999     SelectInst *SI = cast<SelectInst>(I);
8000     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8001                                       NumCastsRemoved) &&
8002            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8003                                       NumCastsRemoved);
8004   }
8005   case Instruction::PHI: {
8006     // We can change a phi if we can change all operands.
8007     PHINode *PN = cast<PHINode>(I);
8008     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8009       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8010                                       NumCastsRemoved))
8011         return false;
8012     return true;
8013   }
8014   default:
8015     // TODO: Can handle more cases here.
8016     break;
8017   }
8018   
8019   return false;
8020 }
8021
8022 /// EvaluateInDifferentType - Given an expression that 
8023 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8024 /// evaluate the expression.
8025 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
8026                                              bool isSigned) {
8027   if (Constant *C = dyn_cast<Constant>(V))
8028     return Context->getConstantExprIntegerCast(C, Ty,
8029                                                isSigned /*Sext or ZExt*/);
8030
8031   // Otherwise, it must be an instruction.
8032   Instruction *I = cast<Instruction>(V);
8033   Instruction *Res = 0;
8034   unsigned Opc = I->getOpcode();
8035   switch (Opc) {
8036   case Instruction::Add:
8037   case Instruction::Sub:
8038   case Instruction::Mul:
8039   case Instruction::And:
8040   case Instruction::Or:
8041   case Instruction::Xor:
8042   case Instruction::AShr:
8043   case Instruction::LShr:
8044   case Instruction::Shl:
8045   case Instruction::UDiv:
8046   case Instruction::URem: {
8047     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8048     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8049     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8050     break;
8051   }    
8052   case Instruction::Trunc:
8053   case Instruction::ZExt:
8054   case Instruction::SExt:
8055     // If the source type of the cast is the type we're trying for then we can
8056     // just return the source.  There's no need to insert it because it is not
8057     // new.
8058     if (I->getOperand(0)->getType() == Ty)
8059       return I->getOperand(0);
8060     
8061     // Otherwise, must be the same type of cast, so just reinsert a new one.
8062     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8063                            Ty);
8064     break;
8065   case Instruction::Select: {
8066     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8067     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8068     Res = SelectInst::Create(I->getOperand(0), True, False);
8069     break;
8070   }
8071   case Instruction::PHI: {
8072     PHINode *OPN = cast<PHINode>(I);
8073     PHINode *NPN = PHINode::Create(Ty);
8074     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8075       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8076       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8077     }
8078     Res = NPN;
8079     break;
8080   }
8081   default: 
8082     // TODO: Can handle more cases here.
8083     llvm_unreachable("Unreachable!");
8084     break;
8085   }
8086   
8087   Res->takeName(I);
8088   return InsertNewInstBefore(Res, *I);
8089 }
8090
8091 /// @brief Implement the transforms common to all CastInst visitors.
8092 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8093   Value *Src = CI.getOperand(0);
8094
8095   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8096   // eliminate it now.
8097   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8098     if (Instruction::CastOps opc = 
8099         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8100       // The first cast (CSrc) is eliminable so we need to fix up or replace
8101       // the second cast (CI). CSrc will then have a good chance of being dead.
8102       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8103     }
8104   }
8105
8106   // If we are casting a select then fold the cast into the select
8107   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8108     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8109       return NV;
8110
8111   // If we are casting a PHI then fold the cast into the PHI
8112   if (isa<PHINode>(Src))
8113     if (Instruction *NV = FoldOpIntoPhi(CI))
8114       return NV;
8115   
8116   return 0;
8117 }
8118
8119 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8120 /// or not there is a sequence of GEP indices into the type that will land us at
8121 /// the specified offset.  If so, fill them into NewIndices and return the
8122 /// resultant element type, otherwise return null.
8123 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8124                                        SmallVectorImpl<Value*> &NewIndices,
8125                                        const TargetData *TD,
8126                                        LLVMContext *Context) {
8127   if (!Ty->isSized()) return 0;
8128   
8129   // Start with the index over the outer type.  Note that the type size
8130   // might be zero (even if the offset isn't zero) if the indexed type
8131   // is something like [0 x {int, int}]
8132   const Type *IntPtrTy = TD->getIntPtrType();
8133   int64_t FirstIdx = 0;
8134   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8135     FirstIdx = Offset/TySize;
8136     Offset -= FirstIdx*TySize;
8137     
8138     // Handle hosts where % returns negative instead of values [0..TySize).
8139     if (Offset < 0) {
8140       --FirstIdx;
8141       Offset += TySize;
8142       assert(Offset >= 0);
8143     }
8144     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8145   }
8146   
8147   NewIndices.push_back(Context->getConstantInt(IntPtrTy, FirstIdx));
8148     
8149   // Index into the types.  If we fail, set OrigBase to null.
8150   while (Offset) {
8151     // Indexing into tail padding between struct/array elements.
8152     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8153       return 0;
8154     
8155     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8156       const StructLayout *SL = TD->getStructLayout(STy);
8157       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8158              "Offset must stay within the indexed type");
8159       
8160       unsigned Elt = SL->getElementContainingOffset(Offset);
8161       NewIndices.push_back(Context->getConstantInt(Type::Int32Ty, Elt));
8162       
8163       Offset -= SL->getElementOffset(Elt);
8164       Ty = STy->getElementType(Elt);
8165     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8166       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8167       assert(EltSize && "Cannot index into a zero-sized array");
8168       NewIndices.push_back(Context->getConstantInt(IntPtrTy,Offset/EltSize));
8169       Offset %= EltSize;
8170       Ty = AT->getElementType();
8171     } else {
8172       // Otherwise, we can't index into the middle of this atomic type, bail.
8173       return 0;
8174     }
8175   }
8176   
8177   return Ty;
8178 }
8179
8180 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8181 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8182   Value *Src = CI.getOperand(0);
8183   
8184   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8185     // If casting the result of a getelementptr instruction with no offset, turn
8186     // this into a cast of the original pointer!
8187     if (GEP->hasAllZeroIndices()) {
8188       // Changing the cast operand is usually not a good idea but it is safe
8189       // here because the pointer operand is being replaced with another 
8190       // pointer operand so the opcode doesn't need to change.
8191       AddToWorkList(GEP);
8192       CI.setOperand(0, GEP->getOperand(0));
8193       return &CI;
8194     }
8195     
8196     // If the GEP has a single use, and the base pointer is a bitcast, and the
8197     // GEP computes a constant offset, see if we can convert these three
8198     // instructions into fewer.  This typically happens with unions and other
8199     // non-type-safe code.
8200     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8201       if (GEP->hasAllConstantIndices()) {
8202         // We are guaranteed to get a constant from EmitGEPOffset.
8203         ConstantInt *OffsetV =
8204                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8205         int64_t Offset = OffsetV->getSExtValue();
8206         
8207         // Get the base pointer input of the bitcast, and the type it points to.
8208         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8209         const Type *GEPIdxTy =
8210           cast<PointerType>(OrigBase->getType())->getElementType();
8211         SmallVector<Value*, 8> NewIndices;
8212         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8213           // If we were able to index down into an element, create the GEP
8214           // and bitcast the result.  This eliminates one bitcast, potentially
8215           // two.
8216           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
8217                                                         NewIndices.begin(),
8218                                                         NewIndices.end(), "");
8219           InsertNewInstBefore(NGEP, CI);
8220           NGEP->takeName(GEP);
8221           
8222           if (isa<BitCastInst>(CI))
8223             return new BitCastInst(NGEP, CI.getType());
8224           assert(isa<PtrToIntInst>(CI));
8225           return new PtrToIntInst(NGEP, CI.getType());
8226         }
8227       }      
8228     }
8229   }
8230     
8231   return commonCastTransforms(CI);
8232 }
8233
8234 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8235 /// type like i42.  We don't want to introduce operations on random non-legal
8236 /// integer types where they don't already exist in the code.  In the future,
8237 /// we should consider making this based off target-data, so that 32-bit targets
8238 /// won't get i64 operations etc.
8239 static bool isSafeIntegerType(const Type *Ty) {
8240   switch (Ty->getPrimitiveSizeInBits()) {
8241   case 8:
8242   case 16:
8243   case 32:
8244   case 64:
8245     return true;
8246   default: 
8247     return false;
8248   }
8249 }
8250
8251 /// commonIntCastTransforms - This function implements the common transforms
8252 /// for trunc, zext, and sext.
8253 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8254   if (Instruction *Result = commonCastTransforms(CI))
8255     return Result;
8256
8257   Value *Src = CI.getOperand(0);
8258   const Type *SrcTy = Src->getType();
8259   const Type *DestTy = CI.getType();
8260   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8261   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8262
8263   // See if we can simplify any instructions used by the LHS whose sole 
8264   // purpose is to compute bits we don't care about.
8265   if (SimplifyDemandedInstructionBits(CI))
8266     return &CI;
8267
8268   // If the source isn't an instruction or has more than one use then we
8269   // can't do anything more. 
8270   Instruction *SrcI = dyn_cast<Instruction>(Src);
8271   if (!SrcI || !Src->hasOneUse())
8272     return 0;
8273
8274   // Attempt to propagate the cast into the instruction for int->int casts.
8275   int NumCastsRemoved = 0;
8276   // Only do this if the dest type is a simple type, don't convert the
8277   // expression tree to something weird like i93 unless the source is also
8278   // strange.
8279   if ((isSafeIntegerType(DestTy->getScalarType()) ||
8280        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8281       CanEvaluateInDifferentType(SrcI, DestTy,
8282                                  CI.getOpcode(), NumCastsRemoved)) {
8283     // If this cast is a truncate, evaluting in a different type always
8284     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8285     // we need to do an AND to maintain the clear top-part of the computation,
8286     // so we require that the input have eliminated at least one cast.  If this
8287     // is a sign extension, we insert two new casts (to do the extension) so we
8288     // require that two casts have been eliminated.
8289     bool DoXForm = false;
8290     bool JustReplace = false;
8291     switch (CI.getOpcode()) {
8292     default:
8293       // All the others use floating point so we shouldn't actually 
8294       // get here because of the check above.
8295       llvm_unreachable("Unknown cast type");
8296     case Instruction::Trunc:
8297       DoXForm = true;
8298       break;
8299     case Instruction::ZExt: {
8300       DoXForm = NumCastsRemoved >= 1;
8301       if (!DoXForm && 0) {
8302         // If it's unnecessary to issue an AND to clear the high bits, it's
8303         // always profitable to do this xform.
8304         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8305         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8306         if (MaskedValueIsZero(TryRes, Mask))
8307           return ReplaceInstUsesWith(CI, TryRes);
8308         
8309         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8310           if (TryI->use_empty())
8311             EraseInstFromFunction(*TryI);
8312       }
8313       break;
8314     }
8315     case Instruction::SExt: {
8316       DoXForm = NumCastsRemoved >= 2;
8317       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8318         // If we do not have to emit the truncate + sext pair, then it's always
8319         // profitable to do this xform.
8320         //
8321         // It's not safe to eliminate the trunc + sext pair if one of the
8322         // eliminated cast is a truncate. e.g.
8323         // t2 = trunc i32 t1 to i16
8324         // t3 = sext i16 t2 to i32
8325         // !=
8326         // i32 t1
8327         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8328         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8329         if (NumSignBits > (DestBitSize - SrcBitSize))
8330           return ReplaceInstUsesWith(CI, TryRes);
8331         
8332         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8333           if (TryI->use_empty())
8334             EraseInstFromFunction(*TryI);
8335       }
8336       break;
8337     }
8338     }
8339     
8340     if (DoXForm) {
8341       DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8342            << " cast: " << CI;
8343       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8344                                            CI.getOpcode() == Instruction::SExt);
8345       if (JustReplace)
8346         // Just replace this cast with the result.
8347         return ReplaceInstUsesWith(CI, Res);
8348
8349       assert(Res->getType() == DestTy);
8350       switch (CI.getOpcode()) {
8351       default: llvm_unreachable("Unknown cast type!");
8352       case Instruction::Trunc:
8353         // Just replace this cast with the result.
8354         return ReplaceInstUsesWith(CI, Res);
8355       case Instruction::ZExt: {
8356         assert(SrcBitSize < DestBitSize && "Not a zext?");
8357
8358         // If the high bits are already zero, just replace this cast with the
8359         // result.
8360         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8361         if (MaskedValueIsZero(Res, Mask))
8362           return ReplaceInstUsesWith(CI, Res);
8363
8364         // We need to emit an AND to clear the high bits.
8365         Constant *C = Context->getConstantInt(APInt::getLowBitsSet(DestBitSize,
8366                                                             SrcBitSize));
8367         return BinaryOperator::CreateAnd(Res, C);
8368       }
8369       case Instruction::SExt: {
8370         // If the high bits are already filled with sign bit, just replace this
8371         // cast with the result.
8372         unsigned NumSignBits = ComputeNumSignBits(Res);
8373         if (NumSignBits > (DestBitSize - SrcBitSize))
8374           return ReplaceInstUsesWith(CI, Res);
8375
8376         // We need to emit a cast to truncate, then a cast to sext.
8377         return CastInst::Create(Instruction::SExt,
8378             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8379                              CI), DestTy);
8380       }
8381       }
8382     }
8383   }
8384   
8385   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8386   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8387
8388   switch (SrcI->getOpcode()) {
8389   case Instruction::Add:
8390   case Instruction::Mul:
8391   case Instruction::And:
8392   case Instruction::Or:
8393   case Instruction::Xor:
8394     // If we are discarding information, rewrite.
8395     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8396       // Don't insert two casts unless at least one can be eliminated.
8397       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8398           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8399         Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8400         Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8401         return BinaryOperator::Create(
8402             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8403       }
8404     }
8405
8406     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8407     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8408         SrcI->getOpcode() == Instruction::Xor &&
8409         Op1 == Context->getTrue() &&
8410         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8411       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8412       return BinaryOperator::CreateXor(New,
8413                                       Context->getConstantInt(CI.getType(), 1));
8414     }
8415     break;
8416
8417   case Instruction::Shl: {
8418     // Canonicalize trunc inside shl, if we can.
8419     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8420     if (CI && DestBitSize < SrcBitSize &&
8421         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8422       Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8423       Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8424       return BinaryOperator::CreateShl(Op0c, Op1c);
8425     }
8426     break;
8427   }
8428   }
8429   return 0;
8430 }
8431
8432 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8433   if (Instruction *Result = commonIntCastTransforms(CI))
8434     return Result;
8435   
8436   Value *Src = CI.getOperand(0);
8437   const Type *Ty = CI.getType();
8438   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8439   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8440
8441   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8442   if (DestBitWidth == 1) {
8443     Constant *One = Context->getConstantInt(Src->getType(), 1);
8444     Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8445     Value *Zero = Context->getNullValue(Src->getType());
8446     return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
8447   }
8448
8449   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8450   ConstantInt *ShAmtV = 0;
8451   Value *ShiftOp = 0;
8452   if (Src->hasOneUse() &&
8453       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
8454     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8455     
8456     // Get a mask for the bits shifting in.
8457     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8458     if (MaskedValueIsZero(ShiftOp, Mask)) {
8459       if (ShAmt >= DestBitWidth)        // All zeros.
8460         return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
8461       
8462       // Okay, we can shrink this.  Truncate the input, then return a new
8463       // shift.
8464       Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8465       Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
8466       return BinaryOperator::CreateLShr(V1, V2);
8467     }
8468   }
8469   
8470   return 0;
8471 }
8472
8473 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8474 /// in order to eliminate the icmp.
8475 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8476                                              bool DoXform) {
8477   // If we are just checking for a icmp eq of a single bit and zext'ing it
8478   // to an integer, then shift the bit to the appropriate place and then
8479   // cast to integer to avoid the comparison.
8480   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8481     const APInt &Op1CV = Op1C->getValue();
8482       
8483     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8484     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8485     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8486         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8487       if (!DoXform) return ICI;
8488
8489       Value *In = ICI->getOperand(0);
8490       Value *Sh = Context->getConstantInt(In->getType(),
8491                                    In->getType()->getScalarSizeInBits()-1);
8492       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8493                                                         In->getName()+".lobit"),
8494                                CI);
8495       if (In->getType() != CI.getType())
8496         In = CastInst::CreateIntegerCast(In, CI.getType(),
8497                                          false/*ZExt*/, "tmp", &CI);
8498
8499       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8500         Constant *One = Context->getConstantInt(In->getType(), 1);
8501         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8502                                                          In->getName()+".not"),
8503                                  CI);
8504       }
8505
8506       return ReplaceInstUsesWith(CI, In);
8507     }
8508       
8509       
8510       
8511     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8512     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8513     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8514     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8515     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8516     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8517     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8518     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8519     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8520         // This only works for EQ and NE
8521         ICI->isEquality()) {
8522       // If Op1C some other power of two, convert:
8523       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8524       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8525       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8526       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8527         
8528       APInt KnownZeroMask(~KnownZero);
8529       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8530         if (!DoXform) return ICI;
8531
8532         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8533         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8534           // (X&4) == 2 --> false
8535           // (X&4) != 2 --> true
8536           Constant *Res = Context->getConstantInt(Type::Int1Ty, isNE);
8537           Res = Context->getConstantExprZExt(Res, CI.getType());
8538           return ReplaceInstUsesWith(CI, Res);
8539         }
8540           
8541         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8542         Value *In = ICI->getOperand(0);
8543         if (ShiftAmt) {
8544           // Perform a logical shr by shiftamt.
8545           // Insert the shift to put the result in the low bit.
8546           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8547                               Context->getConstantInt(In->getType(), ShiftAmt),
8548                                                    In->getName()+".lobit"), CI);
8549         }
8550           
8551         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8552           Constant *One = Context->getConstantInt(In->getType(), 1);
8553           In = BinaryOperator::CreateXor(In, One, "tmp");
8554           InsertNewInstBefore(cast<Instruction>(In), CI);
8555         }
8556           
8557         if (CI.getType() == In->getType())
8558           return ReplaceInstUsesWith(CI, In);
8559         else
8560           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8561       }
8562     }
8563   }
8564
8565   return 0;
8566 }
8567
8568 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8569   // If one of the common conversion will work ..
8570   if (Instruction *Result = commonIntCastTransforms(CI))
8571     return Result;
8572
8573   Value *Src = CI.getOperand(0);
8574
8575   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8576   // types and if the sizes are just right we can convert this into a logical
8577   // 'and' which will be much cheaper than the pair of casts.
8578   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8579     // Get the sizes of the types involved.  We know that the intermediate type
8580     // will be smaller than A or C, but don't know the relation between A and C.
8581     Value *A = CSrc->getOperand(0);
8582     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8583     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8584     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8585     // If we're actually extending zero bits, then if
8586     // SrcSize <  DstSize: zext(a & mask)
8587     // SrcSize == DstSize: a & mask
8588     // SrcSize  > DstSize: trunc(a) & mask
8589     if (SrcSize < DstSize) {
8590       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8591       Constant *AndConst = Context->getConstantInt(A->getType(), AndValue);
8592       Instruction *And =
8593         BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8594       InsertNewInstBefore(And, CI);
8595       return new ZExtInst(And, CI.getType());
8596     } else if (SrcSize == DstSize) {
8597       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8598       return BinaryOperator::CreateAnd(A, Context->getConstantInt(A->getType(),
8599                                                            AndValue));
8600     } else if (SrcSize > DstSize) {
8601       Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8602       InsertNewInstBefore(Trunc, CI);
8603       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8604       return BinaryOperator::CreateAnd(Trunc, 
8605                                        Context->getConstantInt(Trunc->getType(),
8606                                                                AndValue));
8607     }
8608   }
8609
8610   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8611     return transformZExtICmp(ICI, CI);
8612
8613   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8614   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8615     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8616     // of the (zext icmp) will be transformed.
8617     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8618     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8619     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8620         (transformZExtICmp(LHS, CI, false) ||
8621          transformZExtICmp(RHS, CI, false))) {
8622       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8623       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8624       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8625     }
8626   }
8627
8628   // zext(trunc(t) & C) -> (t & zext(C)).
8629   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8630     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8631       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8632         Value *TI0 = TI->getOperand(0);
8633         if (TI0->getType() == CI.getType())
8634           return
8635             BinaryOperator::CreateAnd(TI0,
8636                                 Context->getConstantExprZExt(C, CI.getType()));
8637       }
8638
8639   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8640   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8641     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8642       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8643         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8644             And->getOperand(1) == C)
8645           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8646             Value *TI0 = TI->getOperand(0);
8647             if (TI0->getType() == CI.getType()) {
8648               Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
8649               Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8650               InsertNewInstBefore(NewAnd, *And);
8651               return BinaryOperator::CreateXor(NewAnd, ZC);
8652             }
8653           }
8654
8655   return 0;
8656 }
8657
8658 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8659   if (Instruction *I = commonIntCastTransforms(CI))
8660     return I;
8661   
8662   Value *Src = CI.getOperand(0);
8663   
8664   // Canonicalize sign-extend from i1 to a select.
8665   if (Src->getType() == Type::Int1Ty)
8666     return SelectInst::Create(Src,
8667                               Context->getAllOnesValue(CI.getType()),
8668                               Context->getNullValue(CI.getType()));
8669
8670   // See if the value being truncated is already sign extended.  If so, just
8671   // eliminate the trunc/sext pair.
8672   if (Operator::getOpcode(Src) == Instruction::Trunc) {
8673     Value *Op = cast<User>(Src)->getOperand(0);
8674     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8675     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8676     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8677     unsigned NumSignBits = ComputeNumSignBits(Op);
8678
8679     if (OpBits == DestBits) {
8680       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8681       // bits, it is already ready.
8682       if (NumSignBits > DestBits-MidBits)
8683         return ReplaceInstUsesWith(CI, Op);
8684     } else if (OpBits < DestBits) {
8685       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8686       // bits, just sext from i32.
8687       if (NumSignBits > OpBits-MidBits)
8688         return new SExtInst(Op, CI.getType(), "tmp");
8689     } else {
8690       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8691       // bits, just truncate to i32.
8692       if (NumSignBits > OpBits-MidBits)
8693         return new TruncInst(Op, CI.getType(), "tmp");
8694     }
8695   }
8696
8697   // If the input is a shl/ashr pair of a same constant, then this is a sign
8698   // extension from a smaller value.  If we could trust arbitrary bitwidth
8699   // integers, we could turn this into a truncate to the smaller bit and then
8700   // use a sext for the whole extension.  Since we don't, look deeper and check
8701   // for a truncate.  If the source and dest are the same type, eliminate the
8702   // trunc and extend and just do shifts.  For example, turn:
8703   //   %a = trunc i32 %i to i8
8704   //   %b = shl i8 %a, 6
8705   //   %c = ashr i8 %b, 6
8706   //   %d = sext i8 %c to i32
8707   // into:
8708   //   %a = shl i32 %i, 30
8709   //   %d = ashr i32 %a, 30
8710   Value *A = 0;
8711   ConstantInt *BA = 0, *CA = 0;
8712   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8713                         m_ConstantInt(CA)), *Context) &&
8714       BA == CA && isa<TruncInst>(A)) {
8715     Value *I = cast<TruncInst>(A)->getOperand(0);
8716     if (I->getType() == CI.getType()) {
8717       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8718       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8719       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8720       Constant *ShAmtV = Context->getConstantInt(CI.getType(), ShAmt);
8721       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8722                                                         CI.getName()), CI);
8723       return BinaryOperator::CreateAShr(I, ShAmtV);
8724     }
8725   }
8726   
8727   return 0;
8728 }
8729
8730 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8731 /// in the specified FP type without changing its value.
8732 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8733                               LLVMContext *Context) {
8734   bool losesInfo;
8735   APFloat F = CFP->getValueAPF();
8736   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8737   if (!losesInfo)
8738     return Context->getConstantFP(F);
8739   return 0;
8740 }
8741
8742 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8743 /// through it until we get the source value.
8744 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8745   if (Instruction *I = dyn_cast<Instruction>(V))
8746     if (I->getOpcode() == Instruction::FPExt)
8747       return LookThroughFPExtensions(I->getOperand(0), Context);
8748   
8749   // If this value is a constant, return the constant in the smallest FP type
8750   // that can accurately represent it.  This allows us to turn
8751   // (float)((double)X+2.0) into x+2.0f.
8752   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8753     if (CFP->getType() == Type::PPC_FP128Ty)
8754       return V;  // No constant folding of this.
8755     // See if the value can be truncated to float and then reextended.
8756     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8757       return V;
8758     if (CFP->getType() == Type::DoubleTy)
8759       return V;  // Won't shrink.
8760     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8761       return V;
8762     // Don't try to shrink to various long double types.
8763   }
8764   
8765   return V;
8766 }
8767
8768 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8769   if (Instruction *I = commonCastTransforms(CI))
8770     return I;
8771   
8772   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8773   // smaller than the destination type, we can eliminate the truncate by doing
8774   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8775   // many builtins (sqrt, etc).
8776   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8777   if (OpI && OpI->hasOneUse()) {
8778     switch (OpI->getOpcode()) {
8779     default: break;
8780     case Instruction::FAdd:
8781     case Instruction::FSub:
8782     case Instruction::FMul:
8783     case Instruction::FDiv:
8784     case Instruction::FRem:
8785       const Type *SrcTy = OpI->getType();
8786       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8787       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8788       if (LHSTrunc->getType() != SrcTy && 
8789           RHSTrunc->getType() != SrcTy) {
8790         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8791         // If the source types were both smaller than the destination type of
8792         // the cast, do this xform.
8793         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8794             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8795           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8796                                       CI.getType(), CI);
8797           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8798                                       CI.getType(), CI);
8799           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8800         }
8801       }
8802       break;  
8803     }
8804   }
8805   return 0;
8806 }
8807
8808 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8809   return commonCastTransforms(CI);
8810 }
8811
8812 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8813   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8814   if (OpI == 0)
8815     return commonCastTransforms(FI);
8816
8817   // fptoui(uitofp(X)) --> X
8818   // fptoui(sitofp(X)) --> X
8819   // This is safe if the intermediate type has enough bits in its mantissa to
8820   // accurately represent all values of X.  For example, do not do this with
8821   // i64->float->i64.  This is also safe for sitofp case, because any negative
8822   // 'X' value would cause an undefined result for the fptoui. 
8823   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8824       OpI->getOperand(0)->getType() == FI.getType() &&
8825       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8826                     OpI->getType()->getFPMantissaWidth())
8827     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8828
8829   return commonCastTransforms(FI);
8830 }
8831
8832 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8833   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8834   if (OpI == 0)
8835     return commonCastTransforms(FI);
8836   
8837   // fptosi(sitofp(X)) --> X
8838   // fptosi(uitofp(X)) --> X
8839   // This is safe if the intermediate type has enough bits in its mantissa to
8840   // accurately represent all values of X.  For example, do not do this with
8841   // i64->float->i64.  This is also safe for sitofp case, because any negative
8842   // 'X' value would cause an undefined result for the fptoui. 
8843   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8844       OpI->getOperand(0)->getType() == FI.getType() &&
8845       (int)FI.getType()->getScalarSizeInBits() <=
8846                     OpI->getType()->getFPMantissaWidth())
8847     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8848   
8849   return commonCastTransforms(FI);
8850 }
8851
8852 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8853   return commonCastTransforms(CI);
8854 }
8855
8856 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8857   return commonCastTransforms(CI);
8858 }
8859
8860 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8861   // If the destination integer type is smaller than the intptr_t type for
8862   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8863   // trunc to be exposed to other transforms.  Don't do this for extending
8864   // ptrtoint's, because we don't know if the target sign or zero extends its
8865   // pointers.
8866   if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8867     Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8868                                                     TD->getIntPtrType(),
8869                                                     "tmp"), CI);
8870     return new TruncInst(P, CI.getType());
8871   }
8872   
8873   return commonPointerCastTransforms(CI);
8874 }
8875
8876 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8877   // If the source integer type is larger than the intptr_t type for
8878   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8879   // allows the trunc to be exposed to other transforms.  Don't do this for
8880   // extending inttoptr's, because we don't know if the target sign or zero
8881   // extends to pointers.
8882   if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
8883       TD->getPointerSizeInBits()) {
8884     Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8885                                                  TD->getIntPtrType(),
8886                                                  "tmp"), CI);
8887     return new IntToPtrInst(P, CI.getType());
8888   }
8889   
8890   if (Instruction *I = commonCastTransforms(CI))
8891     return I;
8892
8893   return 0;
8894 }
8895
8896 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8897   // If the operands are integer typed then apply the integer transforms,
8898   // otherwise just apply the common ones.
8899   Value *Src = CI.getOperand(0);
8900   const Type *SrcTy = Src->getType();
8901   const Type *DestTy = CI.getType();
8902
8903   if (isa<PointerType>(SrcTy)) {
8904     if (Instruction *I = commonPointerCastTransforms(CI))
8905       return I;
8906   } else {
8907     if (Instruction *Result = commonCastTransforms(CI))
8908       return Result;
8909   }
8910
8911
8912   // Get rid of casts from one type to the same type. These are useless and can
8913   // be replaced by the operand.
8914   if (DestTy == Src->getType())
8915     return ReplaceInstUsesWith(CI, Src);
8916
8917   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8918     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8919     const Type *DstElTy = DstPTy->getElementType();
8920     const Type *SrcElTy = SrcPTy->getElementType();
8921     
8922     // If the address spaces don't match, don't eliminate the bitcast, which is
8923     // required for changing types.
8924     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8925       return 0;
8926     
8927     // If we are casting a malloc or alloca to a pointer to a type of the same
8928     // size, rewrite the allocation instruction to allocate the "right" type.
8929     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8930       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8931         return V;
8932     
8933     // If the source and destination are pointers, and this cast is equivalent
8934     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8935     // This can enhance SROA and other transforms that want type-safe pointers.
8936     Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
8937     unsigned NumZeros = 0;
8938     while (SrcElTy != DstElTy && 
8939            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8940            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8941       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8942       ++NumZeros;
8943     }
8944
8945     // If we found a path from the src to dest, create the getelementptr now.
8946     if (SrcElTy == DstElTy) {
8947       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8948       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
8949                                        ((Instruction*) NULL));
8950     }
8951   }
8952
8953   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8954     if (DestVTy->getNumElements() == 1) {
8955       if (!isa<VectorType>(SrcTy)) {
8956         Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
8957                                        DestVTy->getElementType(), CI);
8958         return InsertElementInst::Create(Context->getUndef(DestTy), Elem,
8959                                          Context->getNullValue(Type::Int32Ty));
8960       }
8961       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8962     }
8963   }
8964
8965   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8966     if (SrcVTy->getNumElements() == 1) {
8967       if (!isa<VectorType>(DestTy)) {
8968         Instruction *Elem =
8969             new ExtractElementInst(Src, Context->getNullValue(Type::Int32Ty));
8970         InsertNewInstBefore(Elem, CI);
8971         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8972       }
8973     }
8974   }
8975
8976   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8977     if (SVI->hasOneUse()) {
8978       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8979       // a bitconvert to a vector with the same # elts.
8980       if (isa<VectorType>(DestTy) && 
8981           cast<VectorType>(DestTy)->getNumElements() ==
8982                 SVI->getType()->getNumElements() &&
8983           SVI->getType()->getNumElements() ==
8984             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8985         CastInst *Tmp;
8986         // If either of the operands is a cast from CI.getType(), then
8987         // evaluating the shuffle in the casted destination's type will allow
8988         // us to eliminate at least one cast.
8989         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8990              Tmp->getOperand(0)->getType() == DestTy) ||
8991             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8992              Tmp->getOperand(0)->getType() == DestTy)) {
8993           Value *LHS = InsertCastBefore(Instruction::BitCast,
8994                                         SVI->getOperand(0), DestTy, CI);
8995           Value *RHS = InsertCastBefore(Instruction::BitCast,
8996                                         SVI->getOperand(1), DestTy, CI);
8997           // Return a new shuffle vector.  Use the same element ID's, as we
8998           // know the vector types match #elts.
8999           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9000         }
9001       }
9002     }
9003   }
9004   return 0;
9005 }
9006
9007 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9008 ///   %C = or %A, %B
9009 ///   %D = select %cond, %C, %A
9010 /// into:
9011 ///   %C = select %cond, %B, 0
9012 ///   %D = or %A, %C
9013 ///
9014 /// Assuming that the specified instruction is an operand to the select, return
9015 /// a bitmask indicating which operands of this instruction are foldable if they
9016 /// equal the other incoming value of the select.
9017 ///
9018 static unsigned GetSelectFoldableOperands(Instruction *I) {
9019   switch (I->getOpcode()) {
9020   case Instruction::Add:
9021   case Instruction::Mul:
9022   case Instruction::And:
9023   case Instruction::Or:
9024   case Instruction::Xor:
9025     return 3;              // Can fold through either operand.
9026   case Instruction::Sub:   // Can only fold on the amount subtracted.
9027   case Instruction::Shl:   // Can only fold on the shift amount.
9028   case Instruction::LShr:
9029   case Instruction::AShr:
9030     return 1;
9031   default:
9032     return 0;              // Cannot fold
9033   }
9034 }
9035
9036 /// GetSelectFoldableConstant - For the same transformation as the previous
9037 /// function, return the identity constant that goes into the select.
9038 static Constant *GetSelectFoldableConstant(Instruction *I,
9039                                            LLVMContext *Context) {
9040   switch (I->getOpcode()) {
9041   default: llvm_unreachable("This cannot happen!");
9042   case Instruction::Add:
9043   case Instruction::Sub:
9044   case Instruction::Or:
9045   case Instruction::Xor:
9046   case Instruction::Shl:
9047   case Instruction::LShr:
9048   case Instruction::AShr:
9049     return Context->getNullValue(I->getType());
9050   case Instruction::And:
9051     return Context->getAllOnesValue(I->getType());
9052   case Instruction::Mul:
9053     return Context->getConstantInt(I->getType(), 1);
9054   }
9055 }
9056
9057 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9058 /// have the same opcode and only one use each.  Try to simplify this.
9059 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9060                                           Instruction *FI) {
9061   if (TI->getNumOperands() == 1) {
9062     // If this is a non-volatile load or a cast from the same type,
9063     // merge.
9064     if (TI->isCast()) {
9065       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9066         return 0;
9067     } else {
9068       return 0;  // unknown unary op.
9069     }
9070
9071     // Fold this by inserting a select from the input values.
9072     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9073                                            FI->getOperand(0), SI.getName()+".v");
9074     InsertNewInstBefore(NewSI, SI);
9075     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9076                             TI->getType());
9077   }
9078
9079   // Only handle binary operators here.
9080   if (!isa<BinaryOperator>(TI))
9081     return 0;
9082
9083   // Figure out if the operations have any operands in common.
9084   Value *MatchOp, *OtherOpT, *OtherOpF;
9085   bool MatchIsOpZero;
9086   if (TI->getOperand(0) == FI->getOperand(0)) {
9087     MatchOp  = TI->getOperand(0);
9088     OtherOpT = TI->getOperand(1);
9089     OtherOpF = FI->getOperand(1);
9090     MatchIsOpZero = true;
9091   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9092     MatchOp  = TI->getOperand(1);
9093     OtherOpT = TI->getOperand(0);
9094     OtherOpF = FI->getOperand(0);
9095     MatchIsOpZero = false;
9096   } else if (!TI->isCommutative()) {
9097     return 0;
9098   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9099     MatchOp  = TI->getOperand(0);
9100     OtherOpT = TI->getOperand(1);
9101     OtherOpF = FI->getOperand(0);
9102     MatchIsOpZero = true;
9103   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9104     MatchOp  = TI->getOperand(1);
9105     OtherOpT = TI->getOperand(0);
9106     OtherOpF = FI->getOperand(1);
9107     MatchIsOpZero = true;
9108   } else {
9109     return 0;
9110   }
9111
9112   // If we reach here, they do have operations in common.
9113   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9114                                          OtherOpF, SI.getName()+".v");
9115   InsertNewInstBefore(NewSI, SI);
9116
9117   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9118     if (MatchIsOpZero)
9119       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9120     else
9121       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9122   }
9123   llvm_unreachable("Shouldn't get here");
9124   return 0;
9125 }
9126
9127 static bool isSelect01(Constant *C1, Constant *C2) {
9128   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9129   if (!C1I)
9130     return false;
9131   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9132   if (!C2I)
9133     return false;
9134   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9135 }
9136
9137 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9138 /// facilitate further optimization.
9139 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9140                                             Value *FalseVal) {
9141   // See the comment above GetSelectFoldableOperands for a description of the
9142   // transformation we are doing here.
9143   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9144     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9145         !isa<Constant>(FalseVal)) {
9146       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9147         unsigned OpToFold = 0;
9148         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9149           OpToFold = 1;
9150         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9151           OpToFold = 2;
9152         }
9153
9154         if (OpToFold) {
9155           Constant *C = GetSelectFoldableConstant(TVI, Context);
9156           Value *OOp = TVI->getOperand(2-OpToFold);
9157           // Avoid creating select between 2 constants unless it's selecting
9158           // between 0 and 1.
9159           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9160             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9161             InsertNewInstBefore(NewSel, SI);
9162             NewSel->takeName(TVI);
9163             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9164               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9165             llvm_unreachable("Unknown instruction!!");
9166           }
9167         }
9168       }
9169     }
9170   }
9171
9172   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9173     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9174         !isa<Constant>(TrueVal)) {
9175       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9176         unsigned OpToFold = 0;
9177         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9178           OpToFold = 1;
9179         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9180           OpToFold = 2;
9181         }
9182
9183         if (OpToFold) {
9184           Constant *C = GetSelectFoldableConstant(FVI, Context);
9185           Value *OOp = FVI->getOperand(2-OpToFold);
9186           // Avoid creating select between 2 constants unless it's selecting
9187           // between 0 and 1.
9188           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9189             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9190             InsertNewInstBefore(NewSel, SI);
9191             NewSel->takeName(FVI);
9192             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9193               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9194             llvm_unreachable("Unknown instruction!!");
9195           }
9196         }
9197       }
9198     }
9199   }
9200
9201   return 0;
9202 }
9203
9204 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9205 /// ICmpInst as its first operand.
9206 ///
9207 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9208                                                    ICmpInst *ICI) {
9209   bool Changed = false;
9210   ICmpInst::Predicate Pred = ICI->getPredicate();
9211   Value *CmpLHS = ICI->getOperand(0);
9212   Value *CmpRHS = ICI->getOperand(1);
9213   Value *TrueVal = SI.getTrueValue();
9214   Value *FalseVal = SI.getFalseValue();
9215
9216   // Check cases where the comparison is with a constant that
9217   // can be adjusted to fit the min/max idiom. We may edit ICI in
9218   // place here, so make sure the select is the only user.
9219   if (ICI->hasOneUse())
9220     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9221       switch (Pred) {
9222       default: break;
9223       case ICmpInst::ICMP_ULT:
9224       case ICmpInst::ICMP_SLT: {
9225         // X < MIN ? T : F  -->  F
9226         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9227           return ReplaceInstUsesWith(SI, FalseVal);
9228         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9229         Constant *AdjustedRHS = SubOne(CI, Context);
9230         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9231             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9232           Pred = ICmpInst::getSwappedPredicate(Pred);
9233           CmpRHS = AdjustedRHS;
9234           std::swap(FalseVal, TrueVal);
9235           ICI->setPredicate(Pred);
9236           ICI->setOperand(1, CmpRHS);
9237           SI.setOperand(1, TrueVal);
9238           SI.setOperand(2, FalseVal);
9239           Changed = true;
9240         }
9241         break;
9242       }
9243       case ICmpInst::ICMP_UGT:
9244       case ICmpInst::ICMP_SGT: {
9245         // X > MAX ? T : F  -->  F
9246         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9247           return ReplaceInstUsesWith(SI, FalseVal);
9248         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9249         Constant *AdjustedRHS = AddOne(CI, Context);
9250         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9251             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9252           Pred = ICmpInst::getSwappedPredicate(Pred);
9253           CmpRHS = AdjustedRHS;
9254           std::swap(FalseVal, TrueVal);
9255           ICI->setPredicate(Pred);
9256           ICI->setOperand(1, CmpRHS);
9257           SI.setOperand(1, TrueVal);
9258           SI.setOperand(2, FalseVal);
9259           Changed = true;
9260         }
9261         break;
9262       }
9263       }
9264
9265       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9266       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9267       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9268       if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9269           match(FalseVal, m_ConstantInt<0>(), *Context))
9270         Pred = ICI->getPredicate();
9271       else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9272                match(FalseVal, m_ConstantInt<-1>(), *Context))
9273         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9274       
9275       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9276         // If we are just checking for a icmp eq of a single bit and zext'ing it
9277         // to an integer, then shift the bit to the appropriate place and then
9278         // cast to integer to avoid the comparison.
9279         const APInt &Op1CV = CI->getValue();
9280     
9281         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9282         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9283         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9284             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9285           Value *In = ICI->getOperand(0);
9286           Value *Sh = Context->getConstantInt(In->getType(),
9287                                        In->getType()->getScalarSizeInBits()-1);
9288           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9289                                                           In->getName()+".lobit"),
9290                                    *ICI);
9291           if (In->getType() != SI.getType())
9292             In = CastInst::CreateIntegerCast(In, SI.getType(),
9293                                              true/*SExt*/, "tmp", ICI);
9294     
9295           if (Pred == ICmpInst::ICMP_SGT)
9296             In = InsertNewInstBefore(BinaryOperator::CreateNot(*Context, In,
9297                                        In->getName()+".not"), *ICI);
9298     
9299           return ReplaceInstUsesWith(SI, In);
9300         }
9301       }
9302     }
9303
9304   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9305     // Transform (X == Y) ? X : Y  -> Y
9306     if (Pred == ICmpInst::ICMP_EQ)
9307       return ReplaceInstUsesWith(SI, FalseVal);
9308     // Transform (X != Y) ? X : Y  -> X
9309     if (Pred == ICmpInst::ICMP_NE)
9310       return ReplaceInstUsesWith(SI, TrueVal);
9311     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9312
9313   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9314     // Transform (X == Y) ? Y : X  -> X
9315     if (Pred == ICmpInst::ICMP_EQ)
9316       return ReplaceInstUsesWith(SI, FalseVal);
9317     // Transform (X != Y) ? Y : X  -> Y
9318     if (Pred == ICmpInst::ICMP_NE)
9319       return ReplaceInstUsesWith(SI, TrueVal);
9320     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9321   }
9322
9323   /// NOTE: if we wanted to, this is where to detect integer ABS
9324
9325   return Changed ? &SI : 0;
9326 }
9327
9328 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9329   Value *CondVal = SI.getCondition();
9330   Value *TrueVal = SI.getTrueValue();
9331   Value *FalseVal = SI.getFalseValue();
9332
9333   // select true, X, Y  -> X
9334   // select false, X, Y -> Y
9335   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9336     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9337
9338   // select C, X, X -> X
9339   if (TrueVal == FalseVal)
9340     return ReplaceInstUsesWith(SI, TrueVal);
9341
9342   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9343     return ReplaceInstUsesWith(SI, FalseVal);
9344   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9345     return ReplaceInstUsesWith(SI, TrueVal);
9346   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9347     if (isa<Constant>(TrueVal))
9348       return ReplaceInstUsesWith(SI, TrueVal);
9349     else
9350       return ReplaceInstUsesWith(SI, FalseVal);
9351   }
9352
9353   if (SI.getType() == Type::Int1Ty) {
9354     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9355       if (C->getZExtValue()) {
9356         // Change: A = select B, true, C --> A = or B, C
9357         return BinaryOperator::CreateOr(CondVal, FalseVal);
9358       } else {
9359         // Change: A = select B, false, C --> A = and !B, C
9360         Value *NotCond =
9361           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9362                                              "not."+CondVal->getName()), SI);
9363         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9364       }
9365     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9366       if (C->getZExtValue() == false) {
9367         // Change: A = select B, C, false --> A = and B, C
9368         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9369       } else {
9370         // Change: A = select B, C, true --> A = or !B, C
9371         Value *NotCond =
9372           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9373                                              "not."+CondVal->getName()), SI);
9374         return BinaryOperator::CreateOr(NotCond, TrueVal);
9375       }
9376     }
9377     
9378     // select a, b, a  -> a&b
9379     // select a, a, b  -> a|b
9380     if (CondVal == TrueVal)
9381       return BinaryOperator::CreateOr(CondVal, FalseVal);
9382     else if (CondVal == FalseVal)
9383       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9384   }
9385
9386   // Selecting between two integer constants?
9387   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9388     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9389       // select C, 1, 0 -> zext C to int
9390       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9391         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9392       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9393         // select C, 0, 1 -> zext !C to int
9394         Value *NotCond =
9395           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9396                                                "not."+CondVal->getName()), SI);
9397         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9398       }
9399
9400       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9401         // If one of the constants is zero (we know they can't both be) and we
9402         // have an icmp instruction with zero, and we have an 'and' with the
9403         // non-constant value, eliminate this whole mess.  This corresponds to
9404         // cases like this: ((X & 27) ? 27 : 0)
9405         if (TrueValC->isZero() || FalseValC->isZero())
9406           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9407               cast<Constant>(IC->getOperand(1))->isNullValue())
9408             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9409               if (ICA->getOpcode() == Instruction::And &&
9410                   isa<ConstantInt>(ICA->getOperand(1)) &&
9411                   (ICA->getOperand(1) == TrueValC ||
9412                    ICA->getOperand(1) == FalseValC) &&
9413                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9414                 // Okay, now we know that everything is set up, we just don't
9415                 // know whether we have a icmp_ne or icmp_eq and whether the 
9416                 // true or false val is the zero.
9417                 bool ShouldNotVal = !TrueValC->isZero();
9418                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9419                 Value *V = ICA;
9420                 if (ShouldNotVal)
9421                   V = InsertNewInstBefore(BinaryOperator::Create(
9422                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9423                 return ReplaceInstUsesWith(SI, V);
9424               }
9425       }
9426     }
9427
9428   // See if we are selecting two values based on a comparison of the two values.
9429   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9430     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9431       // Transform (X == Y) ? X : Y  -> Y
9432       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9433         // This is not safe in general for floating point:  
9434         // consider X== -0, Y== +0.
9435         // It becomes safe if either operand is a nonzero constant.
9436         ConstantFP *CFPt, *CFPf;
9437         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9438               !CFPt->getValueAPF().isZero()) ||
9439             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9440              !CFPf->getValueAPF().isZero()))
9441         return ReplaceInstUsesWith(SI, FalseVal);
9442       }
9443       // Transform (X != Y) ? X : Y  -> X
9444       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9445         return ReplaceInstUsesWith(SI, TrueVal);
9446       // NOTE: if we wanted to, this is where to detect MIN/MAX
9447
9448     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9449       // Transform (X == Y) ? Y : X  -> X
9450       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9451         // This is not safe in general for floating point:  
9452         // consider X== -0, Y== +0.
9453         // It becomes safe if either operand is a nonzero constant.
9454         ConstantFP *CFPt, *CFPf;
9455         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9456               !CFPt->getValueAPF().isZero()) ||
9457             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9458              !CFPf->getValueAPF().isZero()))
9459           return ReplaceInstUsesWith(SI, FalseVal);
9460       }
9461       // Transform (X != Y) ? Y : X  -> Y
9462       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9463         return ReplaceInstUsesWith(SI, TrueVal);
9464       // NOTE: if we wanted to, this is where to detect MIN/MAX
9465     }
9466     // NOTE: if we wanted to, this is where to detect ABS
9467   }
9468
9469   // See if we are selecting two values based on a comparison of the two values.
9470   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9471     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9472       return Result;
9473
9474   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9475     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9476       if (TI->hasOneUse() && FI->hasOneUse()) {
9477         Instruction *AddOp = 0, *SubOp = 0;
9478
9479         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9480         if (TI->getOpcode() == FI->getOpcode())
9481           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9482             return IV;
9483
9484         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9485         // even legal for FP.
9486         if ((TI->getOpcode() == Instruction::Sub &&
9487              FI->getOpcode() == Instruction::Add) ||
9488             (TI->getOpcode() == Instruction::FSub &&
9489              FI->getOpcode() == Instruction::FAdd)) {
9490           AddOp = FI; SubOp = TI;
9491         } else if ((FI->getOpcode() == Instruction::Sub &&
9492                     TI->getOpcode() == Instruction::Add) ||
9493                    (FI->getOpcode() == Instruction::FSub &&
9494                     TI->getOpcode() == Instruction::FAdd)) {
9495           AddOp = TI; SubOp = FI;
9496         }
9497
9498         if (AddOp) {
9499           Value *OtherAddOp = 0;
9500           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9501             OtherAddOp = AddOp->getOperand(1);
9502           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9503             OtherAddOp = AddOp->getOperand(0);
9504           }
9505
9506           if (OtherAddOp) {
9507             // So at this point we know we have (Y -> OtherAddOp):
9508             //        select C, (add X, Y), (sub X, Z)
9509             Value *NegVal;  // Compute -Z
9510             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9511               NegVal = Context->getConstantExprNeg(C);
9512             } else {
9513               NegVal = InsertNewInstBefore(
9514                     BinaryOperator::CreateNeg(*Context, SubOp->getOperand(1),
9515                                               "tmp"), SI);
9516             }
9517
9518             Value *NewTrueOp = OtherAddOp;
9519             Value *NewFalseOp = NegVal;
9520             if (AddOp != TI)
9521               std::swap(NewTrueOp, NewFalseOp);
9522             Instruction *NewSel =
9523               SelectInst::Create(CondVal, NewTrueOp,
9524                                  NewFalseOp, SI.getName() + ".p");
9525
9526             NewSel = InsertNewInstBefore(NewSel, SI);
9527             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9528           }
9529         }
9530       }
9531
9532   // See if we can fold the select into one of our operands.
9533   if (SI.getType()->isInteger()) {
9534     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9535     if (FoldI)
9536       return FoldI;
9537   }
9538
9539   if (BinaryOperator::isNot(CondVal)) {
9540     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9541     SI.setOperand(1, FalseVal);
9542     SI.setOperand(2, TrueVal);
9543     return &SI;
9544   }
9545
9546   return 0;
9547 }
9548
9549 /// EnforceKnownAlignment - If the specified pointer points to an object that
9550 /// we control, modify the object's alignment to PrefAlign. This isn't
9551 /// often possible though. If alignment is important, a more reliable approach
9552 /// is to simply align all global variables and allocation instructions to
9553 /// their preferred alignment from the beginning.
9554 ///
9555 static unsigned EnforceKnownAlignment(Value *V,
9556                                       unsigned Align, unsigned PrefAlign) {
9557
9558   User *U = dyn_cast<User>(V);
9559   if (!U) return Align;
9560
9561   switch (Operator::getOpcode(U)) {
9562   default: break;
9563   case Instruction::BitCast:
9564     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9565   case Instruction::GetElementPtr: {
9566     // If all indexes are zero, it is just the alignment of the base pointer.
9567     bool AllZeroOperands = true;
9568     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9569       if (!isa<Constant>(*i) ||
9570           !cast<Constant>(*i)->isNullValue()) {
9571         AllZeroOperands = false;
9572         break;
9573       }
9574
9575     if (AllZeroOperands) {
9576       // Treat this like a bitcast.
9577       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9578     }
9579     break;
9580   }
9581   }
9582
9583   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9584     // If there is a large requested alignment and we can, bump up the alignment
9585     // of the global.
9586     if (!GV->isDeclaration()) {
9587       if (GV->getAlignment() >= PrefAlign)
9588         Align = GV->getAlignment();
9589       else {
9590         GV->setAlignment(PrefAlign);
9591         Align = PrefAlign;
9592       }
9593     }
9594   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9595     // If there is a requested alignment and if this is an alloca, round up.  We
9596     // don't do this for malloc, because some systems can't respect the request.
9597     if (isa<AllocaInst>(AI)) {
9598       if (AI->getAlignment() >= PrefAlign)
9599         Align = AI->getAlignment();
9600       else {
9601         AI->setAlignment(PrefAlign);
9602         Align = PrefAlign;
9603       }
9604     }
9605   }
9606
9607   return Align;
9608 }
9609
9610 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9611 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9612 /// and it is more than the alignment of the ultimate object, see if we can
9613 /// increase the alignment of the ultimate object, making this check succeed.
9614 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9615                                                   unsigned PrefAlign) {
9616   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9617                       sizeof(PrefAlign) * CHAR_BIT;
9618   APInt Mask = APInt::getAllOnesValue(BitWidth);
9619   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9620   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9621   unsigned TrailZ = KnownZero.countTrailingOnes();
9622   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9623
9624   if (PrefAlign > Align)
9625     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9626   
9627     // We don't need to make any adjustment.
9628   return Align;
9629 }
9630
9631 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9632   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9633   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9634   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9635   unsigned CopyAlign = MI->getAlignment();
9636
9637   if (CopyAlign < MinAlign) {
9638     MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(), 
9639                                              MinAlign, false));
9640     return MI;
9641   }
9642   
9643   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9644   // load/store.
9645   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9646   if (MemOpLength == 0) return 0;
9647   
9648   // Source and destination pointer types are always "i8*" for intrinsic.  See
9649   // if the size is something we can handle with a single primitive load/store.
9650   // A single load+store correctly handles overlapping memory in the memmove
9651   // case.
9652   unsigned Size = MemOpLength->getZExtValue();
9653   if (Size == 0) return MI;  // Delete this mem transfer.
9654   
9655   if (Size > 8 || (Size&(Size-1)))
9656     return 0;  // If not 1/2/4/8 bytes, exit.
9657   
9658   // Use an integer load+store unless we can find something better.
9659   Type *NewPtrTy =
9660                 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
9661   
9662   // Memcpy forces the use of i8* for the source and destination.  That means
9663   // that if you're using memcpy to move one double around, you'll get a cast
9664   // from double* to i8*.  We'd much rather use a double load+store rather than
9665   // an i64 load+store, here because this improves the odds that the source or
9666   // dest address will be promotable.  See if we can find a better type than the
9667   // integer datatype.
9668   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9669     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9670     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9671       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9672       // down through these levels if so.
9673       while (!SrcETy->isSingleValueType()) {
9674         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9675           if (STy->getNumElements() == 1)
9676             SrcETy = STy->getElementType(0);
9677           else
9678             break;
9679         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9680           if (ATy->getNumElements() == 1)
9681             SrcETy = ATy->getElementType();
9682           else
9683             break;
9684         } else
9685           break;
9686       }
9687       
9688       if (SrcETy->isSingleValueType())
9689         NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
9690     }
9691   }
9692   
9693   
9694   // If the memcpy/memmove provides better alignment info than we can
9695   // infer, use it.
9696   SrcAlign = std::max(SrcAlign, CopyAlign);
9697   DstAlign = std::max(DstAlign, CopyAlign);
9698   
9699   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9700   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9701   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9702   InsertNewInstBefore(L, *MI);
9703   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9704
9705   // Set the size of the copy to 0, it will be deleted on the next iteration.
9706   MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
9707   return MI;
9708 }
9709
9710 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9711   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9712   if (MI->getAlignment() < Alignment) {
9713     MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9714                                              Alignment, false));
9715     return MI;
9716   }
9717   
9718   // Extract the length and alignment and fill if they are constant.
9719   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9720   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9721   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9722     return 0;
9723   uint64_t Len = LenC->getZExtValue();
9724   Alignment = MI->getAlignment();
9725   
9726   // If the length is zero, this is a no-op
9727   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9728   
9729   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9730   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9731     const Type *ITy = Context->getIntegerType(Len*8);  // n=1 -> i8.
9732     
9733     Value *Dest = MI->getDest();
9734     Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
9735
9736     // Alignment 0 is identity for alignment 1 for memset, but not store.
9737     if (Alignment == 0) Alignment = 1;
9738     
9739     // Extract the fill value and store.
9740     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9741     InsertNewInstBefore(new StoreInst(Context->getConstantInt(ITy, Fill),
9742                                       Dest, false, Alignment), *MI);
9743     
9744     // Set the size of the copy to 0, it will be deleted on the next iteration.
9745     MI->setLength(Context->getNullValue(LenC->getType()));
9746     return MI;
9747   }
9748
9749   return 0;
9750 }
9751
9752
9753 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9754 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9755 /// the heavy lifting.
9756 ///
9757 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9758   // If the caller function is nounwind, mark the call as nounwind, even if the
9759   // callee isn't.
9760   if (CI.getParent()->getParent()->doesNotThrow() &&
9761       !CI.doesNotThrow()) {
9762     CI.setDoesNotThrow();
9763     return &CI;
9764   }
9765   
9766   
9767   
9768   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9769   if (!II) return visitCallSite(&CI);
9770   
9771   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9772   // visitCallSite.
9773   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9774     bool Changed = false;
9775
9776     // memmove/cpy/set of zero bytes is a noop.
9777     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9778       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9779
9780       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9781         if (CI->getZExtValue() == 1) {
9782           // Replace the instruction with just byte operations.  We would
9783           // transform other cases to loads/stores, but we don't know if
9784           // alignment is sufficient.
9785         }
9786     }
9787
9788     // If we have a memmove and the source operation is a constant global,
9789     // then the source and dest pointers can't alias, so we can change this
9790     // into a call to memcpy.
9791     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9792       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9793         if (GVSrc->isConstant()) {
9794           Module *M = CI.getParent()->getParent()->getParent();
9795           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9796           const Type *Tys[1];
9797           Tys[0] = CI.getOperand(3)->getType();
9798           CI.setOperand(0, 
9799                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9800           Changed = true;
9801         }
9802
9803       // memmove(x,x,size) -> noop.
9804       if (MMI->getSource() == MMI->getDest())
9805         return EraseInstFromFunction(CI);
9806     }
9807
9808     // If we can determine a pointer alignment that is bigger than currently
9809     // set, update the alignment.
9810     if (isa<MemTransferInst>(MI)) {
9811       if (Instruction *I = SimplifyMemTransfer(MI))
9812         return I;
9813     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9814       if (Instruction *I = SimplifyMemSet(MSI))
9815         return I;
9816     }
9817           
9818     if (Changed) return II;
9819   }
9820   
9821   switch (II->getIntrinsicID()) {
9822   default: break;
9823   case Intrinsic::bswap:
9824     // bswap(bswap(x)) -> x
9825     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9826       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9827         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9828     break;
9829   case Intrinsic::ppc_altivec_lvx:
9830   case Intrinsic::ppc_altivec_lvxl:
9831   case Intrinsic::x86_sse_loadu_ps:
9832   case Intrinsic::x86_sse2_loadu_pd:
9833   case Intrinsic::x86_sse2_loadu_dq:
9834     // Turn PPC lvx     -> load if the pointer is known aligned.
9835     // Turn X86 loadups -> load if the pointer is known aligned.
9836     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9837       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9838                                    Context->getPointerTypeUnqual(II->getType()),
9839                                        CI);
9840       return new LoadInst(Ptr);
9841     }
9842     break;
9843   case Intrinsic::ppc_altivec_stvx:
9844   case Intrinsic::ppc_altivec_stvxl:
9845     // Turn stvx -> store if the pointer is known aligned.
9846     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9847       const Type *OpPtrTy = 
9848         Context->getPointerTypeUnqual(II->getOperand(1)->getType());
9849       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9850       return new StoreInst(II->getOperand(1), Ptr);
9851     }
9852     break;
9853   case Intrinsic::x86_sse_storeu_ps:
9854   case Intrinsic::x86_sse2_storeu_pd:
9855   case Intrinsic::x86_sse2_storeu_dq:
9856     // Turn X86 storeu -> store if the pointer is known aligned.
9857     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9858       const Type *OpPtrTy = 
9859         Context->getPointerTypeUnqual(II->getOperand(2)->getType());
9860       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9861       return new StoreInst(II->getOperand(2), Ptr);
9862     }
9863     break;
9864     
9865   case Intrinsic::x86_sse_cvttss2si: {
9866     // These intrinsics only demands the 0th element of its input vector.  If
9867     // we can simplify the input based on that, do so now.
9868     unsigned VWidth =
9869       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9870     APInt DemandedElts(VWidth, 1);
9871     APInt UndefElts(VWidth, 0);
9872     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9873                                               UndefElts)) {
9874       II->setOperand(1, V);
9875       return II;
9876     }
9877     break;
9878   }
9879     
9880   case Intrinsic::ppc_altivec_vperm:
9881     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9882     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9883       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9884       
9885       // Check that all of the elements are integer constants or undefs.
9886       bool AllEltsOk = true;
9887       for (unsigned i = 0; i != 16; ++i) {
9888         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9889             !isa<UndefValue>(Mask->getOperand(i))) {
9890           AllEltsOk = false;
9891           break;
9892         }
9893       }
9894       
9895       if (AllEltsOk) {
9896         // Cast the input vectors to byte vectors.
9897         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9898         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9899         Value *Result = Context->getUndef(Op0->getType());
9900         
9901         // Only extract each element once.
9902         Value *ExtractedElts[32];
9903         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9904         
9905         for (unsigned i = 0; i != 16; ++i) {
9906           if (isa<UndefValue>(Mask->getOperand(i)))
9907             continue;
9908           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9909           Idx &= 31;  // Match the hardware behavior.
9910           
9911           if (ExtractedElts[Idx] == 0) {
9912             Instruction *Elt = 
9913               new ExtractElementInst(Idx < 16 ? Op0 : Op1, 
9914                   Context->getConstantInt(Type::Int32Ty, Idx&15, false), "tmp");
9915             InsertNewInstBefore(Elt, CI);
9916             ExtractedElts[Idx] = Elt;
9917           }
9918         
9919           // Insert this value into the result vector.
9920           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9921                                Context->getConstantInt(Type::Int32Ty, i, false), 
9922                                "tmp");
9923           InsertNewInstBefore(cast<Instruction>(Result), CI);
9924         }
9925         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9926       }
9927     }
9928     break;
9929
9930   case Intrinsic::stackrestore: {
9931     // If the save is right next to the restore, remove the restore.  This can
9932     // happen when variable allocas are DCE'd.
9933     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9934       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9935         BasicBlock::iterator BI = SS;
9936         if (&*++BI == II)
9937           return EraseInstFromFunction(CI);
9938       }
9939     }
9940     
9941     // Scan down this block to see if there is another stack restore in the
9942     // same block without an intervening call/alloca.
9943     BasicBlock::iterator BI = II;
9944     TerminatorInst *TI = II->getParent()->getTerminator();
9945     bool CannotRemove = false;
9946     for (++BI; &*BI != TI; ++BI) {
9947       if (isa<AllocaInst>(BI)) {
9948         CannotRemove = true;
9949         break;
9950       }
9951       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9952         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9953           // If there is a stackrestore below this one, remove this one.
9954           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9955             return EraseInstFromFunction(CI);
9956           // Otherwise, ignore the intrinsic.
9957         } else {
9958           // If we found a non-intrinsic call, we can't remove the stack
9959           // restore.
9960           CannotRemove = true;
9961           break;
9962         }
9963       }
9964     }
9965     
9966     // If the stack restore is in a return/unwind block and if there are no
9967     // allocas or calls between the restore and the return, nuke the restore.
9968     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9969       return EraseInstFromFunction(CI);
9970     break;
9971   }
9972   }
9973
9974   return visitCallSite(II);
9975 }
9976
9977 // InvokeInst simplification
9978 //
9979 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9980   return visitCallSite(&II);
9981 }
9982
9983 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9984 /// passed through the varargs area, we can eliminate the use of the cast.
9985 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9986                                          const CastInst * const CI,
9987                                          const TargetData * const TD,
9988                                          const int ix) {
9989   if (!CI->isLosslessCast())
9990     return false;
9991
9992   // The size of ByVal arguments is derived from the type, so we
9993   // can't change to a type with a different size.  If the size were
9994   // passed explicitly we could avoid this check.
9995   if (!CS.paramHasAttr(ix, Attribute::ByVal))
9996     return true;
9997
9998   const Type* SrcTy = 
9999             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10000   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10001   if (!SrcTy->isSized() || !DstTy->isSized())
10002     return false;
10003   if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10004     return false;
10005   return true;
10006 }
10007
10008 // visitCallSite - Improvements for call and invoke instructions.
10009 //
10010 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10011   bool Changed = false;
10012
10013   // If the callee is a constexpr cast of a function, attempt to move the cast
10014   // to the arguments of the call/invoke.
10015   if (transformConstExprCastCall(CS)) return 0;
10016
10017   Value *Callee = CS.getCalledValue();
10018
10019   if (Function *CalleeF = dyn_cast<Function>(Callee))
10020     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10021       Instruction *OldCall = CS.getInstruction();
10022       // If the call and callee calling conventions don't match, this call must
10023       // be unreachable, as the call is undefined.
10024       new StoreInst(Context->getTrue(),
10025                 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), 
10026                                   OldCall);
10027       if (!OldCall->use_empty())
10028         OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
10029       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10030         return EraseInstFromFunction(*OldCall);
10031       return 0;
10032     }
10033
10034   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10035     // This instruction is not reachable, just remove it.  We insert a store to
10036     // undef so that we know that this code is not reachable, despite the fact
10037     // that we can't modify the CFG here.
10038     new StoreInst(Context->getTrue(),
10039                Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10040                   CS.getInstruction());
10041
10042     if (!CS.getInstruction()->use_empty())
10043       CS.getInstruction()->
10044         replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
10045
10046     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10047       // Don't break the CFG, insert a dummy cond branch.
10048       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10049                          Context->getTrue(), II);
10050     }
10051     return EraseInstFromFunction(*CS.getInstruction());
10052   }
10053
10054   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10055     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10056       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10057         return transformCallThroughTrampoline(CS);
10058
10059   const PointerType *PTy = cast<PointerType>(Callee->getType());
10060   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10061   if (FTy->isVarArg()) {
10062     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10063     // See if we can optimize any arguments passed through the varargs area of
10064     // the call.
10065     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10066            E = CS.arg_end(); I != E; ++I, ++ix) {
10067       CastInst *CI = dyn_cast<CastInst>(*I);
10068       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10069         *I = CI->getOperand(0);
10070         Changed = true;
10071       }
10072     }
10073   }
10074
10075   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10076     // Inline asm calls cannot throw - mark them 'nounwind'.
10077     CS.setDoesNotThrow();
10078     Changed = true;
10079   }
10080
10081   return Changed ? CS.getInstruction() : 0;
10082 }
10083
10084 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10085 // attempt to move the cast to the arguments of the call/invoke.
10086 //
10087 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10088   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10089   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10090   if (CE->getOpcode() != Instruction::BitCast || 
10091       !isa<Function>(CE->getOperand(0)))
10092     return false;
10093   Function *Callee = cast<Function>(CE->getOperand(0));
10094   Instruction *Caller = CS.getInstruction();
10095   const AttrListPtr &CallerPAL = CS.getAttributes();
10096
10097   // Okay, this is a cast from a function to a different type.  Unless doing so
10098   // would cause a type conversion of one of our arguments, change this call to
10099   // be a direct call with arguments casted to the appropriate types.
10100   //
10101   const FunctionType *FT = Callee->getFunctionType();
10102   const Type *OldRetTy = Caller->getType();
10103   const Type *NewRetTy = FT->getReturnType();
10104
10105   if (isa<StructType>(NewRetTy))
10106     return false; // TODO: Handle multiple return values.
10107
10108   // Check to see if we are changing the return type...
10109   if (OldRetTy != NewRetTy) {
10110     if (Callee->isDeclaration() &&
10111         // Conversion is ok if changing from one pointer type to another or from
10112         // a pointer to an integer of the same size.
10113         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
10114           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
10115       return false;   // Cannot transform this return value.
10116
10117     if (!Caller->use_empty() &&
10118         // void -> non-void is handled specially
10119         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
10120       return false;   // Cannot transform this return value.
10121
10122     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10123       Attributes RAttrs = CallerPAL.getRetAttributes();
10124       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10125         return false;   // Attribute not compatible with transformed value.
10126     }
10127
10128     // If the callsite is an invoke instruction, and the return value is used by
10129     // a PHI node in a successor, we cannot change the return type of the call
10130     // because there is no place to put the cast instruction (without breaking
10131     // the critical edge).  Bail out in this case.
10132     if (!Caller->use_empty())
10133       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10134         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10135              UI != E; ++UI)
10136           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10137             if (PN->getParent() == II->getNormalDest() ||
10138                 PN->getParent() == II->getUnwindDest())
10139               return false;
10140   }
10141
10142   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10143   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10144
10145   CallSite::arg_iterator AI = CS.arg_begin();
10146   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10147     const Type *ParamTy = FT->getParamType(i);
10148     const Type *ActTy = (*AI)->getType();
10149
10150     if (!CastInst::isCastable(ActTy, ParamTy))
10151       return false;   // Cannot transform this parameter value.
10152
10153     if (CallerPAL.getParamAttributes(i + 1) 
10154         & Attribute::typeIncompatible(ParamTy))
10155       return false;   // Attribute not compatible with transformed value.
10156
10157     // Converting from one pointer type to another or between a pointer and an
10158     // integer of the same size is safe even if we do not have a body.
10159     bool isConvertible = ActTy == ParamTy ||
10160       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10161        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
10162     if (Callee->isDeclaration() && !isConvertible) return false;
10163   }
10164
10165   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10166       Callee->isDeclaration())
10167     return false;   // Do not delete arguments unless we have a function body.
10168
10169   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10170       !CallerPAL.isEmpty())
10171     // In this case we have more arguments than the new function type, but we
10172     // won't be dropping them.  Check that these extra arguments have attributes
10173     // that are compatible with being a vararg call argument.
10174     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10175       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10176         break;
10177       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10178       if (PAttrs & Attribute::VarArgsIncompatible)
10179         return false;
10180     }
10181
10182   // Okay, we decided that this is a safe thing to do: go ahead and start
10183   // inserting cast instructions as necessary...
10184   std::vector<Value*> Args;
10185   Args.reserve(NumActualArgs);
10186   SmallVector<AttributeWithIndex, 8> attrVec;
10187   attrVec.reserve(NumCommonArgs);
10188
10189   // Get any return attributes.
10190   Attributes RAttrs = CallerPAL.getRetAttributes();
10191
10192   // If the return value is not being used, the type may not be compatible
10193   // with the existing attributes.  Wipe out any problematic attributes.
10194   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10195
10196   // Add the new return attributes.
10197   if (RAttrs)
10198     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10199
10200   AI = CS.arg_begin();
10201   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10202     const Type *ParamTy = FT->getParamType(i);
10203     if ((*AI)->getType() == ParamTy) {
10204       Args.push_back(*AI);
10205     } else {
10206       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10207           false, ParamTy, false);
10208       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10209       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10210     }
10211
10212     // Add any parameter attributes.
10213     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10214       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10215   }
10216
10217   // If the function takes more arguments than the call was taking, add them
10218   // now...
10219   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10220     Args.push_back(Context->getNullValue(FT->getParamType(i)));
10221
10222   // If we are removing arguments to the function, emit an obnoxious warning...
10223   if (FT->getNumParams() < NumActualArgs) {
10224     if (!FT->isVarArg()) {
10225       cerr << "WARNING: While resolving call to function '"
10226            << Callee->getName() << "' arguments were dropped!\n";
10227     } else {
10228       // Add all of the arguments in their promoted form to the arg list...
10229       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10230         const Type *PTy = getPromotedType((*AI)->getType());
10231         if (PTy != (*AI)->getType()) {
10232           // Must promote to pass through va_arg area!
10233           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
10234                                                                 PTy, false);
10235           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10236           InsertNewInstBefore(Cast, *Caller);
10237           Args.push_back(Cast);
10238         } else {
10239           Args.push_back(*AI);
10240         }
10241
10242         // Add any parameter attributes.
10243         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10244           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10245       }
10246     }
10247   }
10248
10249   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10250     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10251
10252   if (NewRetTy == Type::VoidTy)
10253     Caller->setName("");   // Void type should not have a name.
10254
10255   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
10256
10257   Instruction *NC;
10258   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10259     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10260                             Args.begin(), Args.end(),
10261                             Caller->getName(), Caller);
10262     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10263     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10264   } else {
10265     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10266                           Caller->getName(), Caller);
10267     CallInst *CI = cast<CallInst>(Caller);
10268     if (CI->isTailCall())
10269       cast<CallInst>(NC)->setTailCall();
10270     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10271     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10272   }
10273
10274   // Insert a cast of the return type as necessary.
10275   Value *NV = NC;
10276   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10277     if (NV->getType() != Type::VoidTy) {
10278       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10279                                                             OldRetTy, false);
10280       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10281
10282       // If this is an invoke instruction, we should insert it after the first
10283       // non-phi, instruction in the normal successor block.
10284       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10285         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10286         InsertNewInstBefore(NC, *I);
10287       } else {
10288         // Otherwise, it's a call, just insert cast right after the call instr
10289         InsertNewInstBefore(NC, *Caller);
10290       }
10291       AddUsersToWorkList(*Caller);
10292     } else {
10293       NV = Context->getUndef(Caller->getType());
10294     }
10295   }
10296
10297   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10298     Caller->replaceAllUsesWith(NV);
10299   Caller->eraseFromParent();
10300   RemoveFromWorkList(Caller);
10301   return true;
10302 }
10303
10304 // transformCallThroughTrampoline - Turn a call to a function created by the
10305 // init_trampoline intrinsic into a direct call to the underlying function.
10306 //
10307 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10308   Value *Callee = CS.getCalledValue();
10309   const PointerType *PTy = cast<PointerType>(Callee->getType());
10310   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10311   const AttrListPtr &Attrs = CS.getAttributes();
10312
10313   // If the call already has the 'nest' attribute somewhere then give up -
10314   // otherwise 'nest' would occur twice after splicing in the chain.
10315   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10316     return 0;
10317
10318   IntrinsicInst *Tramp =
10319     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10320
10321   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10322   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10323   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10324
10325   const AttrListPtr &NestAttrs = NestF->getAttributes();
10326   if (!NestAttrs.isEmpty()) {
10327     unsigned NestIdx = 1;
10328     const Type *NestTy = 0;
10329     Attributes NestAttr = Attribute::None;
10330
10331     // Look for a parameter marked with the 'nest' attribute.
10332     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10333          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10334       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10335         // Record the parameter type and any other attributes.
10336         NestTy = *I;
10337         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10338         break;
10339       }
10340
10341     if (NestTy) {
10342       Instruction *Caller = CS.getInstruction();
10343       std::vector<Value*> NewArgs;
10344       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10345
10346       SmallVector<AttributeWithIndex, 8> NewAttrs;
10347       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10348
10349       // Insert the nest argument into the call argument list, which may
10350       // mean appending it.  Likewise for attributes.
10351
10352       // Add any result attributes.
10353       if (Attributes Attr = Attrs.getRetAttributes())
10354         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10355
10356       {
10357         unsigned Idx = 1;
10358         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10359         do {
10360           if (Idx == NestIdx) {
10361             // Add the chain argument and attributes.
10362             Value *NestVal = Tramp->getOperand(3);
10363             if (NestVal->getType() != NestTy)
10364               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10365             NewArgs.push_back(NestVal);
10366             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10367           }
10368
10369           if (I == E)
10370             break;
10371
10372           // Add the original argument and attributes.
10373           NewArgs.push_back(*I);
10374           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10375             NewAttrs.push_back
10376               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10377
10378           ++Idx, ++I;
10379         } while (1);
10380       }
10381
10382       // Add any function attributes.
10383       if (Attributes Attr = Attrs.getFnAttributes())
10384         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10385
10386       // The trampoline may have been bitcast to a bogus type (FTy).
10387       // Handle this by synthesizing a new function type, equal to FTy
10388       // with the chain parameter inserted.
10389
10390       std::vector<const Type*> NewTypes;
10391       NewTypes.reserve(FTy->getNumParams()+1);
10392
10393       // Insert the chain's type into the list of parameter types, which may
10394       // mean appending it.
10395       {
10396         unsigned Idx = 1;
10397         FunctionType::param_iterator I = FTy->param_begin(),
10398           E = FTy->param_end();
10399
10400         do {
10401           if (Idx == NestIdx)
10402             // Add the chain's type.
10403             NewTypes.push_back(NestTy);
10404
10405           if (I == E)
10406             break;
10407
10408           // Add the original type.
10409           NewTypes.push_back(*I);
10410
10411           ++Idx, ++I;
10412         } while (1);
10413       }
10414
10415       // Replace the trampoline call with a direct call.  Let the generic
10416       // code sort out any function type mismatches.
10417       FunctionType *NewFTy =
10418                        Context->getFunctionType(FTy->getReturnType(), NewTypes, 
10419                                                 FTy->isVarArg());
10420       Constant *NewCallee =
10421         NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10422         NestF : Context->getConstantExprBitCast(NestF, 
10423                                          Context->getPointerTypeUnqual(NewFTy));
10424       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
10425
10426       Instruction *NewCaller;
10427       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10428         NewCaller = InvokeInst::Create(NewCallee,
10429                                        II->getNormalDest(), II->getUnwindDest(),
10430                                        NewArgs.begin(), NewArgs.end(),
10431                                        Caller->getName(), Caller);
10432         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10433         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10434       } else {
10435         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10436                                      Caller->getName(), Caller);
10437         if (cast<CallInst>(Caller)->isTailCall())
10438           cast<CallInst>(NewCaller)->setTailCall();
10439         cast<CallInst>(NewCaller)->
10440           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10441         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10442       }
10443       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10444         Caller->replaceAllUsesWith(NewCaller);
10445       Caller->eraseFromParent();
10446       RemoveFromWorkList(Caller);
10447       return 0;
10448     }
10449   }
10450
10451   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10452   // parameter, there is no need to adjust the argument list.  Let the generic
10453   // code sort out any function type mismatches.
10454   Constant *NewCallee =
10455     NestF->getType() == PTy ? NestF : 
10456                               Context->getConstantExprBitCast(NestF, PTy);
10457   CS.setCalledFunction(NewCallee);
10458   return CS.getInstruction();
10459 }
10460
10461 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10462 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10463 /// and a single binop.
10464 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10465   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10466   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10467   unsigned Opc = FirstInst->getOpcode();
10468   Value *LHSVal = FirstInst->getOperand(0);
10469   Value *RHSVal = FirstInst->getOperand(1);
10470     
10471   const Type *LHSType = LHSVal->getType();
10472   const Type *RHSType = RHSVal->getType();
10473   
10474   // Scan to see if all operands are the same opcode, all have one use, and all
10475   // kill their operands (i.e. the operands have one use).
10476   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10477     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10478     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10479         // Verify type of the LHS matches so we don't fold cmp's of different
10480         // types or GEP's with different index types.
10481         I->getOperand(0)->getType() != LHSType ||
10482         I->getOperand(1)->getType() != RHSType)
10483       return 0;
10484
10485     // If they are CmpInst instructions, check their predicates
10486     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10487       if (cast<CmpInst>(I)->getPredicate() !=
10488           cast<CmpInst>(FirstInst)->getPredicate())
10489         return 0;
10490     
10491     // Keep track of which operand needs a phi node.
10492     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10493     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10494   }
10495   
10496   // Otherwise, this is safe to transform!
10497   
10498   Value *InLHS = FirstInst->getOperand(0);
10499   Value *InRHS = FirstInst->getOperand(1);
10500   PHINode *NewLHS = 0, *NewRHS = 0;
10501   if (LHSVal == 0) {
10502     NewLHS = PHINode::Create(LHSType,
10503                              FirstInst->getOperand(0)->getName() + ".pn");
10504     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10505     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10506     InsertNewInstBefore(NewLHS, PN);
10507     LHSVal = NewLHS;
10508   }
10509   
10510   if (RHSVal == 0) {
10511     NewRHS = PHINode::Create(RHSType,
10512                              FirstInst->getOperand(1)->getName() + ".pn");
10513     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10514     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10515     InsertNewInstBefore(NewRHS, PN);
10516     RHSVal = NewRHS;
10517   }
10518   
10519   // Add all operands to the new PHIs.
10520   if (NewLHS || NewRHS) {
10521     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10522       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10523       if (NewLHS) {
10524         Value *NewInLHS = InInst->getOperand(0);
10525         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10526       }
10527       if (NewRHS) {
10528         Value *NewInRHS = InInst->getOperand(1);
10529         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10530       }
10531     }
10532   }
10533     
10534   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10535     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10536   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10537   return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10538                          LHSVal, RHSVal);
10539 }
10540
10541 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10542   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10543   
10544   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10545                                         FirstInst->op_end());
10546   // This is true if all GEP bases are allocas and if all indices into them are
10547   // constants.
10548   bool AllBasePointersAreAllocas = true;
10549   
10550   // Scan to see if all operands are the same opcode, all have one use, and all
10551   // kill their operands (i.e. the operands have one use).
10552   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10553     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10554     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10555       GEP->getNumOperands() != FirstInst->getNumOperands())
10556       return 0;
10557
10558     // Keep track of whether or not all GEPs are of alloca pointers.
10559     if (AllBasePointersAreAllocas &&
10560         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10561          !GEP->hasAllConstantIndices()))
10562       AllBasePointersAreAllocas = false;
10563     
10564     // Compare the operand lists.
10565     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10566       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10567         continue;
10568       
10569       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10570       // if one of the PHIs has a constant for the index.  The index may be
10571       // substantially cheaper to compute for the constants, so making it a
10572       // variable index could pessimize the path.  This also handles the case
10573       // for struct indices, which must always be constant.
10574       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10575           isa<ConstantInt>(GEP->getOperand(op)))
10576         return 0;
10577       
10578       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10579         return 0;
10580       FixedOperands[op] = 0;  // Needs a PHI.
10581     }
10582   }
10583   
10584   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10585   // bother doing this transformation.  At best, this will just save a bit of
10586   // offset calculation, but all the predecessors will have to materialize the
10587   // stack address into a register anyway.  We'd actually rather *clone* the
10588   // load up into the predecessors so that we have a load of a gep of an alloca,
10589   // which can usually all be folded into the load.
10590   if (AllBasePointersAreAllocas)
10591     return 0;
10592   
10593   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10594   // that is variable.
10595   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10596   
10597   bool HasAnyPHIs = false;
10598   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10599     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10600     Value *FirstOp = FirstInst->getOperand(i);
10601     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10602                                      FirstOp->getName()+".pn");
10603     InsertNewInstBefore(NewPN, PN);
10604     
10605     NewPN->reserveOperandSpace(e);
10606     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10607     OperandPhis[i] = NewPN;
10608     FixedOperands[i] = NewPN;
10609     HasAnyPHIs = true;
10610   }
10611
10612   
10613   // Add all operands to the new PHIs.
10614   if (HasAnyPHIs) {
10615     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10616       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10617       BasicBlock *InBB = PN.getIncomingBlock(i);
10618       
10619       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10620         if (PHINode *OpPhi = OperandPhis[op])
10621           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10622     }
10623   }
10624   
10625   Value *Base = FixedOperands[0];
10626   return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10627                                    FixedOperands.end());
10628 }
10629
10630
10631 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10632 /// sink the load out of the block that defines it.  This means that it must be
10633 /// obvious the value of the load is not changed from the point of the load to
10634 /// the end of the block it is in.
10635 ///
10636 /// Finally, it is safe, but not profitable, to sink a load targetting a
10637 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10638 /// to a register.
10639 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10640   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10641   
10642   for (++BBI; BBI != E; ++BBI)
10643     if (BBI->mayWriteToMemory())
10644       return false;
10645   
10646   // Check for non-address taken alloca.  If not address-taken already, it isn't
10647   // profitable to do this xform.
10648   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10649     bool isAddressTaken = false;
10650     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10651          UI != E; ++UI) {
10652       if (isa<LoadInst>(UI)) continue;
10653       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10654         // If storing TO the alloca, then the address isn't taken.
10655         if (SI->getOperand(1) == AI) continue;
10656       }
10657       isAddressTaken = true;
10658       break;
10659     }
10660     
10661     if (!isAddressTaken && AI->isStaticAlloca())
10662       return false;
10663   }
10664   
10665   // If this load is a load from a GEP with a constant offset from an alloca,
10666   // then we don't want to sink it.  In its present form, it will be
10667   // load [constant stack offset].  Sinking it will cause us to have to
10668   // materialize the stack addresses in each predecessor in a register only to
10669   // do a shared load from register in the successor.
10670   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10671     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10672       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10673         return false;
10674   
10675   return true;
10676 }
10677
10678
10679 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10680 // operator and they all are only used by the PHI, PHI together their
10681 // inputs, and do the operation once, to the result of the PHI.
10682 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10683   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10684
10685   // Scan the instruction, looking for input operations that can be folded away.
10686   // If all input operands to the phi are the same instruction (e.g. a cast from
10687   // the same type or "+42") we can pull the operation through the PHI, reducing
10688   // code size and simplifying code.
10689   Constant *ConstantOp = 0;
10690   const Type *CastSrcTy = 0;
10691   bool isVolatile = false;
10692   if (isa<CastInst>(FirstInst)) {
10693     CastSrcTy = FirstInst->getOperand(0)->getType();
10694   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10695     // Can fold binop, compare or shift here if the RHS is a constant, 
10696     // otherwise call FoldPHIArgBinOpIntoPHI.
10697     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10698     if (ConstantOp == 0)
10699       return FoldPHIArgBinOpIntoPHI(PN);
10700   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10701     isVolatile = LI->isVolatile();
10702     // We can't sink the load if the loaded value could be modified between the
10703     // load and the PHI.
10704     if (LI->getParent() != PN.getIncomingBlock(0) ||
10705         !isSafeAndProfitableToSinkLoad(LI))
10706       return 0;
10707     
10708     // If the PHI is of volatile loads and the load block has multiple
10709     // successors, sinking it would remove a load of the volatile value from
10710     // the path through the other successor.
10711     if (isVolatile &&
10712         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10713       return 0;
10714     
10715   } else if (isa<GetElementPtrInst>(FirstInst)) {
10716     return FoldPHIArgGEPIntoPHI(PN);
10717   } else {
10718     return 0;  // Cannot fold this operation.
10719   }
10720
10721   // Check to see if all arguments are the same operation.
10722   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10723     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10724     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10725     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10726       return 0;
10727     if (CastSrcTy) {
10728       if (I->getOperand(0)->getType() != CastSrcTy)
10729         return 0;  // Cast operation must match.
10730     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10731       // We can't sink the load if the loaded value could be modified between 
10732       // the load and the PHI.
10733       if (LI->isVolatile() != isVolatile ||
10734           LI->getParent() != PN.getIncomingBlock(i) ||
10735           !isSafeAndProfitableToSinkLoad(LI))
10736         return 0;
10737       
10738       // If the PHI is of volatile loads and the load block has multiple
10739       // successors, sinking it would remove a load of the volatile value from
10740       // the path through the other successor.
10741       if (isVolatile &&
10742           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10743         return 0;
10744       
10745     } else if (I->getOperand(1) != ConstantOp) {
10746       return 0;
10747     }
10748   }
10749
10750   // Okay, they are all the same operation.  Create a new PHI node of the
10751   // correct type, and PHI together all of the LHS's of the instructions.
10752   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10753                                    PN.getName()+".in");
10754   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10755
10756   Value *InVal = FirstInst->getOperand(0);
10757   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10758
10759   // Add all operands to the new PHI.
10760   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10761     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10762     if (NewInVal != InVal)
10763       InVal = 0;
10764     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10765   }
10766
10767   Value *PhiVal;
10768   if (InVal) {
10769     // The new PHI unions all of the same values together.  This is really
10770     // common, so we handle it intelligently here for compile-time speed.
10771     PhiVal = InVal;
10772     delete NewPN;
10773   } else {
10774     InsertNewInstBefore(NewPN, PN);
10775     PhiVal = NewPN;
10776   }
10777
10778   // Insert and return the new operation.
10779   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10780     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10781   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10782     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10783   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10784     return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10785                            PhiVal, ConstantOp);
10786   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10787   
10788   // If this was a volatile load that we are merging, make sure to loop through
10789   // and mark all the input loads as non-volatile.  If we don't do this, we will
10790   // insert a new volatile load and the old ones will not be deletable.
10791   if (isVolatile)
10792     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10793       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10794   
10795   return new LoadInst(PhiVal, "", isVolatile);
10796 }
10797
10798 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10799 /// that is dead.
10800 static bool DeadPHICycle(PHINode *PN,
10801                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10802   if (PN->use_empty()) return true;
10803   if (!PN->hasOneUse()) return false;
10804
10805   // Remember this node, and if we find the cycle, return.
10806   if (!PotentiallyDeadPHIs.insert(PN))
10807     return true;
10808   
10809   // Don't scan crazily complex things.
10810   if (PotentiallyDeadPHIs.size() == 16)
10811     return false;
10812
10813   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10814     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10815
10816   return false;
10817 }
10818
10819 /// PHIsEqualValue - Return true if this phi node is always equal to
10820 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10821 ///   z = some value; x = phi (y, z); y = phi (x, z)
10822 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10823                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10824   // See if we already saw this PHI node.
10825   if (!ValueEqualPHIs.insert(PN))
10826     return true;
10827   
10828   // Don't scan crazily complex things.
10829   if (ValueEqualPHIs.size() == 16)
10830     return false;
10831  
10832   // Scan the operands to see if they are either phi nodes or are equal to
10833   // the value.
10834   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10835     Value *Op = PN->getIncomingValue(i);
10836     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10837       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10838         return false;
10839     } else if (Op != NonPhiInVal)
10840       return false;
10841   }
10842   
10843   return true;
10844 }
10845
10846
10847 // PHINode simplification
10848 //
10849 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10850   // If LCSSA is around, don't mess with Phi nodes
10851   if (MustPreserveLCSSA) return 0;
10852   
10853   if (Value *V = PN.hasConstantValue())
10854     return ReplaceInstUsesWith(PN, V);
10855
10856   // If all PHI operands are the same operation, pull them through the PHI,
10857   // reducing code size.
10858   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10859       isa<Instruction>(PN.getIncomingValue(1)) &&
10860       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10861       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10862       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10863       // than themselves more than once.
10864       PN.getIncomingValue(0)->hasOneUse())
10865     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10866       return Result;
10867
10868   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10869   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10870   // PHI)... break the cycle.
10871   if (PN.hasOneUse()) {
10872     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10873     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10874       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10875       PotentiallyDeadPHIs.insert(&PN);
10876       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10877         return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10878     }
10879    
10880     // If this phi has a single use, and if that use just computes a value for
10881     // the next iteration of a loop, delete the phi.  This occurs with unused
10882     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10883     // common case here is good because the only other things that catch this
10884     // are induction variable analysis (sometimes) and ADCE, which is only run
10885     // late.
10886     if (PHIUser->hasOneUse() &&
10887         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10888         PHIUser->use_back() == &PN) {
10889       return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10890     }
10891   }
10892
10893   // We sometimes end up with phi cycles that non-obviously end up being the
10894   // same value, for example:
10895   //   z = some value; x = phi (y, z); y = phi (x, z)
10896   // where the phi nodes don't necessarily need to be in the same block.  Do a
10897   // quick check to see if the PHI node only contains a single non-phi value, if
10898   // so, scan to see if the phi cycle is actually equal to that value.
10899   {
10900     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10901     // Scan for the first non-phi operand.
10902     while (InValNo != NumOperandVals && 
10903            isa<PHINode>(PN.getIncomingValue(InValNo)))
10904       ++InValNo;
10905
10906     if (InValNo != NumOperandVals) {
10907       Value *NonPhiInVal = PN.getOperand(InValNo);
10908       
10909       // Scan the rest of the operands to see if there are any conflicts, if so
10910       // there is no need to recursively scan other phis.
10911       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10912         Value *OpVal = PN.getIncomingValue(InValNo);
10913         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10914           break;
10915       }
10916       
10917       // If we scanned over all operands, then we have one unique value plus
10918       // phi values.  Scan PHI nodes to see if they all merge in each other or
10919       // the value.
10920       if (InValNo == NumOperandVals) {
10921         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10922         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10923           return ReplaceInstUsesWith(PN, NonPhiInVal);
10924       }
10925     }
10926   }
10927   return 0;
10928 }
10929
10930 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10931                                    Instruction *InsertPoint,
10932                                    InstCombiner *IC) {
10933   unsigned PtrSize = DTy->getScalarSizeInBits();
10934   unsigned VTySize = V->getType()->getScalarSizeInBits();
10935   // We must cast correctly to the pointer type. Ensure that we
10936   // sign extend the integer value if it is smaller as this is
10937   // used for address computation.
10938   Instruction::CastOps opcode = 
10939      (VTySize < PtrSize ? Instruction::SExt :
10940       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10941   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10942 }
10943
10944
10945 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10946   Value *PtrOp = GEP.getOperand(0);
10947   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10948   // If so, eliminate the noop.
10949   if (GEP.getNumOperands() == 1)
10950     return ReplaceInstUsesWith(GEP, PtrOp);
10951
10952   if (isa<UndefValue>(GEP.getOperand(0)))
10953     return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
10954
10955   bool HasZeroPointerIndex = false;
10956   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10957     HasZeroPointerIndex = C->isNullValue();
10958
10959   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10960     return ReplaceInstUsesWith(GEP, PtrOp);
10961
10962   // Eliminate unneeded casts for indices.
10963   bool MadeChange = false;
10964   
10965   gep_type_iterator GTI = gep_type_begin(GEP);
10966   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10967        i != e; ++i, ++GTI) {
10968     if (isa<SequentialType>(*GTI)) {
10969       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
10970         if (CI->getOpcode() == Instruction::ZExt ||
10971             CI->getOpcode() == Instruction::SExt) {
10972           const Type *SrcTy = CI->getOperand(0)->getType();
10973           // We can eliminate a cast from i32 to i64 iff the target 
10974           // is a 32-bit pointer target.
10975           if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
10976             MadeChange = true;
10977             *i = CI->getOperand(0);
10978           }
10979         }
10980       }
10981       // If we are using a wider index than needed for this platform, shrink it
10982       // to what we need.  If narrower, sign-extend it to what we need.
10983       // If the incoming value needs a cast instruction,
10984       // insert it.  This explicit cast can make subsequent optimizations more
10985       // obvious.
10986       Value *Op = *i;
10987       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
10988         if (Constant *C = dyn_cast<Constant>(Op)) {
10989           *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
10990           MadeChange = true;
10991         } else {
10992           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10993                                 GEP);
10994           *i = Op;
10995           MadeChange = true;
10996         }
10997       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10998         if (Constant *C = dyn_cast<Constant>(Op)) {
10999           *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
11000           MadeChange = true;
11001         } else {
11002           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11003                                 GEP);
11004           *i = Op;
11005           MadeChange = true;
11006         }
11007       }
11008     }
11009   }
11010   if (MadeChange) return &GEP;
11011
11012   // Combine Indices - If the source pointer to this getelementptr instruction
11013   // is a getelementptr instruction, combine the indices of the two
11014   // getelementptr instructions into a single instruction.
11015   //
11016   SmallVector<Value*, 8> SrcGEPOperands;
11017   if (User *Src = dyn_castGetElementPtr(PtrOp))
11018     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
11019
11020   if (!SrcGEPOperands.empty()) {
11021     // Note that if our source is a gep chain itself that we wait for that
11022     // chain to be resolved before we perform this transformation.  This
11023     // avoids us creating a TON of code in some cases.
11024     //
11025     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11026         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11027       return 0;   // Wait until our source is folded to completion.
11028
11029     SmallVector<Value*, 8> Indices;
11030
11031     // Find out whether the last index in the source GEP is a sequential idx.
11032     bool EndsWithSequential = false;
11033     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11034            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11035       EndsWithSequential = !isa<StructType>(*I);
11036
11037     // Can we combine the two pointer arithmetics offsets?
11038     if (EndsWithSequential) {
11039       // Replace: gep (gep %P, long B), long A, ...
11040       // With:    T = long A+B; gep %P, T, ...
11041       //
11042       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
11043       if (SO1 == Context->getNullValue(SO1->getType())) {
11044         Sum = GO1;
11045       } else if (GO1 == Context->getNullValue(GO1->getType())) {
11046         Sum = SO1;
11047       } else {
11048         // If they aren't the same type, convert both to an integer of the
11049         // target's pointer size.
11050         if (SO1->getType() != GO1->getType()) {
11051           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
11052             SO1 =
11053                 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
11054           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
11055             GO1 =
11056                 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
11057           } else {
11058             unsigned PS = TD->getPointerSizeInBits();
11059             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
11060               // Convert GO1 to SO1's type.
11061               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11062
11063             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
11064               // Convert SO1 to GO1's type.
11065               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11066             } else {
11067               const Type *PT = TD->getIntPtrType();
11068               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11069               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11070             }
11071           }
11072         }
11073         if (isa<Constant>(SO1) && isa<Constant>(GO1))
11074           Sum = Context->getConstantExprAdd(cast<Constant>(SO1), 
11075                                             cast<Constant>(GO1));
11076         else {
11077           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11078           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11079         }
11080       }
11081
11082       // Recycle the GEP we already have if possible.
11083       if (SrcGEPOperands.size() == 2) {
11084         GEP.setOperand(0, SrcGEPOperands[0]);
11085         GEP.setOperand(1, Sum);
11086         return &GEP;
11087       } else {
11088         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11089                        SrcGEPOperands.end()-1);
11090         Indices.push_back(Sum);
11091         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11092       }
11093     } else if (isa<Constant>(*GEP.idx_begin()) &&
11094                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11095                SrcGEPOperands.size() != 1) {
11096       // Otherwise we can do the fold if the first index of the GEP is a zero
11097       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11098                      SrcGEPOperands.end());
11099       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11100     }
11101
11102     if (!Indices.empty())
11103       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11104                                        Indices.end(), GEP.getName());
11105
11106   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11107     // GEP of global variable.  If all of the indices for this GEP are
11108     // constants, we can promote this to a constexpr instead of an instruction.
11109
11110     // Scan for nonconstants...
11111     SmallVector<Constant*, 8> Indices;
11112     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11113     for (; I != E && isa<Constant>(*I); ++I)
11114       Indices.push_back(cast<Constant>(*I));
11115
11116     if (I == E) {  // If they are all constants...
11117       Constant *CE = Context->getConstantExprGetElementPtr(GV,
11118                                                     &Indices[0],Indices.size());
11119
11120       // Replace all uses of the GEP with the new constexpr...
11121       return ReplaceInstUsesWith(GEP, CE);
11122     }
11123   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
11124     if (!isa<PointerType>(X->getType())) {
11125       // Not interesting.  Source pointer must be a cast from pointer.
11126     } else if (HasZeroPointerIndex) {
11127       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11128       // into     : GEP [10 x i8]* X, i32 0, ...
11129       //
11130       // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11131       //           into     : GEP i8* X, ...
11132       // 
11133       // This occurs when the program declares an array extern like "int X[];"
11134       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11135       const PointerType *XTy = cast<PointerType>(X->getType());
11136       if (const ArrayType *CATy =
11137           dyn_cast<ArrayType>(CPTy->getElementType())) {
11138         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11139         if (CATy->getElementType() == XTy->getElementType()) {
11140           // -> GEP i8* X, ...
11141           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11142           return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11143                                            GEP.getName());
11144         } else if (const ArrayType *XATy =
11145                  dyn_cast<ArrayType>(XTy->getElementType())) {
11146           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11147           if (CATy->getElementType() == XATy->getElementType()) {
11148             // -> GEP [10 x i8]* X, i32 0, ...
11149             // At this point, we know that the cast source type is a pointer
11150             // to an array of the same type as the destination pointer
11151             // array.  Because the array type is never stepped over (there
11152             // is a leading zero) we can fold the cast into this GEP.
11153             GEP.setOperand(0, X);
11154             return &GEP;
11155           }
11156         }
11157       }
11158     } else if (GEP.getNumOperands() == 2) {
11159       // Transform things like:
11160       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11161       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11162       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11163       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11164       if (isa<ArrayType>(SrcElTy) &&
11165           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11166           TD->getTypeAllocSize(ResElTy)) {
11167         Value *Idx[2];
11168         Idx[0] = Context->getNullValue(Type::Int32Ty);
11169         Idx[1] = GEP.getOperand(1);
11170         Value *V = InsertNewInstBefore(
11171                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
11172         // V and GEP are both pointer types --> BitCast
11173         return new BitCastInst(V, GEP.getType());
11174       }
11175       
11176       // Transform things like:
11177       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11178       //   (where tmp = 8*tmp2) into:
11179       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11180       
11181       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
11182         uint64_t ArrayEltSize =
11183             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11184         
11185         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11186         // allow either a mul, shift, or constant here.
11187         Value *NewIdx = 0;
11188         ConstantInt *Scale = 0;
11189         if (ArrayEltSize == 1) {
11190           NewIdx = GEP.getOperand(1);
11191           Scale = 
11192                Context->getConstantInt(cast<IntegerType>(NewIdx->getType()), 1);
11193         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11194           NewIdx = Context->getConstantInt(CI->getType(), 1);
11195           Scale = CI;
11196         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11197           if (Inst->getOpcode() == Instruction::Shl &&
11198               isa<ConstantInt>(Inst->getOperand(1))) {
11199             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11200             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11201             Scale = Context->getConstantInt(cast<IntegerType>(Inst->getType()),
11202                                      1ULL << ShAmtVal);
11203             NewIdx = Inst->getOperand(0);
11204           } else if (Inst->getOpcode() == Instruction::Mul &&
11205                      isa<ConstantInt>(Inst->getOperand(1))) {
11206             Scale = cast<ConstantInt>(Inst->getOperand(1));
11207             NewIdx = Inst->getOperand(0);
11208           }
11209         }
11210         
11211         // If the index will be to exactly the right offset with the scale taken
11212         // out, perform the transformation. Note, we don't know whether Scale is
11213         // signed or not. We'll use unsigned version of division/modulo
11214         // operation after making sure Scale doesn't have the sign bit set.
11215         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11216             Scale->getZExtValue() % ArrayEltSize == 0) {
11217           Scale = Context->getConstantInt(Scale->getType(),
11218                                    Scale->getZExtValue() / ArrayEltSize);
11219           if (Scale->getZExtValue() != 1) {
11220             Constant *C =
11221                    Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
11222                                                        false /*ZExt*/);
11223             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11224             NewIdx = InsertNewInstBefore(Sc, GEP);
11225           }
11226
11227           // Insert the new GEP instruction.
11228           Value *Idx[2];
11229           Idx[0] = Context->getNullValue(Type::Int32Ty);
11230           Idx[1] = NewIdx;
11231           Instruction *NewGEP =
11232             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11233           NewGEP = InsertNewInstBefore(NewGEP, GEP);
11234           // The NewGEP must be pointer typed, so must the old one -> BitCast
11235           return new BitCastInst(NewGEP, GEP.getType());
11236         }
11237       }
11238     }
11239   }
11240   
11241   /// See if we can simplify:
11242   ///   X = bitcast A to B*
11243   ///   Y = gep X, <...constant indices...>
11244   /// into a gep of the original struct.  This is important for SROA and alias
11245   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11246   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11247     if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11248       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11249       // a constant back from EmitGEPOffset.
11250       ConstantInt *OffsetV =
11251                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11252       int64_t Offset = OffsetV->getSExtValue();
11253       
11254       // If this GEP instruction doesn't move the pointer, just replace the GEP
11255       // with a bitcast of the real input to the dest type.
11256       if (Offset == 0) {
11257         // If the bitcast is of an allocation, and the allocation will be
11258         // converted to match the type of the cast, don't touch this.
11259         if (isa<AllocationInst>(BCI->getOperand(0))) {
11260           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11261           if (Instruction *I = visitBitCast(*BCI)) {
11262             if (I != BCI) {
11263               I->takeName(BCI);
11264               BCI->getParent()->getInstList().insert(BCI, I);
11265               ReplaceInstUsesWith(*BCI, I);
11266             }
11267             return &GEP;
11268           }
11269         }
11270         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11271       }
11272       
11273       // Otherwise, if the offset is non-zero, we need to find out if there is a
11274       // field at Offset in 'A's type.  If so, we can pull the cast through the
11275       // GEP.
11276       SmallVector<Value*, 8> NewIndices;
11277       const Type *InTy =
11278         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11279       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11280         Instruction *NGEP =
11281            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11282                                      NewIndices.end());
11283         if (NGEP->getType() == GEP.getType()) return NGEP;
11284         InsertNewInstBefore(NGEP, GEP);
11285         NGEP->takeName(&GEP);
11286         return new BitCastInst(NGEP, GEP.getType());
11287       }
11288     }
11289   }    
11290     
11291   return 0;
11292 }
11293
11294 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11295   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11296   if (AI.isArrayAllocation()) {  // Check C != 1
11297     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11298       const Type *NewTy = 
11299         Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
11300       AllocationInst *New = 0;
11301
11302       // Create and insert the replacement instruction...
11303       if (isa<MallocInst>(AI))
11304         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11305       else {
11306         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11307         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11308       }
11309
11310       InsertNewInstBefore(New, AI);
11311
11312       // Scan to the end of the allocation instructions, to skip over a block of
11313       // allocas if possible...also skip interleaved debug info
11314       //
11315       BasicBlock::iterator It = New;
11316       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11317
11318       // Now that I is pointing to the first non-allocation-inst in the block,
11319       // insert our getelementptr instruction...
11320       //
11321       Value *NullIdx = Context->getNullValue(Type::Int32Ty);
11322       Value *Idx[2];
11323       Idx[0] = NullIdx;
11324       Idx[1] = NullIdx;
11325       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11326                                            New->getName()+".sub", It);
11327
11328       // Now make everything use the getelementptr instead of the original
11329       // allocation.
11330       return ReplaceInstUsesWith(AI, V);
11331     } else if (isa<UndefValue>(AI.getArraySize())) {
11332       return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11333     }
11334   }
11335
11336   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11337     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11338     // Note that we only do this for alloca's, because malloc should allocate
11339     // and return a unique pointer, even for a zero byte allocation.
11340     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11341       return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11342
11343     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11344     if (AI.getAlignment() == 0)
11345       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11346   }
11347
11348   return 0;
11349 }
11350
11351 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11352   Value *Op = FI.getOperand(0);
11353
11354   // free undef -> unreachable.
11355   if (isa<UndefValue>(Op)) {
11356     // Insert a new store to null because we cannot modify the CFG here.
11357     new StoreInst(Context->getTrue(),
11358            Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
11359     return EraseInstFromFunction(FI);
11360   }
11361   
11362   // If we have 'free null' delete the instruction.  This can happen in stl code
11363   // when lots of inlining happens.
11364   if (isa<ConstantPointerNull>(Op))
11365     return EraseInstFromFunction(FI);
11366   
11367   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11368   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11369     FI.setOperand(0, CI->getOperand(0));
11370     return &FI;
11371   }
11372   
11373   // Change free (gep X, 0,0,0,0) into free(X)
11374   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11375     if (GEPI->hasAllZeroIndices()) {
11376       AddToWorkList(GEPI);
11377       FI.setOperand(0, GEPI->getOperand(0));
11378       return &FI;
11379     }
11380   }
11381   
11382   // Change free(malloc) into nothing, if the malloc has a single use.
11383   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11384     if (MI->hasOneUse()) {
11385       EraseInstFromFunction(FI);
11386       return EraseInstFromFunction(*MI);
11387     }
11388
11389   return 0;
11390 }
11391
11392
11393 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11394 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11395                                         const TargetData *TD) {
11396   User *CI = cast<User>(LI.getOperand(0));
11397   Value *CastOp = CI->getOperand(0);
11398   LLVMContext *Context = IC.getContext();
11399
11400   if (TD) {
11401     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11402       // Instead of loading constant c string, use corresponding integer value
11403       // directly if string length is small enough.
11404       std::string Str;
11405       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11406         unsigned len = Str.length();
11407         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11408         unsigned numBits = Ty->getPrimitiveSizeInBits();
11409         // Replace LI with immediate integer store.
11410         if ((numBits >> 3) == len + 1) {
11411           APInt StrVal(numBits, 0);
11412           APInt SingleChar(numBits, 0);
11413           if (TD->isLittleEndian()) {
11414             for (signed i = len-1; i >= 0; i--) {
11415               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11416               StrVal = (StrVal << 8) | SingleChar;
11417             }
11418           } else {
11419             for (unsigned i = 0; i < len; i++) {
11420               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11421               StrVal = (StrVal << 8) | SingleChar;
11422             }
11423             // Append NULL at the end.
11424             SingleChar = 0;
11425             StrVal = (StrVal << 8) | SingleChar;
11426           }
11427           Value *NL = Context->getConstantInt(StrVal);
11428           return IC.ReplaceInstUsesWith(LI, NL);
11429         }
11430       }
11431     }
11432   }
11433
11434   const PointerType *DestTy = cast<PointerType>(CI->getType());
11435   const Type *DestPTy = DestTy->getElementType();
11436   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11437
11438     // If the address spaces don't match, don't eliminate the cast.
11439     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11440       return 0;
11441
11442     const Type *SrcPTy = SrcTy->getElementType();
11443
11444     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11445          isa<VectorType>(DestPTy)) {
11446       // If the source is an array, the code below will not succeed.  Check to
11447       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11448       // constants.
11449       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11450         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11451           if (ASrcTy->getNumElements() != 0) {
11452             Value *Idxs[2];
11453             Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11454             CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
11455             SrcTy = cast<PointerType>(CastOp->getType());
11456             SrcPTy = SrcTy->getElementType();
11457           }
11458
11459       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11460             isa<VectorType>(SrcPTy)) &&
11461           // Do not allow turning this into a load of an integer, which is then
11462           // casted to a pointer, this pessimizes pointer analysis a lot.
11463           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11464           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11465                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11466
11467         // Okay, we are casting from one integer or pointer type to another of
11468         // the same size.  Instead of casting the pointer before the load, cast
11469         // the result of the loaded value.
11470         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11471                                                              CI->getName(),
11472                                                          LI.isVolatile()),LI);
11473         // Now cast the result of the load.
11474         return new BitCastInst(NewLoad, LI.getType());
11475       }
11476     }
11477   }
11478   return 0;
11479 }
11480
11481 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11482   Value *Op = LI.getOperand(0);
11483
11484   // Attempt to improve the alignment.
11485   unsigned KnownAlign =
11486     GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11487   if (KnownAlign >
11488       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11489                                 LI.getAlignment()))
11490     LI.setAlignment(KnownAlign);
11491
11492   // load (cast X) --> cast (load X) iff safe
11493   if (isa<CastInst>(Op))
11494     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11495       return Res;
11496
11497   // None of the following transforms are legal for volatile loads.
11498   if (LI.isVolatile()) return 0;
11499   
11500   // Do really simple store-to-load forwarding and load CSE, to catch cases
11501   // where there are several consequtive memory accesses to the same location,
11502   // separated by a few arithmetic operations.
11503   BasicBlock::iterator BBI = &LI;
11504   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11505     return ReplaceInstUsesWith(LI, AvailableVal);
11506
11507   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11508     const Value *GEPI0 = GEPI->getOperand(0);
11509     // TODO: Consider a target hook for valid address spaces for this xform.
11510     if (isa<ConstantPointerNull>(GEPI0) &&
11511         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11512       // Insert a new store to null instruction before the load to indicate
11513       // that this code is not reachable.  We do this instead of inserting
11514       // an unreachable instruction directly because we cannot modify the
11515       // CFG.
11516       new StoreInst(Context->getUndef(LI.getType()),
11517                     Context->getNullValue(Op->getType()), &LI);
11518       return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11519     }
11520   } 
11521
11522   if (Constant *C = dyn_cast<Constant>(Op)) {
11523     // load null/undef -> undef
11524     // TODO: Consider a target hook for valid address spaces for this xform.
11525     if (isa<UndefValue>(C) || (C->isNullValue() && 
11526         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11527       // Insert a new store to null instruction before the load to indicate that
11528       // this code is not reachable.  We do this instead of inserting an
11529       // unreachable instruction directly because we cannot modify the 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     // Instcombine load (constant global) into the value loaded.
11536     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11537       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11538         return ReplaceInstUsesWith(LI, GV->getInitializer());
11539
11540     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11541     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11542       if (CE->getOpcode() == Instruction::GetElementPtr) {
11543         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11544           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11545             if (Constant *V = 
11546                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE, 
11547                                                       Context))
11548               return ReplaceInstUsesWith(LI, V);
11549         if (CE->getOperand(0)->isNullValue()) {
11550           // Insert a new store to null instruction before the load to indicate
11551           // that this code is not reachable.  We do this instead of inserting
11552           // an unreachable instruction directly because we cannot modify the
11553           // CFG.
11554           new StoreInst(Context->getUndef(LI.getType()),
11555                         Context->getNullValue(Op->getType()), &LI);
11556           return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11557         }
11558
11559       } else if (CE->isCast()) {
11560         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11561           return Res;
11562       }
11563     }
11564   }
11565     
11566   // If this load comes from anywhere in a constant global, and if the global
11567   // is all undef or zero, we know what it loads.
11568   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11569     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11570       if (GV->getInitializer()->isNullValue())
11571         return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
11572       else if (isa<UndefValue>(GV->getInitializer()))
11573         return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11574     }
11575   }
11576
11577   if (Op->hasOneUse()) {
11578     // Change select and PHI nodes to select values instead of addresses: this
11579     // helps alias analysis out a lot, allows many others simplifications, and
11580     // exposes redundancy in the code.
11581     //
11582     // Note that we cannot do the transformation unless we know that the
11583     // introduced loads cannot trap!  Something like this is valid as long as
11584     // the condition is always false: load (select bool %C, int* null, int* %G),
11585     // but it would not be valid if we transformed it to load from null
11586     // unconditionally.
11587     //
11588     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11589       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11590       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11591           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11592         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11593                                      SI->getOperand(1)->getName()+".val"), LI);
11594         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11595                                      SI->getOperand(2)->getName()+".val"), LI);
11596         return SelectInst::Create(SI->getCondition(), V1, V2);
11597       }
11598
11599       // load (select (cond, null, P)) -> load P
11600       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11601         if (C->isNullValue()) {
11602           LI.setOperand(0, SI->getOperand(2));
11603           return &LI;
11604         }
11605
11606       // load (select (cond, P, null)) -> load P
11607       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11608         if (C->isNullValue()) {
11609           LI.setOperand(0, SI->getOperand(1));
11610           return &LI;
11611         }
11612     }
11613   }
11614   return 0;
11615 }
11616
11617 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11618 /// when possible.  This makes it generally easy to do alias analysis and/or
11619 /// SROA/mem2reg of the memory object.
11620 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11621   User *CI = cast<User>(SI.getOperand(1));
11622   Value *CastOp = CI->getOperand(0);
11623   LLVMContext *Context = IC.getContext();
11624
11625   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11626   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11627   if (SrcTy == 0) return 0;
11628   
11629   const Type *SrcPTy = SrcTy->getElementType();
11630
11631   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11632     return 0;
11633   
11634   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11635   /// to its first element.  This allows us to handle things like:
11636   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11637   /// on 32-bit hosts.
11638   SmallVector<Value*, 4> NewGEPIndices;
11639   
11640   // If the source is an array, the code below will not succeed.  Check to
11641   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11642   // constants.
11643   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11644     // Index through pointer.
11645     Constant *Zero = Context->getNullValue(Type::Int32Ty);
11646     NewGEPIndices.push_back(Zero);
11647     
11648     while (1) {
11649       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11650         if (!STy->getNumElements()) /* Struct can be empty {} */
11651           break;
11652         NewGEPIndices.push_back(Zero);
11653         SrcPTy = STy->getElementType(0);
11654       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11655         NewGEPIndices.push_back(Zero);
11656         SrcPTy = ATy->getElementType();
11657       } else {
11658         break;
11659       }
11660     }
11661     
11662     SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
11663   }
11664
11665   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11666     return 0;
11667   
11668   // If the pointers point into different address spaces or if they point to
11669   // values with different sizes, we can't do the transformation.
11670   if (SrcTy->getAddressSpace() != 
11671         cast<PointerType>(CI->getType())->getAddressSpace() ||
11672       IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
11673       IC.getTargetData().getTypeSizeInBits(DestPTy))
11674     return 0;
11675
11676   // Okay, we are casting from one integer or pointer type to another of
11677   // the same size.  Instead of casting the pointer before 
11678   // the store, cast the value to be stored.
11679   Value *NewCast;
11680   Value *SIOp0 = SI.getOperand(0);
11681   Instruction::CastOps opcode = Instruction::BitCast;
11682   const Type* CastSrcTy = SIOp0->getType();
11683   const Type* CastDstTy = SrcPTy;
11684   if (isa<PointerType>(CastDstTy)) {
11685     if (CastSrcTy->isInteger())
11686       opcode = Instruction::IntToPtr;
11687   } else if (isa<IntegerType>(CastDstTy)) {
11688     if (isa<PointerType>(SIOp0->getType()))
11689       opcode = Instruction::PtrToInt;
11690   }
11691   
11692   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11693   // emit a GEP to index into its first field.
11694   if (!NewGEPIndices.empty()) {
11695     if (Constant *C = dyn_cast<Constant>(CastOp))
11696       CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0], 
11697                                               NewGEPIndices.size());
11698     else
11699       CastOp = IC.InsertNewInstBefore(
11700               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11701                                         NewGEPIndices.end()), SI);
11702   }
11703   
11704   if (Constant *C = dyn_cast<Constant>(SIOp0))
11705     NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
11706   else
11707     NewCast = IC.InsertNewInstBefore(
11708       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11709       SI);
11710   return new StoreInst(NewCast, CastOp);
11711 }
11712
11713 /// equivalentAddressValues - Test if A and B will obviously have the same
11714 /// value. This includes recognizing that %t0 and %t1 will have the same
11715 /// value in code like this:
11716 ///   %t0 = getelementptr \@a, 0, 3
11717 ///   store i32 0, i32* %t0
11718 ///   %t1 = getelementptr \@a, 0, 3
11719 ///   %t2 = load i32* %t1
11720 ///
11721 static bool equivalentAddressValues(Value *A, Value *B) {
11722   // Test if the values are trivially equivalent.
11723   if (A == B) return true;
11724   
11725   // Test if the values come form identical arithmetic instructions.
11726   if (isa<BinaryOperator>(A) ||
11727       isa<CastInst>(A) ||
11728       isa<PHINode>(A) ||
11729       isa<GetElementPtrInst>(A))
11730     if (Instruction *BI = dyn_cast<Instruction>(B))
11731       if (cast<Instruction>(A)->isIdenticalTo(BI))
11732         return true;
11733   
11734   // Otherwise they may not be equivalent.
11735   return false;
11736 }
11737
11738 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11739 // return the llvm.dbg.declare.
11740 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11741   if (!V->hasNUses(2))
11742     return 0;
11743   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11744        UI != E; ++UI) {
11745     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11746       return DI;
11747     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11748       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11749         return DI;
11750       }
11751   }
11752   return 0;
11753 }
11754
11755 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11756   Value *Val = SI.getOperand(0);
11757   Value *Ptr = SI.getOperand(1);
11758
11759   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11760     EraseInstFromFunction(SI);
11761     ++NumCombined;
11762     return 0;
11763   }
11764   
11765   // If the RHS is an alloca with a single use, zapify the store, making the
11766   // alloca dead.
11767   // If the RHS is an alloca with a two uses, the other one being a 
11768   // llvm.dbg.declare, zapify the store and the declare, making the
11769   // alloca dead.  We must do this to prevent declare's from affecting
11770   // codegen.
11771   if (!SI.isVolatile()) {
11772     if (Ptr->hasOneUse()) {
11773       if (isa<AllocaInst>(Ptr)) {
11774         EraseInstFromFunction(SI);
11775         ++NumCombined;
11776         return 0;
11777       }
11778       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11779         if (isa<AllocaInst>(GEP->getOperand(0))) {
11780           if (GEP->getOperand(0)->hasOneUse()) {
11781             EraseInstFromFunction(SI);
11782             ++NumCombined;
11783             return 0;
11784           }
11785           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11786             EraseInstFromFunction(*DI);
11787             EraseInstFromFunction(SI);
11788             ++NumCombined;
11789             return 0;
11790           }
11791         }
11792       }
11793     }
11794     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11795       EraseInstFromFunction(*DI);
11796       EraseInstFromFunction(SI);
11797       ++NumCombined;
11798       return 0;
11799     }
11800   }
11801
11802   // Attempt to improve the alignment.
11803   unsigned KnownAlign =
11804     GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11805   if (KnownAlign >
11806       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11807                                 SI.getAlignment()))
11808     SI.setAlignment(KnownAlign);
11809
11810   // Do really simple DSE, to catch cases where there are several consecutive
11811   // stores to the same location, separated by a few arithmetic operations. This
11812   // situation often occurs with bitfield accesses.
11813   BasicBlock::iterator BBI = &SI;
11814   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11815        --ScanInsts) {
11816     --BBI;
11817     // Don't count debug info directives, lest they affect codegen,
11818     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11819     // It is necessary for correctness to skip those that feed into a
11820     // llvm.dbg.declare, as these are not present when debugging is off.
11821     if (isa<DbgInfoIntrinsic>(BBI) ||
11822         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11823       ScanInsts++;
11824       continue;
11825     }    
11826     
11827     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11828       // Prev store isn't volatile, and stores to the same location?
11829       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11830                                                           SI.getOperand(1))) {
11831         ++NumDeadStore;
11832         ++BBI;
11833         EraseInstFromFunction(*PrevSI);
11834         continue;
11835       }
11836       break;
11837     }
11838     
11839     // If this is a load, we have to stop.  However, if the loaded value is from
11840     // the pointer we're loading and is producing the pointer we're storing,
11841     // then *this* store is dead (X = load P; store X -> P).
11842     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11843       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11844           !SI.isVolatile()) {
11845         EraseInstFromFunction(SI);
11846         ++NumCombined;
11847         return 0;
11848       }
11849       // Otherwise, this is a load from some other location.  Stores before it
11850       // may not be dead.
11851       break;
11852     }
11853     
11854     // Don't skip over loads or things that can modify memory.
11855     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11856       break;
11857   }
11858   
11859   
11860   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11861
11862   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11863   if (isa<ConstantPointerNull>(Ptr) &&
11864       cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11865     if (!isa<UndefValue>(Val)) {
11866       SI.setOperand(0, Context->getUndef(Val->getType()));
11867       if (Instruction *U = dyn_cast<Instruction>(Val))
11868         AddToWorkList(U);  // Dropped a use.
11869       ++NumCombined;
11870     }
11871     return 0;  // Do not modify these!
11872   }
11873
11874   // store undef, Ptr -> noop
11875   if (isa<UndefValue>(Val)) {
11876     EraseInstFromFunction(SI);
11877     ++NumCombined;
11878     return 0;
11879   }
11880
11881   // If the pointer destination is a cast, see if we can fold the cast into the
11882   // source instead.
11883   if (isa<CastInst>(Ptr))
11884     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11885       return Res;
11886   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11887     if (CE->isCast())
11888       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11889         return Res;
11890
11891   
11892   // If this store is the last instruction in the basic block (possibly
11893   // excepting debug info instructions and the pointer bitcasts that feed
11894   // into them), and if the block ends with an unconditional branch, try
11895   // to move it to the successor block.
11896   BBI = &SI; 
11897   do {
11898     ++BBI;
11899   } while (isa<DbgInfoIntrinsic>(BBI) ||
11900            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11901   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11902     if (BI->isUnconditional())
11903       if (SimplifyStoreAtEndOfBlock(SI))
11904         return 0;  // xform done!
11905   
11906   return 0;
11907 }
11908
11909 /// SimplifyStoreAtEndOfBlock - Turn things like:
11910 ///   if () { *P = v1; } else { *P = v2 }
11911 /// into a phi node with a store in the successor.
11912 ///
11913 /// Simplify things like:
11914 ///   *P = v1; if () { *P = v2; }
11915 /// into a phi node with a store in the successor.
11916 ///
11917 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11918   BasicBlock *StoreBB = SI.getParent();
11919   
11920   // Check to see if the successor block has exactly two incoming edges.  If
11921   // so, see if the other predecessor contains a store to the same location.
11922   // if so, insert a PHI node (if needed) and move the stores down.
11923   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11924   
11925   // Determine whether Dest has exactly two predecessors and, if so, compute
11926   // the other predecessor.
11927   pred_iterator PI = pred_begin(DestBB);
11928   BasicBlock *OtherBB = 0;
11929   if (*PI != StoreBB)
11930     OtherBB = *PI;
11931   ++PI;
11932   if (PI == pred_end(DestBB))
11933     return false;
11934   
11935   if (*PI != StoreBB) {
11936     if (OtherBB)
11937       return false;
11938     OtherBB = *PI;
11939   }
11940   if (++PI != pred_end(DestBB))
11941     return false;
11942
11943   // Bail out if all the relevant blocks aren't distinct (this can happen,
11944   // for example, if SI is in an infinite loop)
11945   if (StoreBB == DestBB || OtherBB == DestBB)
11946     return false;
11947
11948   // Verify that the other block ends in a branch and is not otherwise empty.
11949   BasicBlock::iterator BBI = OtherBB->getTerminator();
11950   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11951   if (!OtherBr || BBI == OtherBB->begin())
11952     return false;
11953   
11954   // If the other block ends in an unconditional branch, check for the 'if then
11955   // else' case.  there is an instruction before the branch.
11956   StoreInst *OtherStore = 0;
11957   if (OtherBr->isUnconditional()) {
11958     --BBI;
11959     // Skip over debugging info.
11960     while (isa<DbgInfoIntrinsic>(BBI) ||
11961            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11962       if (BBI==OtherBB->begin())
11963         return false;
11964       --BBI;
11965     }
11966     // If this isn't a store, or isn't a store to the same location, bail out.
11967     OtherStore = dyn_cast<StoreInst>(BBI);
11968     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11969       return false;
11970   } else {
11971     // Otherwise, the other block ended with a conditional branch. If one of the
11972     // destinations is StoreBB, then we have the if/then case.
11973     if (OtherBr->getSuccessor(0) != StoreBB && 
11974         OtherBr->getSuccessor(1) != StoreBB)
11975       return false;
11976     
11977     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11978     // if/then triangle.  See if there is a store to the same ptr as SI that
11979     // lives in OtherBB.
11980     for (;; --BBI) {
11981       // Check to see if we find the matching store.
11982       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11983         if (OtherStore->getOperand(1) != SI.getOperand(1))
11984           return false;
11985         break;
11986       }
11987       // If we find something that may be using or overwriting the stored
11988       // value, or if we run out of instructions, we can't do the xform.
11989       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11990           BBI == OtherBB->begin())
11991         return false;
11992     }
11993     
11994     // In order to eliminate the store in OtherBr, we have to
11995     // make sure nothing reads or overwrites the stored value in
11996     // StoreBB.
11997     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11998       // FIXME: This should really be AA driven.
11999       if (I->mayReadFromMemory() || I->mayWriteToMemory())
12000         return false;
12001     }
12002   }
12003   
12004   // Insert a PHI node now if we need it.
12005   Value *MergedVal = OtherStore->getOperand(0);
12006   if (MergedVal != SI.getOperand(0)) {
12007     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12008     PN->reserveOperandSpace(2);
12009     PN->addIncoming(SI.getOperand(0), SI.getParent());
12010     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12011     MergedVal = InsertNewInstBefore(PN, DestBB->front());
12012   }
12013   
12014   // Advance to a place where it is safe to insert the new store and
12015   // insert it.
12016   BBI = DestBB->getFirstNonPHI();
12017   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12018                                     OtherStore->isVolatile()), *BBI);
12019   
12020   // Nuke the old stores.
12021   EraseInstFromFunction(SI);
12022   EraseInstFromFunction(*OtherStore);
12023   ++NumCombined;
12024   return true;
12025 }
12026
12027
12028 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12029   // Change br (not X), label True, label False to: br X, label False, True
12030   Value *X = 0;
12031   BasicBlock *TrueDest;
12032   BasicBlock *FalseDest;
12033   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
12034       !isa<Constant>(X)) {
12035     // Swap Destinations and condition...
12036     BI.setCondition(X);
12037     BI.setSuccessor(0, FalseDest);
12038     BI.setSuccessor(1, TrueDest);
12039     return &BI;
12040   }
12041
12042   // Cannonicalize fcmp_one -> fcmp_oeq
12043   FCmpInst::Predicate FPred; Value *Y;
12044   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
12045                              TrueDest, FalseDest), *Context))
12046     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12047          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12048       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12049       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
12050       Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
12051       NewSCC->takeName(I);
12052       // Swap Destinations and condition...
12053       BI.setCondition(NewSCC);
12054       BI.setSuccessor(0, FalseDest);
12055       BI.setSuccessor(1, TrueDest);
12056       RemoveFromWorkList(I);
12057       I->eraseFromParent();
12058       AddToWorkList(NewSCC);
12059       return &BI;
12060     }
12061
12062   // Cannonicalize icmp_ne -> icmp_eq
12063   ICmpInst::Predicate IPred;
12064   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12065                       TrueDest, FalseDest), *Context))
12066     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12067          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12068          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12069       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12070       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
12071       Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
12072       NewSCC->takeName(I);
12073       // Swap Destinations and condition...
12074       BI.setCondition(NewSCC);
12075       BI.setSuccessor(0, FalseDest);
12076       BI.setSuccessor(1, TrueDest);
12077       RemoveFromWorkList(I);
12078       I->eraseFromParent();;
12079       AddToWorkList(NewSCC);
12080       return &BI;
12081     }
12082
12083   return 0;
12084 }
12085
12086 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12087   Value *Cond = SI.getCondition();
12088   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12089     if (I->getOpcode() == Instruction::Add)
12090       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12091         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12092         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12093           SI.setOperand(i,
12094                    Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
12095                                                 AddRHS));
12096         SI.setOperand(0, I->getOperand(0));
12097         AddToWorkList(I);
12098         return &SI;
12099       }
12100   }
12101   return 0;
12102 }
12103
12104 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12105   Value *Agg = EV.getAggregateOperand();
12106
12107   if (!EV.hasIndices())
12108     return ReplaceInstUsesWith(EV, Agg);
12109
12110   if (Constant *C = dyn_cast<Constant>(Agg)) {
12111     if (isa<UndefValue>(C))
12112       return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
12113       
12114     if (isa<ConstantAggregateZero>(C))
12115       return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
12116
12117     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12118       // Extract the element indexed by the first index out of the constant
12119       Value *V = C->getOperand(*EV.idx_begin());
12120       if (EV.getNumIndices() > 1)
12121         // Extract the remaining indices out of the constant indexed by the
12122         // first index
12123         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12124       else
12125         return ReplaceInstUsesWith(EV, V);
12126     }
12127     return 0; // Can't handle other constants
12128   } 
12129   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12130     // We're extracting from an insertvalue instruction, compare the indices
12131     const unsigned *exti, *exte, *insi, *inse;
12132     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12133          exte = EV.idx_end(), inse = IV->idx_end();
12134          exti != exte && insi != inse;
12135          ++exti, ++insi) {
12136       if (*insi != *exti)
12137         // The insert and extract both reference distinctly different elements.
12138         // This means the extract is not influenced by the insert, and we can
12139         // replace the aggregate operand of the extract with the aggregate
12140         // operand of the insert. i.e., replace
12141         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12142         // %E = extractvalue { i32, { i32 } } %I, 0
12143         // with
12144         // %E = extractvalue { i32, { i32 } } %A, 0
12145         return ExtractValueInst::Create(IV->getAggregateOperand(),
12146                                         EV.idx_begin(), EV.idx_end());
12147     }
12148     if (exti == exte && insi == inse)
12149       // Both iterators are at the end: Index lists are identical. Replace
12150       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12151       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12152       // with "i32 42"
12153       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12154     if (exti == exte) {
12155       // The extract list is a prefix of the insert list. i.e. replace
12156       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12157       // %E = extractvalue { i32, { i32 } } %I, 1
12158       // with
12159       // %X = extractvalue { i32, { i32 } } %A, 1
12160       // %E = insertvalue { i32 } %X, i32 42, 0
12161       // by switching the order of the insert and extract (though the
12162       // insertvalue should be left in, since it may have other uses).
12163       Value *NewEV = InsertNewInstBefore(
12164         ExtractValueInst::Create(IV->getAggregateOperand(),
12165                                  EV.idx_begin(), EV.idx_end()),
12166         EV);
12167       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12168                                      insi, inse);
12169     }
12170     if (insi == inse)
12171       // The insert list is a prefix of the extract list
12172       // We can simply remove the common indices from the extract and make it
12173       // operate on the inserted value instead of the insertvalue result.
12174       // i.e., replace
12175       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12176       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12177       // with
12178       // %E extractvalue { i32 } { i32 42 }, 0
12179       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12180                                       exti, exte);
12181   }
12182   // Can't simplify extracts from other values. Note that nested extracts are
12183   // already simplified implicitely by the above (extract ( extract (insert) )
12184   // will be translated into extract ( insert ( extract ) ) first and then just
12185   // the value inserted, if appropriate).
12186   return 0;
12187 }
12188
12189 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12190 /// is to leave as a vector operation.
12191 static bool CheapToScalarize(Value *V, bool isConstant) {
12192   if (isa<ConstantAggregateZero>(V)) 
12193     return true;
12194   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12195     if (isConstant) return true;
12196     // If all elts are the same, we can extract.
12197     Constant *Op0 = C->getOperand(0);
12198     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12199       if (C->getOperand(i) != Op0)
12200         return false;
12201     return true;
12202   }
12203   Instruction *I = dyn_cast<Instruction>(V);
12204   if (!I) return false;
12205   
12206   // Insert element gets simplified to the inserted element or is deleted if
12207   // this is constant idx extract element and its a constant idx insertelt.
12208   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12209       isa<ConstantInt>(I->getOperand(2)))
12210     return true;
12211   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12212     return true;
12213   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12214     if (BO->hasOneUse() &&
12215         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12216          CheapToScalarize(BO->getOperand(1), isConstant)))
12217       return true;
12218   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12219     if (CI->hasOneUse() &&
12220         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12221          CheapToScalarize(CI->getOperand(1), isConstant)))
12222       return true;
12223   
12224   return false;
12225 }
12226
12227 /// Read and decode a shufflevector mask.
12228 ///
12229 /// It turns undef elements into values that are larger than the number of
12230 /// elements in the input.
12231 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12232   unsigned NElts = SVI->getType()->getNumElements();
12233   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12234     return std::vector<unsigned>(NElts, 0);
12235   if (isa<UndefValue>(SVI->getOperand(2)))
12236     return std::vector<unsigned>(NElts, 2*NElts);
12237
12238   std::vector<unsigned> Result;
12239   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12240   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12241     if (isa<UndefValue>(*i))
12242       Result.push_back(NElts*2);  // undef -> 8
12243     else
12244       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12245   return Result;
12246 }
12247
12248 /// FindScalarElement - Given a vector and an element number, see if the scalar
12249 /// value is already around as a register, for example if it were inserted then
12250 /// extracted from the vector.
12251 static Value *FindScalarElement(Value *V, unsigned EltNo,
12252                                 LLVMContext *Context) {
12253   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12254   const VectorType *PTy = cast<VectorType>(V->getType());
12255   unsigned Width = PTy->getNumElements();
12256   if (EltNo >= Width)  // Out of range access.
12257     return Context->getUndef(PTy->getElementType());
12258   
12259   if (isa<UndefValue>(V))
12260     return Context->getUndef(PTy->getElementType());
12261   else if (isa<ConstantAggregateZero>(V))
12262     return Context->getNullValue(PTy->getElementType());
12263   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12264     return CP->getOperand(EltNo);
12265   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12266     // If this is an insert to a variable element, we don't know what it is.
12267     if (!isa<ConstantInt>(III->getOperand(2))) 
12268       return 0;
12269     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12270     
12271     // If this is an insert to the element we are looking for, return the
12272     // inserted value.
12273     if (EltNo == IIElt) 
12274       return III->getOperand(1);
12275     
12276     // Otherwise, the insertelement doesn't modify the value, recurse on its
12277     // vector input.
12278     return FindScalarElement(III->getOperand(0), EltNo, Context);
12279   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12280     unsigned LHSWidth =
12281       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12282     unsigned InEl = getShuffleMask(SVI)[EltNo];
12283     if (InEl < LHSWidth)
12284       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12285     else if (InEl < LHSWidth*2)
12286       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12287     else
12288       return Context->getUndef(PTy->getElementType());
12289   }
12290   
12291   // Otherwise, we don't know.
12292   return 0;
12293 }
12294
12295 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12296   // If vector val is undef, replace extract with scalar undef.
12297   if (isa<UndefValue>(EI.getOperand(0)))
12298     return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12299
12300   // If vector val is constant 0, replace extract with scalar 0.
12301   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12302     return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
12303   
12304   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12305     // If vector val is constant with all elements the same, replace EI with
12306     // that element. When the elements are not identical, we cannot replace yet
12307     // (we do that below, but only when the index is constant).
12308     Constant *op0 = C->getOperand(0);
12309     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12310       if (C->getOperand(i) != op0) {
12311         op0 = 0; 
12312         break;
12313       }
12314     if (op0)
12315       return ReplaceInstUsesWith(EI, op0);
12316   }
12317   
12318   // If extracting a specified index from the vector, see if we can recursively
12319   // find a previously computed scalar that was inserted into the vector.
12320   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12321     unsigned IndexVal = IdxC->getZExtValue();
12322     unsigned VectorWidth = 
12323       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12324       
12325     // If this is extracting an invalid index, turn this into undef, to avoid
12326     // crashing the code below.
12327     if (IndexVal >= VectorWidth)
12328       return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12329     
12330     // This instruction only demands the single element from the input vector.
12331     // If the input vector has a single use, simplify it based on this use
12332     // property.
12333     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12334       APInt UndefElts(VectorWidth, 0);
12335       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12336       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12337                                                 DemandedMask, UndefElts)) {
12338         EI.setOperand(0, V);
12339         return &EI;
12340       }
12341     }
12342     
12343     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12344       return ReplaceInstUsesWith(EI, Elt);
12345     
12346     // If the this extractelement is directly using a bitcast from a vector of
12347     // the same number of elements, see if we can find the source element from
12348     // it.  In this case, we will end up needing to bitcast the scalars.
12349     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12350       if (const VectorType *VT = 
12351               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12352         if (VT->getNumElements() == VectorWidth)
12353           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12354                                              IndexVal, Context))
12355             return new BitCastInst(Elt, EI.getType());
12356     }
12357   }
12358   
12359   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12360     if (I->hasOneUse()) {
12361       // Push extractelement into predecessor operation if legal and
12362       // profitable to do so
12363       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12364         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12365         if (CheapToScalarize(BO, isConstantElt)) {
12366           ExtractElementInst *newEI0 = 
12367             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12368                                    EI.getName()+".lhs");
12369           ExtractElementInst *newEI1 =
12370             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12371                                    EI.getName()+".rhs");
12372           InsertNewInstBefore(newEI0, EI);
12373           InsertNewInstBefore(newEI1, EI);
12374           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12375         }
12376       } else if (isa<LoadInst>(I)) {
12377         unsigned AS = 
12378           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12379         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12380                                   Context->getPointerType(EI.getType(), AS),EI);
12381         GetElementPtrInst *GEP =
12382           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12383         InsertNewInstBefore(GEP, EI);
12384         return new LoadInst(GEP);
12385       }
12386     }
12387     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12388       // Extracting the inserted element?
12389       if (IE->getOperand(2) == EI.getOperand(1))
12390         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12391       // If the inserted and extracted elements are constants, they must not
12392       // be the same value, extract from the pre-inserted value instead.
12393       if (isa<Constant>(IE->getOperand(2)) &&
12394           isa<Constant>(EI.getOperand(1))) {
12395         AddUsesToWorkList(EI);
12396         EI.setOperand(0, IE->getOperand(0));
12397         return &EI;
12398       }
12399     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12400       // If this is extracting an element from a shufflevector, figure out where
12401       // it came from and extract from the appropriate input element instead.
12402       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12403         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12404         Value *Src;
12405         unsigned LHSWidth =
12406           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12407
12408         if (SrcIdx < LHSWidth)
12409           Src = SVI->getOperand(0);
12410         else if (SrcIdx < LHSWidth*2) {
12411           SrcIdx -= LHSWidth;
12412           Src = SVI->getOperand(1);
12413         } else {
12414           return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12415         }
12416         return new ExtractElementInst(Src,
12417                          Context->getConstantInt(Type::Int32Ty, SrcIdx, false));
12418       }
12419     }
12420     // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12421   }
12422   return 0;
12423 }
12424
12425 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12426 /// elements from either LHS or RHS, return the shuffle mask and true. 
12427 /// Otherwise, return false.
12428 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12429                                          std::vector<Constant*> &Mask,
12430                                          LLVMContext *Context) {
12431   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12432          "Invalid CollectSingleShuffleElements");
12433   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12434
12435   if (isa<UndefValue>(V)) {
12436     Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12437     return true;
12438   } else if (V == LHS) {
12439     for (unsigned i = 0; i != NumElts; ++i)
12440       Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12441     return true;
12442   } else if (V == RHS) {
12443     for (unsigned i = 0; i != NumElts; ++i)
12444       Mask.push_back(Context->getConstantInt(Type::Int32Ty, i+NumElts));
12445     return true;
12446   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12447     // If this is an insert of an extract from some other vector, include it.
12448     Value *VecOp    = IEI->getOperand(0);
12449     Value *ScalarOp = IEI->getOperand(1);
12450     Value *IdxOp    = IEI->getOperand(2);
12451     
12452     if (!isa<ConstantInt>(IdxOp))
12453       return false;
12454     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12455     
12456     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12457       // Okay, we can handle this if the vector we are insertinting into is
12458       // transitively ok.
12459       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12460         // If so, update the mask to reflect the inserted undef.
12461         Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
12462         return true;
12463       }      
12464     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12465       if (isa<ConstantInt>(EI->getOperand(1)) &&
12466           EI->getOperand(0)->getType() == V->getType()) {
12467         unsigned ExtractedIdx =
12468           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12469         
12470         // This must be extracting from either LHS or RHS.
12471         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12472           // Okay, we can handle this if the vector we are insertinting into is
12473           // transitively ok.
12474           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12475             // If so, update the mask to reflect the inserted value.
12476             if (EI->getOperand(0) == LHS) {
12477               Mask[InsertedIdx % NumElts] = 
12478                  Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12479             } else {
12480               assert(EI->getOperand(0) == RHS);
12481               Mask[InsertedIdx % NumElts] = 
12482                 Context->getConstantInt(Type::Int32Ty, ExtractedIdx+NumElts);
12483               
12484             }
12485             return true;
12486           }
12487         }
12488       }
12489     }
12490   }
12491   // TODO: Handle shufflevector here!
12492   
12493   return false;
12494 }
12495
12496 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12497 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12498 /// that computes V and the LHS value of the shuffle.
12499 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12500                                      Value *&RHS, LLVMContext *Context) {
12501   assert(isa<VectorType>(V->getType()) && 
12502          (RHS == 0 || V->getType() == RHS->getType()) &&
12503          "Invalid shuffle!");
12504   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12505
12506   if (isa<UndefValue>(V)) {
12507     Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12508     return V;
12509   } else if (isa<ConstantAggregateZero>(V)) {
12510     Mask.assign(NumElts, Context->getConstantInt(Type::Int32Ty, 0));
12511     return V;
12512   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12513     // If this is an insert of an extract from some other vector, include it.
12514     Value *VecOp    = IEI->getOperand(0);
12515     Value *ScalarOp = IEI->getOperand(1);
12516     Value *IdxOp    = IEI->getOperand(2);
12517     
12518     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12519       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12520           EI->getOperand(0)->getType() == V->getType()) {
12521         unsigned ExtractedIdx =
12522           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12523         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12524         
12525         // Either the extracted from or inserted into vector must be RHSVec,
12526         // otherwise we'd end up with a shuffle of three inputs.
12527         if (EI->getOperand(0) == RHS || RHS == 0) {
12528           RHS = EI->getOperand(0);
12529           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12530           Mask[InsertedIdx % NumElts] = 
12531             Context->getConstantInt(Type::Int32Ty, NumElts+ExtractedIdx);
12532           return V;
12533         }
12534         
12535         if (VecOp == RHS) {
12536           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12537                                             RHS, Context);
12538           // Everything but the extracted element is replaced with the RHS.
12539           for (unsigned i = 0; i != NumElts; ++i) {
12540             if (i != InsertedIdx)
12541               Mask[i] = Context->getConstantInt(Type::Int32Ty, NumElts+i);
12542           }
12543           return V;
12544         }
12545         
12546         // If this insertelement is a chain that comes from exactly these two
12547         // vectors, return the vector and the effective shuffle.
12548         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12549                                          Context))
12550           return EI->getOperand(0);
12551         
12552       }
12553     }
12554   }
12555   // TODO: Handle shufflevector here!
12556   
12557   // Otherwise, can't do anything fancy.  Return an identity vector.
12558   for (unsigned i = 0; i != NumElts; ++i)
12559     Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12560   return V;
12561 }
12562
12563 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12564   Value *VecOp    = IE.getOperand(0);
12565   Value *ScalarOp = IE.getOperand(1);
12566   Value *IdxOp    = IE.getOperand(2);
12567   
12568   // Inserting an undef or into an undefined place, remove this.
12569   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12570     ReplaceInstUsesWith(IE, VecOp);
12571   
12572   // If the inserted element was extracted from some other vector, and if the 
12573   // indexes are constant, try to turn this into a shufflevector operation.
12574   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12575     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12576         EI->getOperand(0)->getType() == IE.getType()) {
12577       unsigned NumVectorElts = IE.getType()->getNumElements();
12578       unsigned ExtractedIdx =
12579         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12580       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12581       
12582       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12583         return ReplaceInstUsesWith(IE, VecOp);
12584       
12585       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12586         return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
12587       
12588       // If we are extracting a value from a vector, then inserting it right
12589       // back into the same place, just use the input vector.
12590       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12591         return ReplaceInstUsesWith(IE, VecOp);      
12592       
12593       // We could theoretically do this for ANY input.  However, doing so could
12594       // turn chains of insertelement instructions into a chain of shufflevector
12595       // instructions, and right now we do not merge shufflevectors.  As such,
12596       // only do this in a situation where it is clear that there is benefit.
12597       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12598         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12599         // the values of VecOp, except then one read from EIOp0.
12600         // Build a new shuffle mask.
12601         std::vector<Constant*> Mask;
12602         if (isa<UndefValue>(VecOp))
12603           Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
12604         else {
12605           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12606           Mask.assign(NumVectorElts, Context->getConstantInt(Type::Int32Ty,
12607                                                        NumVectorElts));
12608         } 
12609         Mask[InsertedIdx] = 
12610                            Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12611         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12612                                      Context->getConstantVector(Mask));
12613       }
12614       
12615       // If this insertelement isn't used by some other insertelement, turn it
12616       // (and any insertelements it points to), into one big shuffle.
12617       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12618         std::vector<Constant*> Mask;
12619         Value *RHS = 0;
12620         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12621         if (RHS == 0) RHS = Context->getUndef(LHS->getType());
12622         // We now have a shuffle of LHS, RHS, Mask.
12623         return new ShuffleVectorInst(LHS, RHS,
12624                                      Context->getConstantVector(Mask));
12625       }
12626     }
12627   }
12628
12629   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12630   APInt UndefElts(VWidth, 0);
12631   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12632   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12633     return &IE;
12634
12635   return 0;
12636 }
12637
12638
12639 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12640   Value *LHS = SVI.getOperand(0);
12641   Value *RHS = SVI.getOperand(1);
12642   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12643
12644   bool MadeChange = false;
12645
12646   // Undefined shuffle mask -> undefined value.
12647   if (isa<UndefValue>(SVI.getOperand(2)))
12648     return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
12649
12650   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12651
12652   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12653     return 0;
12654
12655   APInt UndefElts(VWidth, 0);
12656   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12657   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12658     LHS = SVI.getOperand(0);
12659     RHS = SVI.getOperand(1);
12660     MadeChange = true;
12661   }
12662   
12663   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12664   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12665   if (LHS == RHS || isa<UndefValue>(LHS)) {
12666     if (isa<UndefValue>(LHS) && LHS == RHS) {
12667       // shuffle(undef,undef,mask) -> undef.
12668       return ReplaceInstUsesWith(SVI, LHS);
12669     }
12670     
12671     // Remap any references to RHS to use LHS.
12672     std::vector<Constant*> Elts;
12673     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12674       if (Mask[i] >= 2*e)
12675         Elts.push_back(Context->getUndef(Type::Int32Ty));
12676       else {
12677         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12678             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12679           Mask[i] = 2*e;     // Turn into undef.
12680           Elts.push_back(Context->getUndef(Type::Int32Ty));
12681         } else {
12682           Mask[i] = Mask[i] % e;  // Force to LHS.
12683           Elts.push_back(Context->getConstantInt(Type::Int32Ty, Mask[i]));
12684         }
12685       }
12686     }
12687     SVI.setOperand(0, SVI.getOperand(1));
12688     SVI.setOperand(1, Context->getUndef(RHS->getType()));
12689     SVI.setOperand(2, Context->getConstantVector(Elts));
12690     LHS = SVI.getOperand(0);
12691     RHS = SVI.getOperand(1);
12692     MadeChange = true;
12693   }
12694   
12695   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12696   bool isLHSID = true, isRHSID = true;
12697     
12698   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12699     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12700     // Is this an identity shuffle of the LHS value?
12701     isLHSID &= (Mask[i] == i);
12702       
12703     // Is this an identity shuffle of the RHS value?
12704     isRHSID &= (Mask[i]-e == i);
12705   }
12706
12707   // Eliminate identity shuffles.
12708   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12709   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12710   
12711   // If the LHS is a shufflevector itself, see if we can combine it with this
12712   // one without producing an unusual shuffle.  Here we are really conservative:
12713   // we are absolutely afraid of producing a shuffle mask not in the input
12714   // program, because the code gen may not be smart enough to turn a merged
12715   // shuffle into two specific shuffles: it may produce worse code.  As such,
12716   // we only merge two shuffles if the result is one of the two input shuffle
12717   // masks.  In this case, merging the shuffles just removes one instruction,
12718   // which we know is safe.  This is good for things like turning:
12719   // (splat(splat)) -> splat.
12720   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12721     if (isa<UndefValue>(RHS)) {
12722       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12723
12724       std::vector<unsigned> NewMask;
12725       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12726         if (Mask[i] >= 2*e)
12727           NewMask.push_back(2*e);
12728         else
12729           NewMask.push_back(LHSMask[Mask[i]]);
12730       
12731       // If the result mask is equal to the src shuffle or this shuffle mask, do
12732       // the replacement.
12733       if (NewMask == LHSMask || NewMask == Mask) {
12734         unsigned LHSInNElts =
12735           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12736         std::vector<Constant*> Elts;
12737         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12738           if (NewMask[i] >= LHSInNElts*2) {
12739             Elts.push_back(Context->getUndef(Type::Int32Ty));
12740           } else {
12741             Elts.push_back(Context->getConstantInt(Type::Int32Ty, NewMask[i]));
12742           }
12743         }
12744         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12745                                      LHSSVI->getOperand(1),
12746                                      Context->getConstantVector(Elts));
12747       }
12748     }
12749   }
12750
12751   return MadeChange ? &SVI : 0;
12752 }
12753
12754
12755
12756
12757 /// TryToSinkInstruction - Try to move the specified instruction from its
12758 /// current block into the beginning of DestBlock, which can only happen if it's
12759 /// safe to move the instruction past all of the instructions between it and the
12760 /// end of its block.
12761 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12762   assert(I->hasOneUse() && "Invariants didn't hold!");
12763
12764   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12765   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12766     return false;
12767
12768   // Do not sink alloca instructions out of the entry block.
12769   if (isa<AllocaInst>(I) && I->getParent() ==
12770         &DestBlock->getParent()->getEntryBlock())
12771     return false;
12772
12773   // We can only sink load instructions if there is nothing between the load and
12774   // the end of block that could change the value.
12775   if (I->mayReadFromMemory()) {
12776     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12777          Scan != E; ++Scan)
12778       if (Scan->mayWriteToMemory())
12779         return false;
12780   }
12781
12782   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12783
12784   CopyPrecedingStopPoint(I, InsertPos);
12785   I->moveBefore(InsertPos);
12786   ++NumSunkInst;
12787   return true;
12788 }
12789
12790
12791 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12792 /// all reachable code to the worklist.
12793 ///
12794 /// This has a couple of tricks to make the code faster and more powerful.  In
12795 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12796 /// them to the worklist (this significantly speeds up instcombine on code where
12797 /// many instructions are dead or constant).  Additionally, if we find a branch
12798 /// whose condition is a known constant, we only visit the reachable successors.
12799 ///
12800 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12801                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12802                                        InstCombiner &IC,
12803                                        const TargetData *TD) {
12804   SmallVector<BasicBlock*, 256> Worklist;
12805   Worklist.push_back(BB);
12806
12807   while (!Worklist.empty()) {
12808     BB = Worklist.back();
12809     Worklist.pop_back();
12810     
12811     // We have now visited this block!  If we've already been here, ignore it.
12812     if (!Visited.insert(BB)) continue;
12813
12814     DbgInfoIntrinsic *DBI_Prev = NULL;
12815     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12816       Instruction *Inst = BBI++;
12817       
12818       // DCE instruction if trivially dead.
12819       if (isInstructionTriviallyDead(Inst)) {
12820         ++NumDeadInst;
12821         DOUT << "IC: DCE: " << *Inst;
12822         Inst->eraseFromParent();
12823         continue;
12824       }
12825       
12826       // ConstantProp instruction if trivially constant.
12827       if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12828         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12829         Inst->replaceAllUsesWith(C);
12830         ++NumConstProp;
12831         Inst->eraseFromParent();
12832         continue;
12833       }
12834      
12835       // If there are two consecutive llvm.dbg.stoppoint calls then
12836       // it is likely that the optimizer deleted code in between these
12837       // two intrinsics. 
12838       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12839       if (DBI_Next) {
12840         if (DBI_Prev
12841             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12842             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12843           IC.RemoveFromWorkList(DBI_Prev);
12844           DBI_Prev->eraseFromParent();
12845         }
12846         DBI_Prev = DBI_Next;
12847       } else {
12848         DBI_Prev = 0;
12849       }
12850
12851       IC.AddToWorkList(Inst);
12852     }
12853
12854     // Recursively visit successors.  If this is a branch or switch on a
12855     // constant, only visit the reachable successor.
12856     TerminatorInst *TI = BB->getTerminator();
12857     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12858       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12859         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12860         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12861         Worklist.push_back(ReachableBB);
12862         continue;
12863       }
12864     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12865       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12866         // See if this is an explicit destination.
12867         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12868           if (SI->getCaseValue(i) == Cond) {
12869             BasicBlock *ReachableBB = SI->getSuccessor(i);
12870             Worklist.push_back(ReachableBB);
12871             continue;
12872           }
12873         
12874         // Otherwise it is the default destination.
12875         Worklist.push_back(SI->getSuccessor(0));
12876         continue;
12877       }
12878     }
12879     
12880     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12881       Worklist.push_back(TI->getSuccessor(i));
12882   }
12883 }
12884
12885 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12886   bool Changed = false;
12887   TD = &getAnalysis<TargetData>();
12888   
12889   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12890              << F.getNameStr() << "\n");
12891
12892   {
12893     // Do a depth-first traversal of the function, populate the worklist with
12894     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12895     // track of which blocks we visit.
12896     SmallPtrSet<BasicBlock*, 64> Visited;
12897     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12898
12899     // Do a quick scan over the function.  If we find any blocks that are
12900     // unreachable, remove any instructions inside of them.  This prevents
12901     // the instcombine code from having to deal with some bad special cases.
12902     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12903       if (!Visited.count(BB)) {
12904         Instruction *Term = BB->getTerminator();
12905         while (Term != BB->begin()) {   // Remove instrs bottom-up
12906           BasicBlock::iterator I = Term; --I;
12907
12908           DOUT << "IC: DCE: " << *I;
12909           // A debug intrinsic shouldn't force another iteration if we weren't
12910           // going to do one without it.
12911           if (!isa<DbgInfoIntrinsic>(I)) {
12912             ++NumDeadInst;
12913             Changed = true;
12914           }
12915           if (!I->use_empty())
12916             I->replaceAllUsesWith(Context->getUndef(I->getType()));
12917           I->eraseFromParent();
12918         }
12919       }
12920   }
12921
12922   while (!Worklist.empty()) {
12923     Instruction *I = RemoveOneFromWorkList();
12924     if (I == 0) continue;  // skip null values.
12925
12926     // Check to see if we can DCE the instruction.
12927     if (isInstructionTriviallyDead(I)) {
12928       // Add operands to the worklist.
12929       if (I->getNumOperands() < 4)
12930         AddUsesToWorkList(*I);
12931       ++NumDeadInst;
12932
12933       DOUT << "IC: DCE: " << *I;
12934
12935       I->eraseFromParent();
12936       RemoveFromWorkList(I);
12937       Changed = true;
12938       continue;
12939     }
12940
12941     // Instruction isn't dead, see if we can constant propagate it.
12942     if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12943       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12944
12945       // Add operands to the worklist.
12946       AddUsesToWorkList(*I);
12947       ReplaceInstUsesWith(*I, C);
12948
12949       ++NumConstProp;
12950       I->eraseFromParent();
12951       RemoveFromWorkList(I);
12952       Changed = true;
12953       continue;
12954     }
12955
12956     if (TD) {
12957       // See if we can constant fold its operands.
12958       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12959         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
12960           if (Constant *NewC = ConstantFoldConstantExpression(CE,   
12961                                   F.getContext(), TD))
12962             if (NewC != CE) {
12963               i->set(NewC);
12964               Changed = true;
12965             }
12966     }
12967
12968     // See if we can trivially sink this instruction to a successor basic block.
12969     if (I->hasOneUse()) {
12970       BasicBlock *BB = I->getParent();
12971       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12972       if (UserParent != BB) {
12973         bool UserIsSuccessor = false;
12974         // See if the user is one of our successors.
12975         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12976           if (*SI == UserParent) {
12977             UserIsSuccessor = true;
12978             break;
12979           }
12980
12981         // If the user is one of our immediate successors, and if that successor
12982         // only has us as a predecessors (we'd have to split the critical edge
12983         // otherwise), we can keep going.
12984         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12985             next(pred_begin(UserParent)) == pred_end(UserParent))
12986           // Okay, the CFG is simple enough, try to sink this instruction.
12987           Changed |= TryToSinkInstruction(I, UserParent);
12988       }
12989     }
12990
12991     // Now that we have an instruction, try combining it to simplify it...
12992 #ifndef NDEBUG
12993     std::string OrigI;
12994 #endif
12995     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
12996     if (Instruction *Result = visit(*I)) {
12997       ++NumCombined;
12998       // Should we replace the old instruction with a new one?
12999       if (Result != I) {
13000         DOUT << "IC: Old = " << *I
13001              << "    New = " << *Result;
13002
13003         // Everything uses the new instruction now.
13004         I->replaceAllUsesWith(Result);
13005
13006         // Push the new instruction and any users onto the worklist.
13007         AddToWorkList(Result);
13008         AddUsersToWorkList(*Result);
13009
13010         // Move the name to the new instruction first.
13011         Result->takeName(I);
13012
13013         // Insert the new instruction into the basic block...
13014         BasicBlock *InstParent = I->getParent();
13015         BasicBlock::iterator InsertPos = I;
13016
13017         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
13018           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13019             ++InsertPos;
13020
13021         InstParent->getInstList().insert(InsertPos, Result);
13022
13023         // Make sure that we reprocess all operands now that we reduced their
13024         // use counts.
13025         AddUsesToWorkList(*I);
13026
13027         // Instructions can end up on the worklist more than once.  Make sure
13028         // we do not process an instruction that has been deleted.
13029         RemoveFromWorkList(I);
13030
13031         // Erase the old instruction.
13032         InstParent->getInstList().erase(I);
13033       } else {
13034 #ifndef NDEBUG
13035         DOUT << "IC: Mod = " << OrigI
13036              << "    New = " << *I;
13037 #endif
13038
13039         // If the instruction was modified, it's possible that it is now dead.
13040         // if so, remove it.
13041         if (isInstructionTriviallyDead(I)) {
13042           // Make sure we process all operands now that we are reducing their
13043           // use counts.
13044           AddUsesToWorkList(*I);
13045
13046           // Instructions may end up in the worklist more than once.  Erase all
13047           // occurrences of this instruction.
13048           RemoveFromWorkList(I);
13049           I->eraseFromParent();
13050         } else {
13051           AddToWorkList(I);
13052           AddUsersToWorkList(*I);
13053         }
13054       }
13055       Changed = true;
13056     }
13057   }
13058
13059   assert(WorklistMap.empty() && "Worklist empty, but map not?");
13060     
13061   // Do an explicit clear, this shrinks the map if needed.
13062   WorklistMap.clear();
13063   return Changed;
13064 }
13065
13066
13067 bool InstCombiner::runOnFunction(Function &F) {
13068   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13069   
13070   bool EverMadeChange = false;
13071
13072   // Iterate while there is work to do.
13073   unsigned Iteration = 0;
13074   while (DoOneIteration(F, Iteration++))
13075     EverMadeChange = true;
13076   return EverMadeChange;
13077 }
13078
13079 FunctionPass *llvm::createInstructionCombiningPass() {
13080   return new InstCombiner();
13081 }