Convert more code to use Operator instead of explicitly handling both
[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 (cast *A to intptrtype) B -> 
2280   //   cast (GEP (cast *A to i8*) B)  -->  intptrtype
2281   {
2282     CastInst *CI = dyn_cast<CastInst>(LHS);
2283     Value *Other = RHS;
2284     if (!CI) {
2285       CI = dyn_cast<CastInst>(RHS);
2286       Other = LHS;
2287     }
2288     if (CI && CI->getType()->isSized() && 
2289         (CI->getType()->getScalarSizeInBits() ==
2290          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2291         && isa<PointerType>(CI->getOperand(0)->getType())) {
2292       unsigned AS =
2293         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2294       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2295                                   Context->getPointerType(Type::Int8Ty, AS), I);
2296       GetElementPtrInst *GEP = GetElementPtrInst::Create(I2, Other, "ctg2");
2297       // A GEP formed from an arbitrary add may overflow.
2298       cast<GEPOperator>(GEP)->setHasNoPointerOverflow(false);
2299       I2 = InsertNewInstBefore(GEP, I);
2300       return new PtrToIntInst(I2, CI->getType());
2301     }
2302   }
2303   
2304   // add (select X 0 (sub n A)) A  -->  select X A n
2305   {
2306     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2307     Value *A = RHS;
2308     if (!SI) {
2309       SI = dyn_cast<SelectInst>(RHS);
2310       A = LHS;
2311     }
2312     if (SI && SI->hasOneUse()) {
2313       Value *TV = SI->getTrueValue();
2314       Value *FV = SI->getFalseValue();
2315       Value *N;
2316
2317       // Can we fold the add into the argument of the select?
2318       // We check both true and false select arguments for a matching subtract.
2319       if (match(FV, m_Zero(), *Context) &&
2320           match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2321         // Fold the add into the true select value.
2322         return SelectInst::Create(SI->getCondition(), N, A);
2323       if (match(TV, m_Zero(), *Context) &&
2324           match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2325         // Fold the add into the false select value.
2326         return SelectInst::Create(SI->getCondition(), A, N);
2327     }
2328   }
2329
2330   // Check for (add (sext x), y), see if we can merge this into an
2331   // integer add followed by a sext.
2332   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2333     // (add (sext x), cst) --> (sext (add x, cst'))
2334     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2335       Constant *CI = 
2336         Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
2337       if (LHSConv->hasOneUse() &&
2338           Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
2339           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2340         // Insert the new, smaller add.
2341         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2342                                                         CI, "addconv");
2343         InsertNewInstBefore(NewAdd, I);
2344         return new SExtInst(NewAdd, I.getType());
2345       }
2346     }
2347     
2348     // (add (sext x), (sext y)) --> (sext (add int x, y))
2349     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2350       // Only do this if x/y have the same type, if at last one of them has a
2351       // single use (so we don't increase the number of sexts), and if the
2352       // integer add will not overflow.
2353       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2354           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2355           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2356                                    RHSConv->getOperand(0))) {
2357         // Insert the new integer add.
2358         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2359                                                         RHSConv->getOperand(0),
2360                                                         "addconv");
2361         InsertNewInstBefore(NewAdd, I);
2362         return new SExtInst(NewAdd, I.getType());
2363       }
2364     }
2365   }
2366
2367   return Changed ? &I : 0;
2368 }
2369
2370 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2371   bool Changed = SimplifyCommutative(I);
2372   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2373
2374   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2375     // X + 0 --> X
2376     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2377       if (CFP->isExactlyValue(Context->getConstantFPNegativeZero
2378                               (I.getType())->getValueAPF()))
2379         return ReplaceInstUsesWith(I, LHS);
2380     }
2381
2382     if (isa<PHINode>(LHS))
2383       if (Instruction *NV = FoldOpIntoPhi(I))
2384         return NV;
2385   }
2386
2387   // -A + B  -->  B - A
2388   // -A + -B  -->  -(A + B)
2389   if (Value *LHSV = dyn_castFNegVal(LHS, Context))
2390     return BinaryOperator::CreateFSub(RHS, LHSV);
2391
2392   // A + -B  -->  A - B
2393   if (!isa<Constant>(RHS))
2394     if (Value *V = dyn_castFNegVal(RHS, Context))
2395       return BinaryOperator::CreateFSub(LHS, V);
2396
2397   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2398   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2399     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2400       return ReplaceInstUsesWith(I, LHS);
2401
2402   // Check for (add double (sitofp x), y), see if we can merge this into an
2403   // integer add followed by a promotion.
2404   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2405     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2406     // ... if the constant fits in the integer value.  This is useful for things
2407     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2408     // requires a constant pool load, and generally allows the add to be better
2409     // instcombined.
2410     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2411       Constant *CI = 
2412       Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
2413       if (LHSConv->hasOneUse() &&
2414           Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
2415           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2416         // Insert the new integer add.
2417         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2418                                                         CI, "addconv");
2419         InsertNewInstBefore(NewAdd, I);
2420         return new SIToFPInst(NewAdd, I.getType());
2421       }
2422     }
2423     
2424     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2425     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2426       // Only do this if x/y have the same type, if at last one of them has a
2427       // single use (so we don't increase the number of int->fp conversions),
2428       // and if the integer add will not overflow.
2429       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2430           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2431           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2432                                    RHSConv->getOperand(0))) {
2433         // Insert the new integer add.
2434         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2435                                                         RHSConv->getOperand(0),
2436                                                         "addconv");
2437         InsertNewInstBefore(NewAdd, I);
2438         return new SIToFPInst(NewAdd, I.getType());
2439       }
2440     }
2441   }
2442   
2443   return Changed ? &I : 0;
2444 }
2445
2446 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2447   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2448
2449   if (Op0 == Op1)                        // sub X, X  -> 0
2450     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2451
2452   // If this is a 'B = x-(-A)', change to B = x+A...
2453   if (Value *V = dyn_castNegVal(Op1, Context))
2454     return BinaryOperator::CreateAdd(Op0, V);
2455
2456   if (isa<UndefValue>(Op0))
2457     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2458   if (isa<UndefValue>(Op1))
2459     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2460
2461   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2462     // Replace (-1 - A) with (~A)...
2463     if (C->isAllOnesValue())
2464       return BinaryOperator::CreateNot(*Context, Op1);
2465
2466     // C - ~X == X + (1+C)
2467     Value *X = 0;
2468     if (match(Op1, m_Not(m_Value(X)), *Context))
2469       return BinaryOperator::CreateAdd(X, AddOne(C, Context));
2470
2471     // -(X >>u 31) -> (X >>s 31)
2472     // -(X >>s 31) -> (X >>u 31)
2473     if (C->isZero()) {
2474       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2475         if (SI->getOpcode() == Instruction::LShr) {
2476           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2477             // Check to see if we are shifting out everything but the sign bit.
2478             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2479                 SI->getType()->getPrimitiveSizeInBits()-1) {
2480               // Ok, the transformation is safe.  Insert AShr.
2481               return BinaryOperator::Create(Instruction::AShr, 
2482                                           SI->getOperand(0), CU, SI->getName());
2483             }
2484           }
2485         }
2486         else if (SI->getOpcode() == Instruction::AShr) {
2487           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2488             // Check to see if we are shifting out everything but the sign bit.
2489             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2490                 SI->getType()->getPrimitiveSizeInBits()-1) {
2491               // Ok, the transformation is safe.  Insert LShr. 
2492               return BinaryOperator::CreateLShr(
2493                                           SI->getOperand(0), CU, SI->getName());
2494             }
2495           }
2496         }
2497       }
2498     }
2499
2500     // Try to fold constant sub into select arguments.
2501     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2502       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2503         return R;
2504
2505     // C - zext(bool) -> bool ? C - 1 : C
2506     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2507       if (ZI->getSrcTy() == Type::Int1Ty)
2508         return SelectInst::Create(ZI->getOperand(0), SubOne(C, Context), C);
2509   }
2510
2511   if (I.getType() == Type::Int1Ty)
2512     return BinaryOperator::CreateXor(Op0, Op1);
2513
2514   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2515     if (Op1I->getOpcode() == Instruction::Add) {
2516       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2517         return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(1),
2518                                          I.getName());
2519       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2520         return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(0), 
2521                                          I.getName());
2522       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2523         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2524           // C1-(X+C2) --> (C1-C2)-X
2525           return BinaryOperator::CreateSub(
2526             Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
2527       }
2528     }
2529
2530     if (Op1I->hasOneUse()) {
2531       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2532       // is not used by anyone else...
2533       //
2534       if (Op1I->getOpcode() == Instruction::Sub) {
2535         // Swap the two operands of the subexpr...
2536         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2537         Op1I->setOperand(0, IIOp1);
2538         Op1I->setOperand(1, IIOp0);
2539
2540         // Create the new top level add instruction...
2541         return BinaryOperator::CreateAdd(Op0, Op1);
2542       }
2543
2544       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2545       //
2546       if (Op1I->getOpcode() == Instruction::And &&
2547           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2548         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2549
2550         Value *NewNot =
2551           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, 
2552                                                         OtherOp, "B.not"), I);
2553         return BinaryOperator::CreateAnd(Op0, NewNot);
2554       }
2555
2556       // 0 - (X sdiv C)  -> (X sdiv -C)
2557       if (Op1I->getOpcode() == Instruction::SDiv)
2558         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2559           if (CSI->isZero())
2560             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2561               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2562                                           Context->getConstantExprNeg(DivRHS));
2563
2564       // X - X*C --> X * (1-C)
2565       ConstantInt *C2 = 0;
2566       if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2567         Constant *CP1 = 
2568           Context->getConstantExprSub(Context->getConstantInt(I.getType(), 1),
2569                                              C2);
2570         return BinaryOperator::CreateMul(Op0, CP1);
2571       }
2572     }
2573   }
2574
2575   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2576     if (Op0I->getOpcode() == Instruction::Add) {
2577       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2578         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2579       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2580         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2581     } else if (Op0I->getOpcode() == Instruction::Sub) {
2582       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2583         return BinaryOperator::CreateNeg(*Context, Op0I->getOperand(1),
2584                                          I.getName());
2585     }
2586   }
2587
2588   ConstantInt *C1;
2589   if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
2590     if (X == Op1)  // X*C - X --> X * (C-1)
2591       return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
2592
2593     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2594     if (X == dyn_castFoldableMul(Op1, C2, Context))
2595       return BinaryOperator::CreateMul(X, Context->getConstantExprSub(C1, C2));
2596   }
2597   return 0;
2598 }
2599
2600 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2601   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2602
2603   // If this is a 'B = x-(-A)', change to B = x+A...
2604   if (Value *V = dyn_castFNegVal(Op1, Context))
2605     return BinaryOperator::CreateFAdd(Op0, V);
2606
2607   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2608     if (Op1I->getOpcode() == Instruction::FAdd) {
2609       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2610         return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(1),
2611                                           I.getName());
2612       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2613         return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(0),
2614                                           I.getName());
2615     }
2616   }
2617
2618   return 0;
2619 }
2620
2621 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2622 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2623 /// TrueIfSigned if the result of the comparison is true when the input value is
2624 /// signed.
2625 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2626                            bool &TrueIfSigned) {
2627   switch (pred) {
2628   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2629     TrueIfSigned = true;
2630     return RHS->isZero();
2631   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2632     TrueIfSigned = true;
2633     return RHS->isAllOnesValue();
2634   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2635     TrueIfSigned = false;
2636     return RHS->isAllOnesValue();
2637   case ICmpInst::ICMP_UGT:
2638     // True if LHS u> RHS and RHS == high-bit-mask - 1
2639     TrueIfSigned = true;
2640     return RHS->getValue() ==
2641       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2642   case ICmpInst::ICMP_UGE: 
2643     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2644     TrueIfSigned = true;
2645     return RHS->getValue().isSignBit();
2646   default:
2647     return false;
2648   }
2649 }
2650
2651 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2652   bool Changed = SimplifyCommutative(I);
2653   Value *Op0 = I.getOperand(0);
2654
2655   // TODO: If Op1 is undef and Op0 is finite, return zero.
2656   if (!I.getType()->isFPOrFPVector() &&
2657       isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2658     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2659
2660   // Simplify mul instructions with a constant RHS...
2661   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2662     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2663
2664       // ((X << C1)*C2) == (X * (C2 << C1))
2665       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2666         if (SI->getOpcode() == Instruction::Shl)
2667           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2668             return BinaryOperator::CreateMul(SI->getOperand(0),
2669                                         Context->getConstantExprShl(CI, ShOp));
2670
2671       if (CI->isZero())
2672         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2673       if (CI->equalsInt(1))                  // X * 1  == X
2674         return ReplaceInstUsesWith(I, Op0);
2675       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2676         return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2677
2678       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2679       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2680         return BinaryOperator::CreateShl(Op0,
2681                  Context->getConstantInt(Op0->getType(), Val.logBase2()));
2682       }
2683     } else if (isa<VectorType>(Op1->getType())) {
2684       if (Op1->isNullValue())
2685         return ReplaceInstUsesWith(I, Op1);
2686
2687       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2688         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2689           return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2690
2691         // As above, vector X*splat(1.0) -> X in all defined cases.
2692         if (Constant *Splat = Op1V->getSplatValue()) {
2693           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2694             if (CI->equalsInt(1))
2695               return ReplaceInstUsesWith(I, Op0);
2696         }
2697       }
2698     }
2699     
2700     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2701       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2702           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2703         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2704         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2705                                                      Op1, "tmp");
2706         InsertNewInstBefore(Add, I);
2707         Value *C1C2 = Context->getConstantExprMul(Op1, 
2708                                            cast<Constant>(Op0I->getOperand(1)));
2709         return BinaryOperator::CreateAdd(Add, C1C2);
2710         
2711       }
2712
2713     // Try to fold constant mul into select arguments.
2714     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2715       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2716         return R;
2717
2718     if (isa<PHINode>(Op0))
2719       if (Instruction *NV = FoldOpIntoPhi(I))
2720         return NV;
2721   }
2722
2723   if (Value *Op0v = dyn_castNegVal(Op0, Context))     // -X * -Y = X*Y
2724     if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
2725       return BinaryOperator::CreateMul(Op0v, Op1v);
2726
2727   // (X / Y) *  Y = X - (X % Y)
2728   // (X / Y) * -Y = (X % Y) - X
2729   {
2730     Value *Op1 = I.getOperand(1);
2731     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2732     if (!BO ||
2733         (BO->getOpcode() != Instruction::UDiv && 
2734          BO->getOpcode() != Instruction::SDiv)) {
2735       Op1 = Op0;
2736       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2737     }
2738     Value *Neg = dyn_castNegVal(Op1, Context);
2739     if (BO && BO->hasOneUse() &&
2740         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2741         (BO->getOpcode() == Instruction::UDiv ||
2742          BO->getOpcode() == Instruction::SDiv)) {
2743       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2744
2745       Instruction *Rem;
2746       if (BO->getOpcode() == Instruction::UDiv)
2747         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2748       else
2749         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2750
2751       InsertNewInstBefore(Rem, I);
2752       Rem->takeName(BO);
2753
2754       if (Op1BO == Op1)
2755         return BinaryOperator::CreateSub(Op0BO, Rem);
2756       else
2757         return BinaryOperator::CreateSub(Rem, Op0BO);
2758     }
2759   }
2760
2761   if (I.getType() == Type::Int1Ty)
2762     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2763
2764   // If one of the operands of the multiply is a cast from a boolean value, then
2765   // we know the bool is either zero or one, so this is a 'masking' multiply.
2766   // See if we can simplify things based on how the boolean was originally
2767   // formed.
2768   CastInst *BoolCast = 0;
2769   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2770     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2771       BoolCast = CI;
2772   if (!BoolCast)
2773     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2774       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2775         BoolCast = CI;
2776   if (BoolCast) {
2777     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2778       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2779       const Type *SCOpTy = SCIOp0->getType();
2780       bool TIS = false;
2781       
2782       // If the icmp is true iff the sign bit of X is set, then convert this
2783       // multiply into a shift/and combination.
2784       if (isa<ConstantInt>(SCIOp1) &&
2785           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2786           TIS) {
2787         // Shift the X value right to turn it into "all signbits".
2788         Constant *Amt = Context->getConstantInt(SCIOp0->getType(),
2789                                           SCOpTy->getPrimitiveSizeInBits()-1);
2790         Value *V =
2791           InsertNewInstBefore(
2792             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2793                                             BoolCast->getOperand(0)->getName()+
2794                                             ".mask"), I);
2795
2796         // If the multiply type is not the same as the source type, sign extend
2797         // or truncate to the multiply type.
2798         if (I.getType() != V->getType()) {
2799           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2800           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2801           Instruction::CastOps opcode = 
2802             (SrcBits == DstBits ? Instruction::BitCast : 
2803              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2804           V = InsertCastBefore(opcode, V, I.getType(), I);
2805         }
2806
2807         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2808         return BinaryOperator::CreateAnd(V, OtherOp);
2809       }
2810     }
2811   }
2812
2813   return Changed ? &I : 0;
2814 }
2815
2816 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2817   bool Changed = SimplifyCommutative(I);
2818   Value *Op0 = I.getOperand(0);
2819
2820   // Simplify mul instructions with a constant RHS...
2821   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2822     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2823       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2824       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2825       if (Op1F->isExactlyValue(1.0))
2826         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2827     } else if (isa<VectorType>(Op1->getType())) {
2828       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2829         // As above, vector X*splat(1.0) -> X in all defined cases.
2830         if (Constant *Splat = Op1V->getSplatValue()) {
2831           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2832             if (F->isExactlyValue(1.0))
2833               return ReplaceInstUsesWith(I, Op0);
2834         }
2835       }
2836     }
2837
2838     // Try to fold constant mul into select arguments.
2839     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2840       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2841         return R;
2842
2843     if (isa<PHINode>(Op0))
2844       if (Instruction *NV = FoldOpIntoPhi(I))
2845         return NV;
2846   }
2847
2848   if (Value *Op0v = dyn_castFNegVal(Op0, Context))     // -X * -Y = X*Y
2849     if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
2850       return BinaryOperator::CreateFMul(Op0v, Op1v);
2851
2852   return Changed ? &I : 0;
2853 }
2854
2855 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2856 /// instruction.
2857 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2858   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2859   
2860   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2861   int NonNullOperand = -1;
2862   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2863     if (ST->isNullValue())
2864       NonNullOperand = 2;
2865   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2866   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2867     if (ST->isNullValue())
2868       NonNullOperand = 1;
2869   
2870   if (NonNullOperand == -1)
2871     return false;
2872   
2873   Value *SelectCond = SI->getOperand(0);
2874   
2875   // Change the div/rem to use 'Y' instead of the select.
2876   I.setOperand(1, SI->getOperand(NonNullOperand));
2877   
2878   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2879   // problem.  However, the select, or the condition of the select may have
2880   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2881   // propagate the known value for the select into other uses of it, and
2882   // propagate a known value of the condition into its other users.
2883   
2884   // If the select and condition only have a single use, don't bother with this,
2885   // early exit.
2886   if (SI->use_empty() && SelectCond->hasOneUse())
2887     return true;
2888   
2889   // Scan the current block backward, looking for other uses of SI.
2890   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2891   
2892   while (BBI != BBFront) {
2893     --BBI;
2894     // If we found a call to a function, we can't assume it will return, so
2895     // information from below it cannot be propagated above it.
2896     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2897       break;
2898     
2899     // Replace uses of the select or its condition with the known values.
2900     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2901          I != E; ++I) {
2902       if (*I == SI) {
2903         *I = SI->getOperand(NonNullOperand);
2904         AddToWorkList(BBI);
2905       } else if (*I == SelectCond) {
2906         *I = NonNullOperand == 1 ? Context->getConstantIntTrue() :
2907                                    Context->getConstantIntFalse();
2908         AddToWorkList(BBI);
2909       }
2910     }
2911     
2912     // If we past the instruction, quit looking for it.
2913     if (&*BBI == SI)
2914       SI = 0;
2915     if (&*BBI == SelectCond)
2916       SelectCond = 0;
2917     
2918     // If we ran out of things to eliminate, break out of the loop.
2919     if (SelectCond == 0 && SI == 0)
2920       break;
2921     
2922   }
2923   return true;
2924 }
2925
2926
2927 /// This function implements the transforms on div instructions that work
2928 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2929 /// used by the visitors to those instructions.
2930 /// @brief Transforms common to all three div instructions
2931 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2932   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2933
2934   // undef / X -> 0        for integer.
2935   // undef / X -> undef    for FP (the undef could be a snan).
2936   if (isa<UndefValue>(Op0)) {
2937     if (Op0->getType()->isFPOrFPVector())
2938       return ReplaceInstUsesWith(I, Op0);
2939     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2940   }
2941
2942   // X / undef -> undef
2943   if (isa<UndefValue>(Op1))
2944     return ReplaceInstUsesWith(I, Op1);
2945
2946   return 0;
2947 }
2948
2949 /// This function implements the transforms common to both integer division
2950 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2951 /// division instructions.
2952 /// @brief Common integer divide transforms
2953 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2954   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2955
2956   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2957   if (Op0 == Op1) {
2958     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2959       Constant *CI = Context->getConstantInt(Ty->getElementType(), 1);
2960       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2961       return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
2962     }
2963
2964     Constant *CI = Context->getConstantInt(I.getType(), 1);
2965     return ReplaceInstUsesWith(I, CI);
2966   }
2967   
2968   if (Instruction *Common = commonDivTransforms(I))
2969     return Common;
2970   
2971   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2972   // This does not apply for fdiv.
2973   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2974     return &I;
2975
2976   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2977     // div X, 1 == X
2978     if (RHS->equalsInt(1))
2979       return ReplaceInstUsesWith(I, Op0);
2980
2981     // (X / C1) / C2  -> X / (C1*C2)
2982     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2983       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2984         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2985           if (MultiplyOverflows(RHS, LHSRHS,
2986                                 I.getOpcode()==Instruction::SDiv, Context))
2987             return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2988           else 
2989             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2990                                       Context->getConstantExprMul(RHS, LHSRHS));
2991         }
2992
2993     if (!RHS->isZero()) { // avoid X udiv 0
2994       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2995         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2996           return R;
2997       if (isa<PHINode>(Op0))
2998         if (Instruction *NV = FoldOpIntoPhi(I))
2999           return NV;
3000     }
3001   }
3002
3003   // 0 / X == 0, we don't need to preserve faults!
3004   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3005     if (LHS->equalsInt(0))
3006       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3007
3008   // It can't be division by zero, hence it must be division by one.
3009   if (I.getType() == Type::Int1Ty)
3010     return ReplaceInstUsesWith(I, Op0);
3011
3012   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3013     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3014       // div X, 1 == X
3015       if (X->isOne())
3016         return ReplaceInstUsesWith(I, Op0);
3017   }
3018
3019   return 0;
3020 }
3021
3022 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3023   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3024
3025   // Handle the integer div common cases
3026   if (Instruction *Common = commonIDivTransforms(I))
3027     return Common;
3028
3029   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3030     // X udiv C^2 -> X >> C
3031     // Check to see if this is an unsigned division with an exact power of 2,
3032     // if so, convert to a right shift.
3033     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3034       return BinaryOperator::CreateLShr(Op0, 
3035             Context->getConstantInt(Op0->getType(), C->getValue().logBase2()));
3036
3037     // X udiv C, where C >= signbit
3038     if (C->getValue().isNegative()) {
3039       Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3040                                                     ICmpInst::ICMP_ULT, Op0, C),
3041                                       I);
3042       return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3043                                 Context->getConstantInt(I.getType(), 1));
3044     }
3045   }
3046
3047   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3048   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3049     if (RHSI->getOpcode() == Instruction::Shl &&
3050         isa<ConstantInt>(RHSI->getOperand(0))) {
3051       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3052       if (C1.isPowerOf2()) {
3053         Value *N = RHSI->getOperand(1);
3054         const Type *NTy = N->getType();
3055         if (uint32_t C2 = C1.logBase2()) {
3056           Constant *C2V = Context->getConstantInt(NTy, C2);
3057           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3058         }
3059         return BinaryOperator::CreateLShr(Op0, N);
3060       }
3061     }
3062   }
3063   
3064   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3065   // where C1&C2 are powers of two.
3066   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3067     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3068       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3069         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3070         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3071           // Compute the shift amounts
3072           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3073           // Construct the "on true" case of the select
3074           Constant *TC = Context->getConstantInt(Op0->getType(), TSA);
3075           Instruction *TSI = BinaryOperator::CreateLShr(
3076                                                  Op0, TC, SI->getName()+".t");
3077           TSI = InsertNewInstBefore(TSI, I);
3078   
3079           // Construct the "on false" case of the select
3080           Constant *FC = Context->getConstantInt(Op0->getType(), FSA); 
3081           Instruction *FSI = BinaryOperator::CreateLShr(
3082                                                  Op0, FC, SI->getName()+".f");
3083           FSI = InsertNewInstBefore(FSI, I);
3084
3085           // construct the select instruction and return it.
3086           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3087         }
3088       }
3089   return 0;
3090 }
3091
3092 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3093   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3094
3095   // Handle the integer div common cases
3096   if (Instruction *Common = commonIDivTransforms(I))
3097     return Common;
3098
3099   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3100     // sdiv X, -1 == -X
3101     if (RHS->isAllOnesValue())
3102       return BinaryOperator::CreateNeg(*Context, Op0);
3103   }
3104
3105   // If the sign bits of both operands are zero (i.e. we can prove they are
3106   // unsigned inputs), turn this into a udiv.
3107   if (I.getType()->isInteger()) {
3108     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3109     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3110       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3111       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3112     }
3113   }      
3114   
3115   return 0;
3116 }
3117
3118 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3119   return commonDivTransforms(I);
3120 }
3121
3122 /// This function implements the transforms on rem instructions that work
3123 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3124 /// is used by the visitors to those instructions.
3125 /// @brief Transforms common to all three rem instructions
3126 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3127   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3128
3129   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3130     if (I.getType()->isFPOrFPVector())
3131       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3132     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3133   }
3134   if (isa<UndefValue>(Op1))
3135     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3136
3137   // Handle cases involving: rem X, (select Cond, Y, Z)
3138   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3139     return &I;
3140
3141   return 0;
3142 }
3143
3144 /// This function implements the transforms common to both integer remainder
3145 /// instructions (urem and srem). It is called by the visitors to those integer
3146 /// remainder instructions.
3147 /// @brief Common integer remainder transforms
3148 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3149   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3150
3151   if (Instruction *common = commonRemTransforms(I))
3152     return common;
3153
3154   // 0 % X == 0 for integer, we don't need to preserve faults!
3155   if (Constant *LHS = dyn_cast<Constant>(Op0))
3156     if (LHS->isNullValue())
3157       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3158
3159   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3160     // X % 0 == undef, we don't need to preserve faults!
3161     if (RHS->equalsInt(0))
3162       return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
3163     
3164     if (RHS->equalsInt(1))  // X % 1 == 0
3165       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3166
3167     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3168       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3169         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3170           return R;
3171       } else if (isa<PHINode>(Op0I)) {
3172         if (Instruction *NV = FoldOpIntoPhi(I))
3173           return NV;
3174       }
3175
3176       // See if we can fold away this rem instruction.
3177       if (SimplifyDemandedInstructionBits(I))
3178         return &I;
3179     }
3180   }
3181
3182   return 0;
3183 }
3184
3185 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3186   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3187
3188   if (Instruction *common = commonIRemTransforms(I))
3189     return common;
3190   
3191   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3192     // X urem C^2 -> X and C
3193     // Check to see if this is an unsigned remainder with an exact power of 2,
3194     // if so, convert to a bitwise and.
3195     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3196       if (C->getValue().isPowerOf2())
3197         return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
3198   }
3199
3200   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3201     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3202     if (RHSI->getOpcode() == Instruction::Shl &&
3203         isa<ConstantInt>(RHSI->getOperand(0))) {
3204       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3205         Constant *N1 = Context->getAllOnesValue(I.getType());
3206         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3207                                                                    "tmp"), I);
3208         return BinaryOperator::CreateAnd(Op0, Add);
3209       }
3210     }
3211   }
3212
3213   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3214   // where C1&C2 are powers of two.
3215   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3216     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3217       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3218         // STO == 0 and SFO == 0 handled above.
3219         if ((STO->getValue().isPowerOf2()) && 
3220             (SFO->getValue().isPowerOf2())) {
3221           Value *TrueAnd = InsertNewInstBefore(
3222             BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3223                                       SI->getName()+".t"), I);
3224           Value *FalseAnd = InsertNewInstBefore(
3225             BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3226                                       SI->getName()+".f"), I);
3227           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3228         }
3229       }
3230   }
3231   
3232   return 0;
3233 }
3234
3235 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3236   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3237
3238   // Handle the integer rem common cases
3239   if (Instruction *common = commonIRemTransforms(I))
3240     return common;
3241   
3242   if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
3243     if (!isa<Constant>(RHSNeg) ||
3244         (isa<ConstantInt>(RHSNeg) &&
3245          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3246       // X % -Y -> X % Y
3247       AddUsesToWorkList(I);
3248       I.setOperand(1, RHSNeg);
3249       return &I;
3250     }
3251
3252   // If the sign bits of both operands are zero (i.e. we can prove they are
3253   // unsigned inputs), turn this into a urem.
3254   if (I.getType()->isInteger()) {
3255     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3256     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3257       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3258       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3259     }
3260   }
3261
3262   // If it's a constant vector, flip any negative values positive.
3263   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3264     unsigned VWidth = RHSV->getNumOperands();
3265
3266     bool hasNegative = false;
3267     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3268       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3269         if (RHS->getValue().isNegative())
3270           hasNegative = true;
3271
3272     if (hasNegative) {
3273       std::vector<Constant *> Elts(VWidth);
3274       for (unsigned i = 0; i != VWidth; ++i) {
3275         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3276           if (RHS->getValue().isNegative())
3277             Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
3278           else
3279             Elts[i] = RHS;
3280         }
3281       }
3282
3283       Constant *NewRHSV = Context->getConstantVector(Elts);
3284       if (NewRHSV != RHSV) {
3285         AddUsesToWorkList(I);
3286         I.setOperand(1, NewRHSV);
3287         return &I;
3288       }
3289     }
3290   }
3291
3292   return 0;
3293 }
3294
3295 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3296   return commonRemTransforms(I);
3297 }
3298
3299 // isOneBitSet - Return true if there is exactly one bit set in the specified
3300 // constant.
3301 static bool isOneBitSet(const ConstantInt *CI) {
3302   return CI->getValue().isPowerOf2();
3303 }
3304
3305 // isHighOnes - Return true if the constant is of the form 1+0+.
3306 // This is the same as lowones(~X).
3307 static bool isHighOnes(const ConstantInt *CI) {
3308   return (~CI->getValue() + 1).isPowerOf2();
3309 }
3310
3311 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3312 /// are carefully arranged to allow folding of expressions such as:
3313 ///
3314 ///      (A < B) | (A > B) --> (A != B)
3315 ///
3316 /// Note that this is only valid if the first and second predicates have the
3317 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3318 ///
3319 /// Three bits are used to represent the condition, as follows:
3320 ///   0  A > B
3321 ///   1  A == B
3322 ///   2  A < B
3323 ///
3324 /// <=>  Value  Definition
3325 /// 000     0   Always false
3326 /// 001     1   A >  B
3327 /// 010     2   A == B
3328 /// 011     3   A >= B
3329 /// 100     4   A <  B
3330 /// 101     5   A != B
3331 /// 110     6   A <= B
3332 /// 111     7   Always true
3333 ///  
3334 static unsigned getICmpCode(const ICmpInst *ICI) {
3335   switch (ICI->getPredicate()) {
3336     // False -> 0
3337   case ICmpInst::ICMP_UGT: return 1;  // 001
3338   case ICmpInst::ICMP_SGT: return 1;  // 001
3339   case ICmpInst::ICMP_EQ:  return 2;  // 010
3340   case ICmpInst::ICMP_UGE: return 3;  // 011
3341   case ICmpInst::ICMP_SGE: return 3;  // 011
3342   case ICmpInst::ICMP_ULT: return 4;  // 100
3343   case ICmpInst::ICMP_SLT: return 4;  // 100
3344   case ICmpInst::ICMP_NE:  return 5;  // 101
3345   case ICmpInst::ICMP_ULE: return 6;  // 110
3346   case ICmpInst::ICMP_SLE: return 6;  // 110
3347     // True -> 7
3348   default:
3349     llvm_unreachable("Invalid ICmp predicate!");
3350     return 0;
3351   }
3352 }
3353
3354 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3355 /// predicate into a three bit mask. It also returns whether it is an ordered
3356 /// predicate by reference.
3357 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3358   isOrdered = false;
3359   switch (CC) {
3360   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3361   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3362   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3363   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3364   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3365   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3366   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3367   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3368   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3369   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3370   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3371   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3372   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3373   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3374     // True -> 7
3375   default:
3376     // Not expecting FCMP_FALSE and FCMP_TRUE;
3377     llvm_unreachable("Unexpected FCmp predicate!");
3378     return 0;
3379   }
3380 }
3381
3382 /// getICmpValue - This is the complement of getICmpCode, which turns an
3383 /// opcode and two operands into either a constant true or false, or a brand 
3384 /// new ICmp instruction. The sign is passed in to determine which kind
3385 /// of predicate to use in the new icmp instruction.
3386 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3387                            LLVMContext *Context) {
3388   switch (code) {
3389   default: llvm_unreachable("Illegal ICmp code!");
3390   case  0: return Context->getConstantIntFalse();
3391   case  1: 
3392     if (sign)
3393       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
3394     else
3395       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3396   case  2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ,  LHS, RHS);
3397   case  3: 
3398     if (sign)
3399       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
3400     else
3401       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
3402   case  4: 
3403     if (sign)
3404       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
3405     else
3406       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3407   case  5: return new ICmpInst(*Context, ICmpInst::ICMP_NE,  LHS, RHS);
3408   case  6: 
3409     if (sign)
3410       return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
3411     else
3412       return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
3413   case  7: return Context->getConstantIntTrue();
3414   }
3415 }
3416
3417 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3418 /// opcode and two operands into either a FCmp instruction. isordered is passed
3419 /// in to determine which kind of predicate to use in the new fcmp instruction.
3420 static Value *getFCmpValue(bool isordered, unsigned code,
3421                            Value *LHS, Value *RHS, LLVMContext *Context) {
3422   switch (code) {
3423   default: llvm_unreachable("Illegal FCmp code!");
3424   case  0:
3425     if (isordered)
3426       return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
3427     else
3428       return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
3429   case  1: 
3430     if (isordered)
3431       return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
3432     else
3433       return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
3434   case  2: 
3435     if (isordered)
3436       return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
3437     else
3438       return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
3439   case  3: 
3440     if (isordered)
3441       return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
3442     else
3443       return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
3444   case  4: 
3445     if (isordered)
3446       return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
3447     else
3448       return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
3449   case  5: 
3450     if (isordered)
3451       return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
3452     else
3453       return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
3454   case  6: 
3455     if (isordered)
3456       return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
3457     else
3458       return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
3459   case  7: return Context->getConstantIntTrue();
3460   }
3461 }
3462
3463 /// PredicatesFoldable - Return true if both predicates match sign or if at
3464 /// least one of them is an equality comparison (which is signless).
3465 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3466   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3467          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3468          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3469 }
3470
3471 namespace { 
3472 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3473 struct FoldICmpLogical {
3474   InstCombiner &IC;
3475   Value *LHS, *RHS;
3476   ICmpInst::Predicate pred;
3477   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3478     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3479       pred(ICI->getPredicate()) {}
3480   bool shouldApply(Value *V) const {
3481     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3482       if (PredicatesFoldable(pred, ICI->getPredicate()))
3483         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3484                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3485     return false;
3486   }
3487   Instruction *apply(Instruction &Log) const {
3488     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3489     if (ICI->getOperand(0) != LHS) {
3490       assert(ICI->getOperand(1) == LHS);
3491       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3492     }
3493
3494     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3495     unsigned LHSCode = getICmpCode(ICI);
3496     unsigned RHSCode = getICmpCode(RHSICI);
3497     unsigned Code;
3498     switch (Log.getOpcode()) {
3499     case Instruction::And: Code = LHSCode & RHSCode; break;
3500     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3501     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3502     default: llvm_unreachable("Illegal logical opcode!"); return 0;
3503     }
3504
3505     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3506                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3507       
3508     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3509     if (Instruction *I = dyn_cast<Instruction>(RV))
3510       return I;
3511     // Otherwise, it's a constant boolean value...
3512     return IC.ReplaceInstUsesWith(Log, RV);
3513   }
3514 };
3515 } // end anonymous namespace
3516
3517 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3518 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3519 // guaranteed to be a binary operator.
3520 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3521                                     ConstantInt *OpRHS,
3522                                     ConstantInt *AndRHS,
3523                                     BinaryOperator &TheAnd) {
3524   Value *X = Op->getOperand(0);
3525   Constant *Together = 0;
3526   if (!Op->isShift())
3527     Together = Context->getConstantExprAnd(AndRHS, OpRHS);
3528
3529   switch (Op->getOpcode()) {
3530   case Instruction::Xor:
3531     if (Op->hasOneUse()) {
3532       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3533       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3534       InsertNewInstBefore(And, TheAnd);
3535       And->takeName(Op);
3536       return BinaryOperator::CreateXor(And, Together);
3537     }
3538     break;
3539   case Instruction::Or:
3540     if (Together == AndRHS) // (X | C) & C --> C
3541       return ReplaceInstUsesWith(TheAnd, AndRHS);
3542
3543     if (Op->hasOneUse() && Together != OpRHS) {
3544       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3545       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3546       InsertNewInstBefore(Or, TheAnd);
3547       Or->takeName(Op);
3548       return BinaryOperator::CreateAnd(Or, AndRHS);
3549     }
3550     break;
3551   case Instruction::Add:
3552     if (Op->hasOneUse()) {
3553       // Adding a one to a single bit bit-field should be turned into an XOR
3554       // of the bit.  First thing to check is to see if this AND is with a
3555       // single bit constant.
3556       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3557
3558       // If there is only one bit set...
3559       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3560         // Ok, at this point, we know that we are masking the result of the
3561         // ADD down to exactly one bit.  If the constant we are adding has
3562         // no bits set below this bit, then we can eliminate the ADD.
3563         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3564
3565         // Check to see if any bits below the one bit set in AndRHSV are set.
3566         if ((AddRHS & (AndRHSV-1)) == 0) {
3567           // If not, the only thing that can effect the output of the AND is
3568           // the bit specified by AndRHSV.  If that bit is set, the effect of
3569           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3570           // no effect.
3571           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3572             TheAnd.setOperand(0, X);
3573             return &TheAnd;
3574           } else {
3575             // Pull the XOR out of the AND.
3576             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3577             InsertNewInstBefore(NewAnd, TheAnd);
3578             NewAnd->takeName(Op);
3579             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3580           }
3581         }
3582       }
3583     }
3584     break;
3585
3586   case Instruction::Shl: {
3587     // We know that the AND will not produce any of the bits shifted in, so if
3588     // the anded constant includes them, clear them now!
3589     //
3590     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3591     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3592     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3593     ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShlMask);
3594
3595     if (CI->getValue() == ShlMask) { 
3596     // Masking out bits that the shift already masks
3597       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3598     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3599       TheAnd.setOperand(1, CI);
3600       return &TheAnd;
3601     }
3602     break;
3603   }
3604   case Instruction::LShr:
3605   {
3606     // We know that the AND will not produce any of the bits shifted in, so if
3607     // the anded constant includes them, clear them now!  This only applies to
3608     // unsigned shifts, because a signed shr may bring in set bits!
3609     //
3610     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3611     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3612     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3613     ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3614
3615     if (CI->getValue() == ShrMask) {   
3616     // Masking out bits that the shift already masks.
3617       return ReplaceInstUsesWith(TheAnd, Op);
3618     } else if (CI != AndRHS) {
3619       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3620       return &TheAnd;
3621     }
3622     break;
3623   }
3624   case Instruction::AShr:
3625     // Signed shr.
3626     // See if this is shifting in some sign extension, then masking it out
3627     // with an and.
3628     if (Op->hasOneUse()) {
3629       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3630       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3631       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3632       Constant *C = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3633       if (C == AndRHS) {          // Masking out bits shifted in.
3634         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3635         // Make the argument unsigned.
3636         Value *ShVal = Op->getOperand(0);
3637         ShVal = InsertNewInstBefore(
3638             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3639                                    Op->getName()), TheAnd);
3640         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3641       }
3642     }
3643     break;
3644   }
3645   return 0;
3646 }
3647
3648
3649 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3650 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3651 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3652 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3653 /// insert new instructions.
3654 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3655                                            bool isSigned, bool Inside, 
3656                                            Instruction &IB) {
3657   assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ? 
3658             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3659          "Lo is not <= Hi in range emission code!");
3660     
3661   if (Inside) {
3662     if (Lo == Hi)  // Trivially false.
3663       return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
3664
3665     // V >= Min && V < Hi --> V < Hi
3666     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3667       ICmpInst::Predicate pred = (isSigned ? 
3668         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3669       return new ICmpInst(*Context, pred, V, Hi);
3670     }
3671
3672     // Emit V-Lo <u Hi-Lo
3673     Constant *NegLo = Context->getConstantExprNeg(Lo);
3674     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3675     InsertNewInstBefore(Add, IB);
3676     Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
3677     return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
3678   }
3679
3680   if (Lo == Hi)  // Trivially true.
3681     return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
3682
3683   // V < Min || V >= Hi -> V > Hi-1
3684   Hi = SubOne(cast<ConstantInt>(Hi), Context);
3685   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3686     ICmpInst::Predicate pred = (isSigned ? 
3687         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3688     return new ICmpInst(*Context, pred, V, Hi);
3689   }
3690
3691   // Emit V-Lo >u Hi-1-Lo
3692   // Note that Hi has already had one subtracted from it, above.
3693   ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
3694   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3695   InsertNewInstBefore(Add, IB);
3696   Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
3697   return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
3698 }
3699
3700 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3701 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3702 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3703 // not, since all 1s are not contiguous.
3704 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3705   const APInt& V = Val->getValue();
3706   uint32_t BitWidth = Val->getType()->getBitWidth();
3707   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3708
3709   // look for the first zero bit after the run of ones
3710   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3711   // look for the first non-zero bit
3712   ME = V.getActiveBits(); 
3713   return true;
3714 }
3715
3716 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3717 /// where isSub determines whether the operator is a sub.  If we can fold one of
3718 /// the following xforms:
3719 /// 
3720 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3721 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3722 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3723 ///
3724 /// return (A +/- B).
3725 ///
3726 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3727                                         ConstantInt *Mask, bool isSub,
3728                                         Instruction &I) {
3729   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3730   if (!LHSI || LHSI->getNumOperands() != 2 ||
3731       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3732
3733   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3734
3735   switch (LHSI->getOpcode()) {
3736   default: return 0;
3737   case Instruction::And:
3738     if (Context->getConstantExprAnd(N, Mask) == Mask) {
3739       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3740       if ((Mask->getValue().countLeadingZeros() + 
3741            Mask->getValue().countPopulation()) == 
3742           Mask->getValue().getBitWidth())
3743         break;
3744
3745       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3746       // part, we don't need any explicit masks to take them out of A.  If that
3747       // is all N is, ignore it.
3748       uint32_t MB = 0, ME = 0;
3749       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3750         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3751         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3752         if (MaskedValueIsZero(RHS, Mask))
3753           break;
3754       }
3755     }
3756     return 0;
3757   case Instruction::Or:
3758   case Instruction::Xor:
3759     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3760     if ((Mask->getValue().countLeadingZeros() + 
3761          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3762         && Context->getConstantExprAnd(N, Mask)->isNullValue())
3763       break;
3764     return 0;
3765   }
3766   
3767   Instruction *New;
3768   if (isSub)
3769     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3770   else
3771     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3772   return InsertNewInstBefore(New, I);
3773 }
3774
3775 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3776 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3777                                           ICmpInst *LHS, ICmpInst *RHS) {
3778   Value *Val, *Val2;
3779   ConstantInt *LHSCst, *RHSCst;
3780   ICmpInst::Predicate LHSCC, RHSCC;
3781   
3782   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3783   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3784                          m_ConstantInt(LHSCst)), *Context) ||
3785       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3786                          m_ConstantInt(RHSCst)), *Context))
3787     return 0;
3788   
3789   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3790   // where C is a power of 2
3791   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3792       LHSCst->getValue().isPowerOf2()) {
3793     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3794     InsertNewInstBefore(NewOr, I);
3795     return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
3796   }
3797   
3798   // From here on, we only handle:
3799   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3800   if (Val != Val2) return 0;
3801   
3802   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3803   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3804       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3805       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3806       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3807     return 0;
3808   
3809   // We can't fold (ugt x, C) & (sgt x, C2).
3810   if (!PredicatesFoldable(LHSCC, RHSCC))
3811     return 0;
3812     
3813   // Ensure that the larger constant is on the RHS.
3814   bool ShouldSwap;
3815   if (ICmpInst::isSignedPredicate(LHSCC) ||
3816       (ICmpInst::isEquality(LHSCC) && 
3817        ICmpInst::isSignedPredicate(RHSCC)))
3818     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3819   else
3820     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3821     
3822   if (ShouldSwap) {
3823     std::swap(LHS, RHS);
3824     std::swap(LHSCst, RHSCst);
3825     std::swap(LHSCC, RHSCC);
3826   }
3827
3828   // At this point, we know we have have two icmp instructions
3829   // comparing a value against two constants and and'ing the result
3830   // together.  Because of the above check, we know that we only have
3831   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3832   // (from the FoldICmpLogical check above), that the two constants 
3833   // are not equal and that the larger constant is on the RHS
3834   assert(LHSCst != RHSCst && "Compares not folded above?");
3835
3836   switch (LHSCC) {
3837   default: llvm_unreachable("Unknown integer condition code!");
3838   case ICmpInst::ICMP_EQ:
3839     switch (RHSCC) {
3840     default: llvm_unreachable("Unknown integer condition code!");
3841     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3842     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3843     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3844       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3845     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3846     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3847     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3848       return ReplaceInstUsesWith(I, LHS);
3849     }
3850   case ICmpInst::ICMP_NE:
3851     switch (RHSCC) {
3852     default: llvm_unreachable("Unknown integer condition code!");
3853     case ICmpInst::ICMP_ULT:
3854       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
3855         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
3856       break;                        // (X != 13 & X u< 15) -> no change
3857     case ICmpInst::ICMP_SLT:
3858       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
3859         return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
3860       break;                        // (X != 13 & X s< 15) -> no change
3861     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3862     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3863     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3864       return ReplaceInstUsesWith(I, RHS);
3865     case ICmpInst::ICMP_NE:
3866       if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3867         Constant *AddCST = Context->getConstantExprNeg(LHSCst);
3868         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3869                                                      Val->getName()+".off");
3870         InsertNewInstBefore(Add, I);
3871         return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
3872                             Context->getConstantInt(Add->getType(), 1));
3873       }
3874       break;                        // (X != 13 & X != 15) -> no change
3875     }
3876     break;
3877   case ICmpInst::ICMP_ULT:
3878     switch (RHSCC) {
3879     default: llvm_unreachable("Unknown integer condition code!");
3880     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3881     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3882       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3883     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3884       break;
3885     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3886     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3887       return ReplaceInstUsesWith(I, LHS);
3888     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3889       break;
3890     }
3891     break;
3892   case ICmpInst::ICMP_SLT:
3893     switch (RHSCC) {
3894     default: llvm_unreachable("Unknown integer condition code!");
3895     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3896     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3897       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3898     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3899       break;
3900     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3901     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3902       return ReplaceInstUsesWith(I, LHS);
3903     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3904       break;
3905     }
3906     break;
3907   case ICmpInst::ICMP_UGT:
3908     switch (RHSCC) {
3909     default: llvm_unreachable("Unknown integer condition code!");
3910     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3911     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3912       return ReplaceInstUsesWith(I, RHS);
3913     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3914       break;
3915     case ICmpInst::ICMP_NE:
3916       if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
3917         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3918       break;                        // (X u> 13 & X != 15) -> no change
3919     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3920       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3921                              RHSCst, false, true, I);
3922     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3923       break;
3924     }
3925     break;
3926   case ICmpInst::ICMP_SGT:
3927     switch (RHSCC) {
3928     default: llvm_unreachable("Unknown integer condition code!");
3929     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3930     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3931       return ReplaceInstUsesWith(I, RHS);
3932     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3933       break;
3934     case ICmpInst::ICMP_NE:
3935       if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
3936         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3937       break;                        // (X s> 13 & X != 15) -> no change
3938     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3939       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3940                              RHSCst, true, true, I);
3941     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3942       break;
3943     }
3944     break;
3945   }
3946  
3947   return 0;
3948 }
3949
3950
3951 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3952   bool Changed = SimplifyCommutative(I);
3953   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3954
3955   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3956     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3957
3958   // and X, X = X
3959   if (Op0 == Op1)
3960     return ReplaceInstUsesWith(I, Op1);
3961
3962   // See if we can simplify any instructions used by the instruction whose sole 
3963   // purpose is to compute bits we don't care about.
3964   if (SimplifyDemandedInstructionBits(I))
3965     return &I;
3966   if (isa<VectorType>(I.getType())) {
3967     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3968       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3969         return ReplaceInstUsesWith(I, I.getOperand(0));
3970     } else if (isa<ConstantAggregateZero>(Op1)) {
3971       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3972     }
3973   }
3974
3975   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3976     const APInt& AndRHSMask = AndRHS->getValue();
3977     APInt NotAndRHS(~AndRHSMask);
3978
3979     // Optimize a variety of ((val OP C1) & C2) combinations...
3980     if (isa<BinaryOperator>(Op0)) {
3981       Instruction *Op0I = cast<Instruction>(Op0);
3982       Value *Op0LHS = Op0I->getOperand(0);
3983       Value *Op0RHS = Op0I->getOperand(1);
3984       switch (Op0I->getOpcode()) {
3985       case Instruction::Xor:
3986       case Instruction::Or:
3987         // If the mask is only needed on one incoming arm, push it up.
3988         if (Op0I->hasOneUse()) {
3989           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3990             // Not masking anything out for the LHS, move to RHS.
3991             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3992                                                    Op0RHS->getName()+".masked");
3993             InsertNewInstBefore(NewRHS, I);
3994             return BinaryOperator::Create(
3995                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3996           }
3997           if (!isa<Constant>(Op0RHS) &&
3998               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3999             // Not masking anything out for the RHS, move to LHS.
4000             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
4001                                                    Op0LHS->getName()+".masked");
4002             InsertNewInstBefore(NewLHS, I);
4003             return BinaryOperator::Create(
4004                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4005           }
4006         }
4007
4008         break;
4009       case Instruction::Add:
4010         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4011         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4012         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4013         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4014           return BinaryOperator::CreateAnd(V, AndRHS);
4015         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4016           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4017         break;
4018
4019       case Instruction::Sub:
4020         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4021         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4022         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4023         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4024           return BinaryOperator::CreateAnd(V, AndRHS);
4025
4026         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4027         // has 1's for all bits that the subtraction with A might affect.
4028         if (Op0I->hasOneUse()) {
4029           uint32_t BitWidth = AndRHSMask.getBitWidth();
4030           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4031           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4032
4033           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4034           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4035               MaskedValueIsZero(Op0LHS, Mask)) {
4036             Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
4037             InsertNewInstBefore(NewNeg, I);
4038             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4039           }
4040         }
4041         break;
4042
4043       case Instruction::Shl:
4044       case Instruction::LShr:
4045         // (1 << x) & 1 --> zext(x == 0)
4046         // (1 >> x) & 1 --> zext(x == 0)
4047         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4048           Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4049                                     Op0RHS, Context->getNullValue(I.getType()));
4050           InsertNewInstBefore(NewICmp, I);
4051           return new ZExtInst(NewICmp, I.getType());
4052         }
4053         break;
4054       }
4055
4056       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4057         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4058           return Res;
4059     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4060       // If this is an integer truncation or change from signed-to-unsigned, and
4061       // if the source is an and/or with immediate, transform it.  This
4062       // frequently occurs for bitfield accesses.
4063       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4064         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4065             CastOp->getNumOperands() == 2)
4066           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4067             if (CastOp->getOpcode() == Instruction::And) {
4068               // Change: and (cast (and X, C1) to T), C2
4069               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4070               // This will fold the two constants together, which may allow 
4071               // other simplifications.
4072               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4073                 CastOp->getOperand(0), I.getType(), 
4074                 CastOp->getName()+".shrunk");
4075               NewCast = InsertNewInstBefore(NewCast, I);
4076               // trunc_or_bitcast(C1)&C2
4077               Constant *C3 =
4078                       Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4079               C3 = Context->getConstantExprAnd(C3, AndRHS);
4080               return BinaryOperator::CreateAnd(NewCast, C3);
4081             } else if (CastOp->getOpcode() == Instruction::Or) {
4082               // Change: and (cast (or X, C1) to T), C2
4083               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4084               Constant *C3 =
4085                       Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4086               if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4087                 // trunc(C1)&C2
4088                 return ReplaceInstUsesWith(I, AndRHS);
4089             }
4090           }
4091       }
4092     }
4093
4094     // Try to fold constant and into select arguments.
4095     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4096       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4097         return R;
4098     if (isa<PHINode>(Op0))
4099       if (Instruction *NV = FoldOpIntoPhi(I))
4100         return NV;
4101   }
4102
4103   Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4104   Value *Op1NotVal = dyn_castNotVal(Op1, Context);
4105
4106   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4107     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
4108
4109   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4110   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4111     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4112                                                I.getName()+".demorgan");
4113     InsertNewInstBefore(Or, I);
4114     return BinaryOperator::CreateNot(*Context, Or);
4115   }
4116   
4117   {
4118     Value *A = 0, *B = 0, *C = 0, *D = 0;
4119     if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
4120       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4121         return ReplaceInstUsesWith(I, Op1);
4122     
4123       // (A|B) & ~(A&B) -> A^B
4124       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4125         if ((A == C && B == D) || (A == D && B == C))
4126           return BinaryOperator::CreateXor(A, B);
4127       }
4128     }
4129     
4130     if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
4131       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4132         return ReplaceInstUsesWith(I, Op0);
4133
4134       // ~(A&B) & (A|B) -> A^B
4135       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4136         if ((A == C && B == D) || (A == D && B == C))
4137           return BinaryOperator::CreateXor(A, B);
4138       }
4139     }
4140     
4141     if (Op0->hasOneUse() &&
4142         match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4143       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4144         I.swapOperands();     // Simplify below
4145         std::swap(Op0, Op1);
4146       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4147         cast<BinaryOperator>(Op0)->swapOperands();
4148         I.swapOperands();     // Simplify below
4149         std::swap(Op0, Op1);
4150       }
4151     }
4152
4153     if (Op1->hasOneUse() &&
4154         match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4155       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4156         cast<BinaryOperator>(Op1)->swapOperands();
4157         std::swap(A, B);
4158       }
4159       if (A == Op0) {                                // A&(A^B) -> A & ~B
4160         Instruction *NotB = BinaryOperator::CreateNot(*Context, B, "tmp");
4161         InsertNewInstBefore(NotB, I);
4162         return BinaryOperator::CreateAnd(A, NotB);
4163       }
4164     }
4165
4166     // (A&((~A)|B)) -> A&B
4167     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4168         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
4169       return BinaryOperator::CreateAnd(A, Op1);
4170     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4171         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
4172       return BinaryOperator::CreateAnd(A, Op0);
4173   }
4174   
4175   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4176     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4177     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4178       return R;
4179
4180     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4181       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4182         return Res;
4183   }
4184
4185   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4186   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4187     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4188       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4189         const Type *SrcTy = Op0C->getOperand(0)->getType();
4190         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4191             // Only do this if the casts both really cause code to be generated.
4192             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4193                               I.getType(), TD) &&
4194             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4195                               I.getType(), TD)) {
4196           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4197                                                          Op1C->getOperand(0),
4198                                                          I.getName());
4199           InsertNewInstBefore(NewOp, I);
4200           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4201         }
4202       }
4203     
4204   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4205   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4206     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4207       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4208           SI0->getOperand(1) == SI1->getOperand(1) &&
4209           (SI0->hasOneUse() || SI1->hasOneUse())) {
4210         Instruction *NewOp =
4211           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4212                                                         SI1->getOperand(0),
4213                                                         SI0->getName()), I);
4214         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4215                                       SI1->getOperand(1));
4216       }
4217   }
4218
4219   // If and'ing two fcmp, try combine them into one.
4220   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4221     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4222       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4223           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4224         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4225         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4226           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4227             // If either of the constants are nans, then the whole thing returns
4228             // false.
4229             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4230               return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4231             return new FCmpInst(*Context, FCmpInst::FCMP_ORD, 
4232                                 LHS->getOperand(0), RHS->getOperand(0));
4233           }
4234       } else {
4235         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4236         FCmpInst::Predicate Op0CC, Op1CC;
4237         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4238                   m_Value(Op0RHS)), *Context) &&
4239             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4240                   m_Value(Op1RHS)), *Context)) {
4241           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4242             // Swap RHS operands to match LHS.
4243             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4244             std::swap(Op1LHS, Op1RHS);
4245           }
4246           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4247             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4248             if (Op0CC == Op1CC)
4249               return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4250                                   Op0LHS, Op0RHS);
4251             else if (Op0CC == FCmpInst::FCMP_FALSE ||
4252                      Op1CC == FCmpInst::FCMP_FALSE)
4253               return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4254             else if (Op0CC == FCmpInst::FCMP_TRUE)
4255               return ReplaceInstUsesWith(I, Op1);
4256             else if (Op1CC == FCmpInst::FCMP_TRUE)
4257               return ReplaceInstUsesWith(I, Op0);
4258             bool Op0Ordered;
4259             bool Op1Ordered;
4260             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4261             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4262             if (Op1Pred == 0) {
4263               std::swap(Op0, Op1);
4264               std::swap(Op0Pred, Op1Pred);
4265               std::swap(Op0Ordered, Op1Ordered);
4266             }
4267             if (Op0Pred == 0) {
4268               // uno && ueq -> uno && (uno || eq) -> ueq
4269               // ord && olt -> ord && (ord && lt) -> olt
4270               if (Op0Ordered == Op1Ordered)
4271                 return ReplaceInstUsesWith(I, Op1);
4272               // uno && oeq -> uno && (ord && eq) -> false
4273               // uno && ord -> false
4274               if (!Op0Ordered)
4275                 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4276               // ord && ueq -> ord && (uno || eq) -> oeq
4277               return cast<Instruction>(getFCmpValue(true, Op1Pred,
4278                                                     Op0LHS, Op0RHS, Context));
4279             }
4280           }
4281         }
4282       }
4283     }
4284   }
4285
4286   return Changed ? &I : 0;
4287 }
4288
4289 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4290 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4291 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4292 /// the expression came from the corresponding "byte swapped" byte in some other
4293 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4294 /// we know that the expression deposits the low byte of %X into the high byte
4295 /// of the bswap result and that all other bytes are zero.  This expression is
4296 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4297 /// match.
4298 ///
4299 /// This function returns true if the match was unsuccessful and false if so.
4300 /// On entry to the function the "OverallLeftShift" is a signed integer value
4301 /// indicating the number of bytes that the subexpression is later shifted.  For
4302 /// example, if the expression is later right shifted by 16 bits, the
4303 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4304 /// byte of ByteValues is actually being set.
4305 ///
4306 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4307 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4308 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4309 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4310 /// always in the local (OverallLeftShift) coordinate space.
4311 ///
4312 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4313                               SmallVector<Value*, 8> &ByteValues) {
4314   if (Instruction *I = dyn_cast<Instruction>(V)) {
4315     // If this is an or instruction, it may be an inner node of the bswap.
4316     if (I->getOpcode() == Instruction::Or) {
4317       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4318                                ByteValues) ||
4319              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4320                                ByteValues);
4321     }
4322   
4323     // If this is a logical shift by a constant multiple of 8, recurse with
4324     // OverallLeftShift and ByteMask adjusted.
4325     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4326       unsigned ShAmt = 
4327         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4328       // Ensure the shift amount is defined and of a byte value.
4329       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4330         return true;
4331
4332       unsigned ByteShift = ShAmt >> 3;
4333       if (I->getOpcode() == Instruction::Shl) {
4334         // X << 2 -> collect(X, +2)
4335         OverallLeftShift += ByteShift;
4336         ByteMask >>= ByteShift;
4337       } else {
4338         // X >>u 2 -> collect(X, -2)
4339         OverallLeftShift -= ByteShift;
4340         ByteMask <<= ByteShift;
4341         ByteMask &= (~0U >> (32-ByteValues.size()));
4342       }
4343
4344       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4345       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4346
4347       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4348                                ByteValues);
4349     }
4350
4351     // If this is a logical 'and' with a mask that clears bytes, clear the
4352     // corresponding bytes in ByteMask.
4353     if (I->getOpcode() == Instruction::And &&
4354         isa<ConstantInt>(I->getOperand(1))) {
4355       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4356       unsigned NumBytes = ByteValues.size();
4357       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4358       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4359       
4360       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4361         // If this byte is masked out by a later operation, we don't care what
4362         // the and mask is.
4363         if ((ByteMask & (1 << i)) == 0)
4364           continue;
4365         
4366         // If the AndMask is all zeros for this byte, clear the bit.
4367         APInt MaskB = AndMask & Byte;
4368         if (MaskB == 0) {
4369           ByteMask &= ~(1U << i);
4370           continue;
4371         }
4372         
4373         // If the AndMask is not all ones for this byte, it's not a bytezap.
4374         if (MaskB != Byte)
4375           return true;
4376
4377         // Otherwise, this byte is kept.
4378       }
4379
4380       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4381                                ByteValues);
4382     }
4383   }
4384   
4385   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4386   // the input value to the bswap.  Some observations: 1) if more than one byte
4387   // is demanded from this input, then it could not be successfully assembled
4388   // into a byteswap.  At least one of the two bytes would not be aligned with
4389   // their ultimate destination.
4390   if (!isPowerOf2_32(ByteMask)) return true;
4391   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4392   
4393   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4394   // is demanded, it needs to go into byte 0 of the result.  This means that the
4395   // byte needs to be shifted until it lands in the right byte bucket.  The
4396   // shift amount depends on the position: if the byte is coming from the high
4397   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4398   // low part, it must be shifted left.
4399   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4400   if (InputByteNo < ByteValues.size()/2) {
4401     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4402       return true;
4403   } else {
4404     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4405       return true;
4406   }
4407   
4408   // If the destination byte value is already defined, the values are or'd
4409   // together, which isn't a bswap (unless it's an or of the same bits).
4410   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4411     return true;
4412   ByteValues[DestByteNo] = V;
4413   return false;
4414 }
4415
4416 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4417 /// If so, insert the new bswap intrinsic and return it.
4418 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4419   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4420   if (!ITy || ITy->getBitWidth() % 16 || 
4421       // ByteMask only allows up to 32-byte values.
4422       ITy->getBitWidth() > 32*8) 
4423     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4424   
4425   /// ByteValues - For each byte of the result, we keep track of which value
4426   /// defines each byte.
4427   SmallVector<Value*, 8> ByteValues;
4428   ByteValues.resize(ITy->getBitWidth()/8);
4429     
4430   // Try to find all the pieces corresponding to the bswap.
4431   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4432   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4433     return 0;
4434   
4435   // Check to see if all of the bytes come from the same value.
4436   Value *V = ByteValues[0];
4437   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4438   
4439   // Check to make sure that all of the bytes come from the same value.
4440   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4441     if (ByteValues[i] != V)
4442       return 0;
4443   const Type *Tys[] = { ITy };
4444   Module *M = I.getParent()->getParent()->getParent();
4445   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4446   return CallInst::Create(F, V);
4447 }
4448
4449 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4450 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4451 /// we can simplify this expression to "cond ? C : D or B".
4452 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4453                                          Value *C, Value *D,
4454                                          LLVMContext *Context) {
4455   // If A is not a select of -1/0, this cannot match.
4456   Value *Cond = 0;
4457   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
4458     return 0;
4459
4460   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4461   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4462     return SelectInst::Create(Cond, C, B);
4463   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4464     return SelectInst::Create(Cond, C, B);
4465   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4466   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4467     return SelectInst::Create(Cond, C, D);
4468   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4469     return SelectInst::Create(Cond, C, D);
4470   return 0;
4471 }
4472
4473 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4474 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4475                                          ICmpInst *LHS, ICmpInst *RHS) {
4476   Value *Val, *Val2;
4477   ConstantInt *LHSCst, *RHSCst;
4478   ICmpInst::Predicate LHSCC, RHSCC;
4479   
4480   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4481   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4482              m_ConstantInt(LHSCst)), *Context) ||
4483       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4484              m_ConstantInt(RHSCst)), *Context))
4485     return 0;
4486   
4487   // From here on, we only handle:
4488   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4489   if (Val != Val2) return 0;
4490   
4491   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4492   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4493       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4494       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4495       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4496     return 0;
4497   
4498   // We can't fold (ugt x, C) | (sgt x, C2).
4499   if (!PredicatesFoldable(LHSCC, RHSCC))
4500     return 0;
4501   
4502   // Ensure that the larger constant is on the RHS.
4503   bool ShouldSwap;
4504   if (ICmpInst::isSignedPredicate(LHSCC) ||
4505       (ICmpInst::isEquality(LHSCC) && 
4506        ICmpInst::isSignedPredicate(RHSCC)))
4507     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4508   else
4509     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4510   
4511   if (ShouldSwap) {
4512     std::swap(LHS, RHS);
4513     std::swap(LHSCst, RHSCst);
4514     std::swap(LHSCC, RHSCC);
4515   }
4516   
4517   // At this point, we know we have have two icmp instructions
4518   // comparing a value against two constants and or'ing the result
4519   // together.  Because of the above check, we know that we only have
4520   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4521   // FoldICmpLogical check above), that the two constants are not
4522   // equal.
4523   assert(LHSCst != RHSCst && "Compares not folded above?");
4524
4525   switch (LHSCC) {
4526   default: llvm_unreachable("Unknown integer condition code!");
4527   case ICmpInst::ICMP_EQ:
4528     switch (RHSCC) {
4529     default: llvm_unreachable("Unknown integer condition code!");
4530     case ICmpInst::ICMP_EQ:
4531       if (LHSCst == SubOne(RHSCst, Context)) {
4532         // (X == 13 | X == 14) -> X-13 <u 2
4533         Constant *AddCST = Context->getConstantExprNeg(LHSCst);
4534         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4535                                                      Val->getName()+".off");
4536         InsertNewInstBefore(Add, I);
4537         AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
4538         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
4539       }
4540       break;                         // (X == 13 | X == 15) -> no change
4541     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4542     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4543       break;
4544     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4545     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4546     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4547       return ReplaceInstUsesWith(I, RHS);
4548     }
4549     break;
4550   case ICmpInst::ICMP_NE:
4551     switch (RHSCC) {
4552     default: llvm_unreachable("Unknown integer condition code!");
4553     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4554     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4555     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4556       return ReplaceInstUsesWith(I, LHS);
4557     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4558     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4559     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4560       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4561     }
4562     break;
4563   case ICmpInst::ICMP_ULT:
4564     switch (RHSCC) {
4565     default: llvm_unreachable("Unknown integer condition code!");
4566     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4567       break;
4568     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4569       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4570       // this can cause overflow.
4571       if (RHSCst->isMaxValue(false))
4572         return ReplaceInstUsesWith(I, LHS);
4573       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4574                              false, false, I);
4575     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4576       break;
4577     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4578     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4579       return ReplaceInstUsesWith(I, RHS);
4580     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4581       break;
4582     }
4583     break;
4584   case ICmpInst::ICMP_SLT:
4585     switch (RHSCC) {
4586     default: llvm_unreachable("Unknown integer condition code!");
4587     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4588       break;
4589     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4590       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4591       // this can cause overflow.
4592       if (RHSCst->isMaxValue(true))
4593         return ReplaceInstUsesWith(I, LHS);
4594       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4595                              true, false, I);
4596     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4597       break;
4598     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4599     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4600       return ReplaceInstUsesWith(I, RHS);
4601     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4602       break;
4603     }
4604     break;
4605   case ICmpInst::ICMP_UGT:
4606     switch (RHSCC) {
4607     default: llvm_unreachable("Unknown integer condition code!");
4608     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4609     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4610       return ReplaceInstUsesWith(I, LHS);
4611     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4612       break;
4613     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4614     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4615       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4616     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4617       break;
4618     }
4619     break;
4620   case ICmpInst::ICMP_SGT:
4621     switch (RHSCC) {
4622     default: llvm_unreachable("Unknown integer condition code!");
4623     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4624     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4625       return ReplaceInstUsesWith(I, LHS);
4626     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4627       break;
4628     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4629     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4630       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4631     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4632       break;
4633     }
4634     break;
4635   }
4636   return 0;
4637 }
4638
4639 /// FoldOrWithConstants - This helper function folds:
4640 ///
4641 ///     ((A | B) & C1) | (B & C2)
4642 ///
4643 /// into:
4644 /// 
4645 ///     (A & C1) | B
4646 ///
4647 /// when the XOR of the two constants is "all ones" (-1).
4648 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4649                                                Value *A, Value *B, Value *C) {
4650   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4651   if (!CI1) return 0;
4652
4653   Value *V1 = 0;
4654   ConstantInt *CI2 = 0;
4655   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
4656
4657   APInt Xor = CI1->getValue() ^ CI2->getValue();
4658   if (!Xor.isAllOnesValue()) return 0;
4659
4660   if (V1 == A || V1 == B) {
4661     Instruction *NewOp =
4662       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4663     return BinaryOperator::CreateOr(NewOp, V1);
4664   }
4665
4666   return 0;
4667 }
4668
4669 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4670   bool Changed = SimplifyCommutative(I);
4671   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4672
4673   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4674     return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4675
4676   // or X, X = X
4677   if (Op0 == Op1)
4678     return ReplaceInstUsesWith(I, Op0);
4679
4680   // See if we can simplify any instructions used by the instruction whose sole 
4681   // purpose is to compute bits we don't care about.
4682   if (SimplifyDemandedInstructionBits(I))
4683     return &I;
4684   if (isa<VectorType>(I.getType())) {
4685     if (isa<ConstantAggregateZero>(Op1)) {
4686       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4687     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4688       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4689         return ReplaceInstUsesWith(I, I.getOperand(1));
4690     }
4691   }
4692
4693   // or X, -1 == -1
4694   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4695     ConstantInt *C1 = 0; Value *X = 0;
4696     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4697     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) && 
4698         isOnlyUse(Op0)) {
4699       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4700       InsertNewInstBefore(Or, I);
4701       Or->takeName(Op0);
4702       return BinaryOperator::CreateAnd(Or, 
4703                Context->getConstantInt(RHS->getValue() | C1->getValue()));
4704     }
4705
4706     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4707     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) && 
4708         isOnlyUse(Op0)) {
4709       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4710       InsertNewInstBefore(Or, I);
4711       Or->takeName(Op0);
4712       return BinaryOperator::CreateXor(Or,
4713                  Context->getConstantInt(C1->getValue() & ~RHS->getValue()));
4714     }
4715
4716     // Try to fold constant and into select arguments.
4717     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4718       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4719         return R;
4720     if (isa<PHINode>(Op0))
4721       if (Instruction *NV = FoldOpIntoPhi(I))
4722         return NV;
4723   }
4724
4725   Value *A = 0, *B = 0;
4726   ConstantInt *C1 = 0, *C2 = 0;
4727
4728   if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
4729     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4730       return ReplaceInstUsesWith(I, Op1);
4731   if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
4732     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4733       return ReplaceInstUsesWith(I, Op0);
4734
4735   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4736   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4737   if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4738       match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4739       (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4740        match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
4741     if (Instruction *BSwap = MatchBSwap(I))
4742       return BSwap;
4743   }
4744   
4745   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4746   if (Op0->hasOneUse() &&
4747       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4748       MaskedValueIsZero(Op1, C1->getValue())) {
4749     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4750     InsertNewInstBefore(NOr, I);
4751     NOr->takeName(Op0);
4752     return BinaryOperator::CreateXor(NOr, C1);
4753   }
4754
4755   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4756   if (Op1->hasOneUse() &&
4757       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4758       MaskedValueIsZero(Op0, C1->getValue())) {
4759     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4760     InsertNewInstBefore(NOr, I);
4761     NOr->takeName(Op0);
4762     return BinaryOperator::CreateXor(NOr, C1);
4763   }
4764
4765   // (A & C)|(B & D)
4766   Value *C = 0, *D = 0;
4767   if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4768       match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
4769     Value *V1 = 0, *V2 = 0, *V3 = 0;
4770     C1 = dyn_cast<ConstantInt>(C);
4771     C2 = dyn_cast<ConstantInt>(D);
4772     if (C1 && C2) {  // (A & C1)|(B & C2)
4773       // If we have: ((V + N) & C1) | (V & C2)
4774       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4775       // replace with V+N.
4776       if (C1->getValue() == ~C2->getValue()) {
4777         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4778             match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4779           // Add commutes, try both ways.
4780           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4781             return ReplaceInstUsesWith(I, A);
4782           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4783             return ReplaceInstUsesWith(I, A);
4784         }
4785         // Or commutes, try both ways.
4786         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4787             match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4788           // Add commutes, try both ways.
4789           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4790             return ReplaceInstUsesWith(I, B);
4791           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4792             return ReplaceInstUsesWith(I, B);
4793         }
4794       }
4795       V1 = 0; V2 = 0; V3 = 0;
4796     }
4797     
4798     // Check to see if we have any common things being and'ed.  If so, find the
4799     // terms for V1 & (V2|V3).
4800     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4801       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4802         V1 = A, V2 = C, V3 = D;
4803       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4804         V1 = A, V2 = B, V3 = C;
4805       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4806         V1 = C, V2 = A, V3 = D;
4807       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4808         V1 = C, V2 = A, V3 = B;
4809       
4810       if (V1) {
4811         Value *Or =
4812           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4813         return BinaryOperator::CreateAnd(V1, Or);
4814       }
4815     }
4816
4817     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4818     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4819       return Match;
4820     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4821       return Match;
4822     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4823       return Match;
4824     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4825       return Match;
4826
4827     // ((A&~B)|(~A&B)) -> A^B
4828     if ((match(C, m_Not(m_Specific(D)), *Context) &&
4829          match(B, m_Not(m_Specific(A)), *Context)))
4830       return BinaryOperator::CreateXor(A, D);
4831     // ((~B&A)|(~A&B)) -> A^B
4832     if ((match(A, m_Not(m_Specific(D)), *Context) &&
4833          match(B, m_Not(m_Specific(C)), *Context)))
4834       return BinaryOperator::CreateXor(C, D);
4835     // ((A&~B)|(B&~A)) -> A^B
4836     if ((match(C, m_Not(m_Specific(B)), *Context) &&
4837          match(D, m_Not(m_Specific(A)), *Context)))
4838       return BinaryOperator::CreateXor(A, B);
4839     // ((~B&A)|(B&~A)) -> A^B
4840     if ((match(A, m_Not(m_Specific(B)), *Context) &&
4841          match(D, m_Not(m_Specific(C)), *Context)))
4842       return BinaryOperator::CreateXor(C, B);
4843   }
4844   
4845   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4846   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4847     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4848       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4849           SI0->getOperand(1) == SI1->getOperand(1) &&
4850           (SI0->hasOneUse() || SI1->hasOneUse())) {
4851         Instruction *NewOp =
4852         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4853                                                      SI1->getOperand(0),
4854                                                      SI0->getName()), I);
4855         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4856                                       SI1->getOperand(1));
4857       }
4858   }
4859
4860   // ((A|B)&1)|(B&-2) -> (A&1) | B
4861   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4862       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4863     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4864     if (Ret) return Ret;
4865   }
4866   // (B&-2)|((A|B)&1) -> (A&1) | B
4867   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4868       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4869     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4870     if (Ret) return Ret;
4871   }
4872
4873   if (match(Op0, m_Not(m_Value(A)), *Context)) {   // ~A | Op1
4874     if (A == Op1)   // ~A | A == -1
4875       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4876   } else {
4877     A = 0;
4878   }
4879   // Note, A is still live here!
4880   if (match(Op1, m_Not(m_Value(B)), *Context)) {   // Op0 | ~B
4881     if (Op0 == B)
4882       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4883
4884     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4885     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4886       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4887                                               I.getName()+".demorgan"), I);
4888       return BinaryOperator::CreateNot(*Context, And);
4889     }
4890   }
4891
4892   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4893   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4894     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4895       return R;
4896
4897     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4898       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4899         return Res;
4900   }
4901     
4902   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4903   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4904     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4905       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4906         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4907             !isa<ICmpInst>(Op1C->getOperand(0))) {
4908           const Type *SrcTy = Op0C->getOperand(0)->getType();
4909           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4910               // Only do this if the casts both really cause code to be
4911               // generated.
4912               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4913                                 I.getType(), TD) &&
4914               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4915                                 I.getType(), TD)) {
4916             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4917                                                           Op1C->getOperand(0),
4918                                                           I.getName());
4919             InsertNewInstBefore(NewOp, I);
4920             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4921           }
4922         }
4923       }
4924   }
4925   
4926     
4927   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4928   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4929     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4930       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4931           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4932           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4933         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4934           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4935             // If either of the constants are nans, then the whole thing returns
4936             // true.
4937             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4938               return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4939             
4940             // Otherwise, no need to compare the two constants, compare the
4941             // rest.
4942             return new FCmpInst(*Context, FCmpInst::FCMP_UNO, 
4943                                 LHS->getOperand(0), RHS->getOperand(0));
4944           }
4945       } else {
4946         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4947         FCmpInst::Predicate Op0CC, Op1CC;
4948         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4949                   m_Value(Op0RHS)), *Context) &&
4950             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4951                   m_Value(Op1RHS)), *Context)) {
4952           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4953             // Swap RHS operands to match LHS.
4954             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4955             std::swap(Op1LHS, Op1RHS);
4956           }
4957           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4958             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4959             if (Op0CC == Op1CC)
4960               return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4961                                   Op0LHS, Op0RHS);
4962             else if (Op0CC == FCmpInst::FCMP_TRUE ||
4963                      Op1CC == FCmpInst::FCMP_TRUE)
4964               return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4965             else if (Op0CC == FCmpInst::FCMP_FALSE)
4966               return ReplaceInstUsesWith(I, Op1);
4967             else if (Op1CC == FCmpInst::FCMP_FALSE)
4968               return ReplaceInstUsesWith(I, Op0);
4969             bool Op0Ordered;
4970             bool Op1Ordered;
4971             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4972             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4973             if (Op0Ordered == Op1Ordered) {
4974               // If both are ordered or unordered, return a new fcmp with
4975               // or'ed predicates.
4976               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4977                                        Op0LHS, Op0RHS, Context);
4978               if (Instruction *I = dyn_cast<Instruction>(RV))
4979                 return I;
4980               // Otherwise, it's a constant boolean value...
4981               return ReplaceInstUsesWith(I, RV);
4982             }
4983           }
4984         }
4985       }
4986     }
4987   }
4988
4989   return Changed ? &I : 0;
4990 }
4991
4992 namespace {
4993
4994 // XorSelf - Implements: X ^ X --> 0
4995 struct XorSelf {
4996   Value *RHS;
4997   XorSelf(Value *rhs) : RHS(rhs) {}
4998   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4999   Instruction *apply(BinaryOperator &Xor) const {
5000     return &Xor;
5001   }
5002 };
5003
5004 }
5005
5006 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5007   bool Changed = SimplifyCommutative(I);
5008   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5009
5010   if (isa<UndefValue>(Op1)) {
5011     if (isa<UndefValue>(Op0))
5012       // Handle undef ^ undef -> 0 special case. This is a common
5013       // idiom (misuse).
5014       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5015     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5016   }
5017
5018   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5019   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
5020     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5021     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5022   }
5023   
5024   // See if we can simplify any instructions used by the instruction whose sole 
5025   // purpose is to compute bits we don't care about.
5026   if (SimplifyDemandedInstructionBits(I))
5027     return &I;
5028   if (isa<VectorType>(I.getType()))
5029     if (isa<ConstantAggregateZero>(Op1))
5030       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5031
5032   // Is this a ~ operation?
5033   if (Value *NotOp = dyn_castNotVal(&I, Context)) {
5034     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5035     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5036     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5037       if (Op0I->getOpcode() == Instruction::And || 
5038           Op0I->getOpcode() == Instruction::Or) {
5039         if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5040         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
5041           Instruction *NotY =
5042             BinaryOperator::CreateNot(*Context, Op0I->getOperand(1),
5043                                       Op0I->getOperand(1)->getName()+".not");
5044           InsertNewInstBefore(NotY, I);
5045           if (Op0I->getOpcode() == Instruction::And)
5046             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5047           else
5048             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5049         }
5050       }
5051     }
5052   }
5053   
5054   
5055   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5056     if (RHS == Context->getConstantIntTrue() && Op0->hasOneUse()) {
5057       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5058       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5059         return new ICmpInst(*Context, ICI->getInversePredicate(),
5060                             ICI->getOperand(0), ICI->getOperand(1));
5061
5062       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5063         return new FCmpInst(*Context, FCI->getInversePredicate(),
5064                             FCI->getOperand(0), FCI->getOperand(1));
5065     }
5066
5067     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5068     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5069       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5070         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5071           Instruction::CastOps Opcode = Op0C->getOpcode();
5072           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5073             if (RHS == Context->getConstantExprCast(Opcode, 
5074                                              Context->getConstantIntTrue(),
5075                                              Op0C->getDestTy())) {
5076               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5077                                      *Context,
5078                                      CI->getOpcode(), CI->getInversePredicate(),
5079                                      CI->getOperand(0), CI->getOperand(1)), I);
5080               NewCI->takeName(CI);
5081               return CastInst::Create(Opcode, NewCI, Op0C->getType());
5082             }
5083           }
5084         }
5085       }
5086     }
5087
5088     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5089       // ~(c-X) == X-c-1 == X+(-c-1)
5090       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5091         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5092           Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5093           Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
5094                                       Context->getConstantInt(I.getType(), 1));
5095           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5096         }
5097           
5098       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5099         if (Op0I->getOpcode() == Instruction::Add) {
5100           // ~(X-c) --> (-c-1)-X
5101           if (RHS->isAllOnesValue()) {
5102             Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
5103             return BinaryOperator::CreateSub(
5104                            Context->getConstantExprSub(NegOp0CI,
5105                                       Context->getConstantInt(I.getType(), 1)),
5106                                       Op0I->getOperand(0));
5107           } else if (RHS->getValue().isSignBit()) {
5108             // (X + C) ^ signbit -> (X + C + signbit)
5109             Constant *C =
5110                    Context->getConstantInt(RHS->getValue() + Op0CI->getValue());
5111             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5112
5113           }
5114         } else if (Op0I->getOpcode() == Instruction::Or) {
5115           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5116           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5117             Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
5118             // Anything in both C1 and C2 is known to be zero, remove it from
5119             // NewRHS.
5120             Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5121             NewRHS = Context->getConstantExprAnd(NewRHS, 
5122                                        Context->getConstantExprNot(CommonBits));
5123             AddToWorkList(Op0I);
5124             I.setOperand(0, Op0I->getOperand(0));
5125             I.setOperand(1, NewRHS);
5126             return &I;
5127           }
5128         }
5129       }
5130     }
5131
5132     // Try to fold constant and into select arguments.
5133     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5134       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5135         return R;
5136     if (isa<PHINode>(Op0))
5137       if (Instruction *NV = FoldOpIntoPhi(I))
5138         return NV;
5139   }
5140
5141   if (Value *X = dyn_castNotVal(Op0, Context))   // ~A ^ A == -1
5142     if (X == Op1)
5143       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5144
5145   if (Value *X = dyn_castNotVal(Op1, Context))   // A ^ ~A == -1
5146     if (X == Op0)
5147       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5148
5149   
5150   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5151   if (Op1I) {
5152     Value *A, *B;
5153     if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
5154       if (A == Op0) {              // B^(B|A) == (A|B)^B
5155         Op1I->swapOperands();
5156         I.swapOperands();
5157         std::swap(Op0, Op1);
5158       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5159         I.swapOperands();     // Simplified below.
5160         std::swap(Op0, Op1);
5161       }
5162     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
5163       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5164     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
5165       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5166     } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) && 
5167                Op1I->hasOneUse()){
5168       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5169         Op1I->swapOperands();
5170         std::swap(A, B);
5171       }
5172       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5173         I.swapOperands();     // Simplified below.
5174         std::swap(Op0, Op1);
5175       }
5176     }
5177   }
5178   
5179   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5180   if (Op0I) {
5181     Value *A, *B;
5182     if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5183         Op0I->hasOneUse()) {
5184       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5185         std::swap(A, B);
5186       if (B == Op1) {                                // (A|B)^B == A & ~B
5187         Instruction *NotB =
5188           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, 
5189                                                         Op1, "tmp"), I);
5190         return BinaryOperator::CreateAnd(A, NotB);
5191       }
5192     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
5193       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5194     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
5195       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5196     } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) && 
5197                Op0I->hasOneUse()){
5198       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5199         std::swap(A, B);
5200       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5201           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5202         Instruction *N =
5203           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, A, "tmp"), I);
5204         return BinaryOperator::CreateAnd(N, Op1);
5205       }
5206     }
5207   }
5208   
5209   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5210   if (Op0I && Op1I && Op0I->isShift() && 
5211       Op0I->getOpcode() == Op1I->getOpcode() && 
5212       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5213       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5214     Instruction *NewOp =
5215       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5216                                                     Op1I->getOperand(0),
5217                                                     Op0I->getName()), I);
5218     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5219                                   Op1I->getOperand(1));
5220   }
5221     
5222   if (Op0I && Op1I) {
5223     Value *A, *B, *C, *D;
5224     // (A & B)^(A | B) -> A ^ B
5225     if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5226         match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
5227       if ((A == C && B == D) || (A == D && B == C)) 
5228         return BinaryOperator::CreateXor(A, B);
5229     }
5230     // (A | B)^(A & B) -> A ^ B
5231     if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5232         match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5233       if ((A == C && B == D) || (A == D && B == C)) 
5234         return BinaryOperator::CreateXor(A, B);
5235     }
5236     
5237     // (A & B)^(C & D)
5238     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5239         match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5240         match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5241       // (X & Y)^(X & Y) -> (Y^Z) & X
5242       Value *X = 0, *Y = 0, *Z = 0;
5243       if (A == C)
5244         X = A, Y = B, Z = D;
5245       else if (A == D)
5246         X = A, Y = B, Z = C;
5247       else if (B == C)
5248         X = B, Y = A, Z = D;
5249       else if (B == D)
5250         X = B, Y = A, Z = C;
5251       
5252       if (X) {
5253         Instruction *NewOp =
5254         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5255         return BinaryOperator::CreateAnd(NewOp, X);
5256       }
5257     }
5258   }
5259     
5260   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5261   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5262     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
5263       return R;
5264
5265   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5266   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5267     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5268       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5269         const Type *SrcTy = Op0C->getOperand(0)->getType();
5270         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5271             // Only do this if the casts both really cause code to be generated.
5272             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5273                               I.getType(), TD) &&
5274             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5275                               I.getType(), TD)) {
5276           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5277                                                          Op1C->getOperand(0),
5278                                                          I.getName());
5279           InsertNewInstBefore(NewOp, I);
5280           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5281         }
5282       }
5283   }
5284
5285   return Changed ? &I : 0;
5286 }
5287
5288 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5289                                    LLVMContext *Context) {
5290   return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
5291 }
5292
5293 static bool HasAddOverflow(ConstantInt *Result,
5294                            ConstantInt *In1, ConstantInt *In2,
5295                            bool IsSigned) {
5296   if (IsSigned)
5297     if (In2->getValue().isNegative())
5298       return Result->getValue().sgt(In1->getValue());
5299     else
5300       return Result->getValue().slt(In1->getValue());
5301   else
5302     return Result->getValue().ult(In1->getValue());
5303 }
5304
5305 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5306 /// overflowed for this type.
5307 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5308                             Constant *In2, LLVMContext *Context,
5309                             bool IsSigned = false) {
5310   Result = Context->getConstantExprAdd(In1, In2);
5311
5312   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5313     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5314       Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5315       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5316                          ExtractElement(In1, Idx, Context),
5317                          ExtractElement(In2, Idx, Context),
5318                          IsSigned))
5319         return true;
5320     }
5321     return false;
5322   }
5323
5324   return HasAddOverflow(cast<ConstantInt>(Result),
5325                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5326                         IsSigned);
5327 }
5328
5329 static bool HasSubOverflow(ConstantInt *Result,
5330                            ConstantInt *In1, ConstantInt *In2,
5331                            bool IsSigned) {
5332   if (IsSigned)
5333     if (In2->getValue().isNegative())
5334       return Result->getValue().slt(In1->getValue());
5335     else
5336       return Result->getValue().sgt(In1->getValue());
5337   else
5338     return Result->getValue().ugt(In1->getValue());
5339 }
5340
5341 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5342 /// overflowed for this type.
5343 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5344                             Constant *In2, LLVMContext *Context,
5345                             bool IsSigned = false) {
5346   Result = Context->getConstantExprSub(In1, In2);
5347
5348   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5349     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5350       Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5351       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5352                          ExtractElement(In1, Idx, Context),
5353                          ExtractElement(In2, Idx, Context),
5354                          IsSigned))
5355         return true;
5356     }
5357     return false;
5358   }
5359
5360   return HasSubOverflow(cast<ConstantInt>(Result),
5361                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5362                         IsSigned);
5363 }
5364
5365 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5366 /// code necessary to compute the offset from the base pointer (without adding
5367 /// in the base pointer).  Return the result as a signed integer of intptr size.
5368 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5369   TargetData &TD = IC.getTargetData();
5370   gep_type_iterator GTI = gep_type_begin(GEP);
5371   const Type *IntPtrTy = TD.getIntPtrType();
5372   LLVMContext *Context = IC.getContext();
5373   Value *Result = Context->getNullValue(IntPtrTy);
5374
5375   // Build a mask for high order bits.
5376   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5377   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5378
5379   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5380        ++i, ++GTI) {
5381     Value *Op = *i;
5382     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5383     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5384       if (OpC->isZero()) continue;
5385       
5386       // Handle a struct index, which adds its field offset to the pointer.
5387       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5388         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5389         
5390         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5391           Result = 
5392              Context->getConstantInt(RC->getValue() + APInt(IntPtrWidth, Size));
5393         else
5394           Result = IC.InsertNewInstBefore(
5395                    BinaryOperator::CreateAdd(Result,
5396                                         Context->getConstantInt(IntPtrTy, Size),
5397                                              GEP->getName()+".offs"), I);
5398         continue;
5399       }
5400       
5401       Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5402       Constant *OC =
5403               Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5404       Scale = Context->getConstantExprMul(OC, Scale);
5405       if (Constant *RC = dyn_cast<Constant>(Result))
5406         Result = Context->getConstantExprAdd(RC, Scale);
5407       else {
5408         // Emit an add instruction.
5409         Result = IC.InsertNewInstBefore(
5410            BinaryOperator::CreateAdd(Result, Scale,
5411                                      GEP->getName()+".offs"), I);
5412       }
5413       continue;
5414     }
5415     // Convert to correct type.
5416     if (Op->getType() != IntPtrTy) {
5417       if (Constant *OpC = dyn_cast<Constant>(Op))
5418         Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
5419       else
5420         Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5421                                                                 true,
5422                                                       Op->getName()+".c"), I);
5423     }
5424     if (Size != 1) {
5425       Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5426       if (Constant *OpC = dyn_cast<Constant>(Op))
5427         Op = Context->getConstantExprMul(OpC, Scale);
5428       else    // We'll let instcombine(mul) convert this to a shl if possible.
5429         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5430                                                   GEP->getName()+".idx"), I);
5431     }
5432
5433     // Emit an add instruction.
5434     if (isa<Constant>(Op) && isa<Constant>(Result))
5435       Result = Context->getConstantExprAdd(cast<Constant>(Op),
5436                                     cast<Constant>(Result));
5437     else
5438       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5439                                                   GEP->getName()+".offs"), I);
5440   }
5441   return Result;
5442 }
5443
5444
5445 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5446 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
5447 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
5448 /// be complex, and scales are involved.  The above expression would also be
5449 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5450 /// This later form is less amenable to optimization though, and we are allowed
5451 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5452 ///
5453 /// If we can't emit an optimized form for this expression, this returns null.
5454 /// 
5455 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5456                                           InstCombiner &IC) {
5457   TargetData &TD = IC.getTargetData();
5458   gep_type_iterator GTI = gep_type_begin(GEP);
5459
5460   // Check to see if this gep only has a single variable index.  If so, and if
5461   // any constant indices are a multiple of its scale, then we can compute this
5462   // in terms of the scale of the variable index.  For example, if the GEP
5463   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5464   // because the expression will cross zero at the same point.
5465   unsigned i, e = GEP->getNumOperands();
5466   int64_t Offset = 0;
5467   for (i = 1; i != e; ++i, ++GTI) {
5468     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5469       // Compute the aggregate offset of constant indices.
5470       if (CI->isZero()) continue;
5471
5472       // Handle a struct index, which adds its field offset to the pointer.
5473       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5474         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5475       } else {
5476         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5477         Offset += Size*CI->getSExtValue();
5478       }
5479     } else {
5480       // Found our variable index.
5481       break;
5482     }
5483   }
5484   
5485   // If there are no variable indices, we must have a constant offset, just
5486   // evaluate it the general way.
5487   if (i == e) return 0;
5488   
5489   Value *VariableIdx = GEP->getOperand(i);
5490   // Determine the scale factor of the variable element.  For example, this is
5491   // 4 if the variable index is into an array of i32.
5492   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5493   
5494   // Verify that there are no other variable indices.  If so, emit the hard way.
5495   for (++i, ++GTI; i != e; ++i, ++GTI) {
5496     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5497     if (!CI) return 0;
5498    
5499     // Compute the aggregate offset of constant indices.
5500     if (CI->isZero()) continue;
5501     
5502     // Handle a struct index, which adds its field offset to the pointer.
5503     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5504       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5505     } else {
5506       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5507       Offset += Size*CI->getSExtValue();
5508     }
5509   }
5510   
5511   // Okay, we know we have a single variable index, which must be a
5512   // pointer/array/vector index.  If there is no offset, life is simple, return
5513   // the index.
5514   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5515   if (Offset == 0) {
5516     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5517     // we don't need to bother extending: the extension won't affect where the
5518     // computation crosses zero.
5519     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5520       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5521                                   VariableIdx->getNameStart(), &I);
5522     return VariableIdx;
5523   }
5524   
5525   // Otherwise, there is an index.  The computation we will do will be modulo
5526   // the pointer size, so get it.
5527   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5528   
5529   Offset &= PtrSizeMask;
5530   VariableScale &= PtrSizeMask;
5531
5532   // To do this transformation, any constant index must be a multiple of the
5533   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5534   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5535   // multiple of the variable scale.
5536   int64_t NewOffs = Offset / (int64_t)VariableScale;
5537   if (Offset != NewOffs*(int64_t)VariableScale)
5538     return 0;
5539
5540   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5541   const Type *IntPtrTy = TD.getIntPtrType();
5542   if (VariableIdx->getType() != IntPtrTy)
5543     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5544                                               true /*SExt*/, 
5545                                               VariableIdx->getNameStart(), &I);
5546   Constant *OffsetVal = IC.getContext()->getConstantInt(IntPtrTy, NewOffs);
5547   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5548 }
5549
5550
5551 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5552 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5553 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5554                                        ICmpInst::Predicate Cond,
5555                                        Instruction &I) {
5556   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5557
5558   // Look through bitcasts.
5559   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5560     RHS = BCI->getOperand(0);
5561
5562   Value *PtrBase = GEPLHS->getOperand(0);
5563   if (PtrBase == RHS) {
5564     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5565     // This transformation (ignoring the base and scales) is valid because we
5566     // know pointers can't overflow.  See if we can output an optimized form.
5567     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5568     
5569     // If not, synthesize the offset the hard way.
5570     if (Offset == 0)
5571       Offset = EmitGEPOffset(GEPLHS, I, *this);
5572     return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
5573                         Context->getNullValue(Offset->getType()));
5574   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5575     // If the base pointers are different, but the indices are the same, just
5576     // compare the base pointer.
5577     if (PtrBase != GEPRHS->getOperand(0)) {
5578       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5579       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5580                         GEPRHS->getOperand(0)->getType();
5581       if (IndicesTheSame)
5582         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5583           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5584             IndicesTheSame = false;
5585             break;
5586           }
5587
5588       // If all indices are the same, just compare the base pointers.
5589       if (IndicesTheSame)
5590         return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), 
5591                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5592
5593       // Otherwise, the base pointers are different and the indices are
5594       // different, bail out.
5595       return 0;
5596     }
5597
5598     // If one of the GEPs has all zero indices, recurse.
5599     bool AllZeros = true;
5600     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5601       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5602           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5603         AllZeros = false;
5604         break;
5605       }
5606     if (AllZeros)
5607       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5608                           ICmpInst::getSwappedPredicate(Cond), I);
5609
5610     // If the other GEP has all zero indices, recurse.
5611     AllZeros = true;
5612     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5613       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5614           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5615         AllZeros = false;
5616         break;
5617       }
5618     if (AllZeros)
5619       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5620
5621     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5622       // If the GEPs only differ by one index, compare it.
5623       unsigned NumDifferences = 0;  // Keep track of # differences.
5624       unsigned DiffOperand = 0;     // The operand that differs.
5625       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5626         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5627           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5628                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5629             // Irreconcilable differences.
5630             NumDifferences = 2;
5631             break;
5632           } else {
5633             if (NumDifferences++) break;
5634             DiffOperand = i;
5635           }
5636         }
5637
5638       if (NumDifferences == 0)   // SAME GEP?
5639         return ReplaceInstUsesWith(I, // No comparison is needed here.
5640                                    Context->getConstantInt(Type::Int1Ty,
5641                                              ICmpInst::isTrueWhenEqual(Cond)));
5642
5643       else if (NumDifferences == 1) {
5644         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5645         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5646         // Make sure we do a signed comparison here.
5647         return new ICmpInst(*Context,
5648                             ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5649       }
5650     }
5651
5652     // Only lower this if the icmp is the only user of the GEP or if we expect
5653     // the result to fold to a constant!
5654     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5655         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5656       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5657       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5658       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5659       return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
5660     }
5661   }
5662   return 0;
5663 }
5664
5665 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5666 ///
5667 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5668                                                 Instruction *LHSI,
5669                                                 Constant *RHSC) {
5670   if (!isa<ConstantFP>(RHSC)) return 0;
5671   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5672   
5673   // Get the width of the mantissa.  We don't want to hack on conversions that
5674   // might lose information from the integer, e.g. "i64 -> float"
5675   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5676   if (MantissaWidth == -1) return 0;  // Unknown.
5677   
5678   // Check to see that the input is converted from an integer type that is small
5679   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5680   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5681   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5682   
5683   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5684   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5685   if (LHSUnsigned)
5686     ++InputSize;
5687   
5688   // If the conversion would lose info, don't hack on this.
5689   if ((int)InputSize > MantissaWidth)
5690     return 0;
5691   
5692   // Otherwise, we can potentially simplify the comparison.  We know that it
5693   // will always come through as an integer value and we know the constant is
5694   // not a NAN (it would have been previously simplified).
5695   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5696   
5697   ICmpInst::Predicate Pred;
5698   switch (I.getPredicate()) {
5699   default: llvm_unreachable("Unexpected predicate!");
5700   case FCmpInst::FCMP_UEQ:
5701   case FCmpInst::FCMP_OEQ:
5702     Pred = ICmpInst::ICMP_EQ;
5703     break;
5704   case FCmpInst::FCMP_UGT:
5705   case FCmpInst::FCMP_OGT:
5706     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5707     break;
5708   case FCmpInst::FCMP_UGE:
5709   case FCmpInst::FCMP_OGE:
5710     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5711     break;
5712   case FCmpInst::FCMP_ULT:
5713   case FCmpInst::FCMP_OLT:
5714     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5715     break;
5716   case FCmpInst::FCMP_ULE:
5717   case FCmpInst::FCMP_OLE:
5718     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5719     break;
5720   case FCmpInst::FCMP_UNE:
5721   case FCmpInst::FCMP_ONE:
5722     Pred = ICmpInst::ICMP_NE;
5723     break;
5724   case FCmpInst::FCMP_ORD:
5725     return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5726   case FCmpInst::FCMP_UNO:
5727     return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5728   }
5729   
5730   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5731   
5732   // Now we know that the APFloat is a normal number, zero or inf.
5733   
5734   // See if the FP constant is too large for the integer.  For example,
5735   // comparing an i8 to 300.0.
5736   unsigned IntWidth = IntTy->getScalarSizeInBits();
5737   
5738   if (!LHSUnsigned) {
5739     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5740     // and large values.
5741     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5742     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5743                           APFloat::rmNearestTiesToEven);
5744     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5745       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5746           Pred == ICmpInst::ICMP_SLE)
5747         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5748       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5749     }
5750   } else {
5751     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5752     // +INF and large values.
5753     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5754     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5755                           APFloat::rmNearestTiesToEven);
5756     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5757       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5758           Pred == ICmpInst::ICMP_ULE)
5759         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5760       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5761     }
5762   }
5763   
5764   if (!LHSUnsigned) {
5765     // See if the RHS value is < SignedMin.
5766     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5767     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5768                           APFloat::rmNearestTiesToEven);
5769     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5770       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5771           Pred == ICmpInst::ICMP_SGE)
5772         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5773       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5774     }
5775   }
5776
5777   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5778   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5779   // casting the FP value to the integer value and back, checking for equality.
5780   // Don't do this for zero, because -0.0 is not fractional.
5781   Constant *RHSInt = LHSUnsigned
5782     ? Context->getConstantExprFPToUI(RHSC, IntTy)
5783     : Context->getConstantExprFPToSI(RHSC, IntTy);
5784   if (!RHS.isZero()) {
5785     bool Equal = LHSUnsigned
5786       ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5787       : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
5788     if (!Equal) {
5789       // If we had a comparison against a fractional value, we have to adjust
5790       // the compare predicate and sometimes the value.  RHSC is rounded towards
5791       // zero at this point.
5792       switch (Pred) {
5793       default: llvm_unreachable("Unexpected integer comparison!");
5794       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5795         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5796       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5797         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5798       case ICmpInst::ICMP_ULE:
5799         // (float)int <= 4.4   --> int <= 4
5800         // (float)int <= -4.4  --> false
5801         if (RHS.isNegative())
5802           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5803         break;
5804       case ICmpInst::ICMP_SLE:
5805         // (float)int <= 4.4   --> int <= 4
5806         // (float)int <= -4.4  --> int < -4
5807         if (RHS.isNegative())
5808           Pred = ICmpInst::ICMP_SLT;
5809         break;
5810       case ICmpInst::ICMP_ULT:
5811         // (float)int < -4.4   --> false
5812         // (float)int < 4.4    --> int <= 4
5813         if (RHS.isNegative())
5814           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5815         Pred = ICmpInst::ICMP_ULE;
5816         break;
5817       case ICmpInst::ICMP_SLT:
5818         // (float)int < -4.4   --> int < -4
5819         // (float)int < 4.4    --> int <= 4
5820         if (!RHS.isNegative())
5821           Pred = ICmpInst::ICMP_SLE;
5822         break;
5823       case ICmpInst::ICMP_UGT:
5824         // (float)int > 4.4    --> int > 4
5825         // (float)int > -4.4   --> true
5826         if (RHS.isNegative())
5827           return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5828         break;
5829       case ICmpInst::ICMP_SGT:
5830         // (float)int > 4.4    --> int > 4
5831         // (float)int > -4.4   --> int >= -4
5832         if (RHS.isNegative())
5833           Pred = ICmpInst::ICMP_SGE;
5834         break;
5835       case ICmpInst::ICMP_UGE:
5836         // (float)int >= -4.4   --> true
5837         // (float)int >= 4.4    --> int > 4
5838         if (!RHS.isNegative())
5839           return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5840         Pred = ICmpInst::ICMP_UGT;
5841         break;
5842       case ICmpInst::ICMP_SGE:
5843         // (float)int >= -4.4   --> int >= -4
5844         // (float)int >= 4.4    --> int > 4
5845         if (!RHS.isNegative())
5846           Pred = ICmpInst::ICMP_SGT;
5847         break;
5848       }
5849     }
5850   }
5851
5852   // Lower this FP comparison into an appropriate integer version of the
5853   // comparison.
5854   return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
5855 }
5856
5857 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5858   bool Changed = SimplifyCompare(I);
5859   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5860
5861   // Fold trivial predicates.
5862   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5863     return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5864   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5865     return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5866   
5867   // Simplify 'fcmp pred X, X'
5868   if (Op0 == Op1) {
5869     switch (I.getPredicate()) {
5870     default: llvm_unreachable("Unknown predicate!");
5871     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5872     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5873     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5874       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5875     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5876     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5877     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5878       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5879       
5880     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5881     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5882     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5883     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5884       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5885       I.setPredicate(FCmpInst::FCMP_UNO);
5886       I.setOperand(1, Context->getNullValue(Op0->getType()));
5887       return &I;
5888       
5889     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5890     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5891     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5892     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5893       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5894       I.setPredicate(FCmpInst::FCMP_ORD);
5895       I.setOperand(1, Context->getNullValue(Op0->getType()));
5896       return &I;
5897     }
5898   }
5899     
5900   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5901     return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5902
5903   // Handle fcmp with constant RHS
5904   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5905     // If the constant is a nan, see if we can fold the comparison based on it.
5906     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5907       if (CFP->getValueAPF().isNaN()) {
5908         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5909           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5910         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5911                "Comparison must be either ordered or unordered!");
5912         // True if unordered.
5913         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5914       }
5915     }
5916     
5917     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5918       switch (LHSI->getOpcode()) {
5919       case Instruction::PHI:
5920         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5921         // block.  If in the same block, we're encouraging jump threading.  If
5922         // not, we are just pessimizing the code by making an i1 phi.
5923         if (LHSI->getParent() == I.getParent())
5924           if (Instruction *NV = FoldOpIntoPhi(I))
5925             return NV;
5926         break;
5927       case Instruction::SIToFP:
5928       case Instruction::UIToFP:
5929         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5930           return NV;
5931         break;
5932       case Instruction::Select:
5933         // If either operand of the select is a constant, we can fold the
5934         // comparison into the select arms, which will cause one to be
5935         // constant folded and the select turned into a bitwise or.
5936         Value *Op1 = 0, *Op2 = 0;
5937         if (LHSI->hasOneUse()) {
5938           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5939             // Fold the known value into the constant operand.
5940             Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5941             // Insert a new FCmp of the other select operand.
5942             Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5943                                                       LHSI->getOperand(2), RHSC,
5944                                                       I.getName()), I);
5945           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5946             // Fold the known value into the constant operand.
5947             Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5948             // Insert a new FCmp of the other select operand.
5949             Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5950                                                       LHSI->getOperand(1), RHSC,
5951                                                       I.getName()), I);
5952           }
5953         }
5954
5955         if (Op1)
5956           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5957         break;
5958       }
5959   }
5960
5961   return Changed ? &I : 0;
5962 }
5963
5964 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5965   bool Changed = SimplifyCompare(I);
5966   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5967   const Type *Ty = Op0->getType();
5968
5969   // icmp X, X
5970   if (Op0 == Op1)
5971     return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty, 
5972                                                    I.isTrueWhenEqual()));
5973
5974   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5975     return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5976   
5977   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5978   // addresses never equal each other!  We already know that Op0 != Op1.
5979   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5980        isa<ConstantPointerNull>(Op0)) &&
5981       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5982        isa<ConstantPointerNull>(Op1)))
5983     return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty, 
5984                                                    !I.isTrueWhenEqual()));
5985
5986   // icmp's with boolean values can always be turned into bitwise operations
5987   if (Ty == Type::Int1Ty) {
5988     switch (I.getPredicate()) {
5989     default: llvm_unreachable("Invalid icmp instruction!");
5990     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5991       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5992       InsertNewInstBefore(Xor, I);
5993       return BinaryOperator::CreateNot(*Context, Xor);
5994     }
5995     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5996       return BinaryOperator::CreateXor(Op0, Op1);
5997
5998     case ICmpInst::ICMP_UGT:
5999       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
6000       // FALL THROUGH
6001     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
6002       Instruction *Not = BinaryOperator::CreateNot(*Context,
6003                                                    Op0, I.getName()+"tmp");
6004       InsertNewInstBefore(Not, I);
6005       return BinaryOperator::CreateAnd(Not, Op1);
6006     }
6007     case ICmpInst::ICMP_SGT:
6008       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
6009       // FALL THROUGH
6010     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
6011       Instruction *Not = BinaryOperator::CreateNot(*Context, 
6012                                                    Op1, I.getName()+"tmp");
6013       InsertNewInstBefore(Not, I);
6014       return BinaryOperator::CreateAnd(Not, Op0);
6015     }
6016     case ICmpInst::ICMP_UGE:
6017       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6018       // FALL THROUGH
6019     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6020       Instruction *Not = BinaryOperator::CreateNot(*Context,
6021                                                    Op0, I.getName()+"tmp");
6022       InsertNewInstBefore(Not, I);
6023       return BinaryOperator::CreateOr(Not, Op1);
6024     }
6025     case ICmpInst::ICMP_SGE:
6026       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6027       // FALL THROUGH
6028     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6029       Instruction *Not = BinaryOperator::CreateNot(*Context,
6030                                                    Op1, I.getName()+"tmp");
6031       InsertNewInstBefore(Not, I);
6032       return BinaryOperator::CreateOr(Not, Op0);
6033     }
6034     }
6035   }
6036
6037   unsigned BitWidth = 0;
6038   if (TD)
6039     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6040   else if (Ty->isIntOrIntVector())
6041     BitWidth = Ty->getScalarSizeInBits();
6042
6043   bool isSignBit = false;
6044
6045   // See if we are doing a comparison with a constant.
6046   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6047     Value *A = 0, *B = 0;
6048     
6049     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6050     if (I.isEquality() && CI->isNullValue() &&
6051         match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
6052       // (icmp cond A B) if cond is equality
6053       return new ICmpInst(*Context, I.getPredicate(), A, B);
6054     }
6055     
6056     // If we have an icmp le or icmp ge instruction, turn it into the
6057     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6058     // them being folded in the code below.
6059     switch (I.getPredicate()) {
6060     default: break;
6061     case ICmpInst::ICMP_ULE:
6062       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
6063         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6064       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6065                           AddOne(CI, Context));
6066     case ICmpInst::ICMP_SLE:
6067       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
6068         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6069       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6070                           AddOne(CI, Context));
6071     case ICmpInst::ICMP_UGE:
6072       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
6073         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6074       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6075                           SubOne(CI, Context));
6076     case ICmpInst::ICMP_SGE:
6077       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
6078         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6079       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6080                           SubOne(CI, Context));
6081     }
6082     
6083     // If this comparison is a normal comparison, it demands all
6084     // bits, if it is a sign bit comparison, it only demands the sign bit.
6085     bool UnusedBit;
6086     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6087   }
6088
6089   // See if we can fold the comparison based on range information we can get
6090   // by checking whether bits are known to be zero or one in the input.
6091   if (BitWidth != 0) {
6092     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6093     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6094
6095     if (SimplifyDemandedBits(I.getOperandUse(0),
6096                              isSignBit ? APInt::getSignBit(BitWidth)
6097                                        : APInt::getAllOnesValue(BitWidth),
6098                              Op0KnownZero, Op0KnownOne, 0))
6099       return &I;
6100     if (SimplifyDemandedBits(I.getOperandUse(1),
6101                              APInt::getAllOnesValue(BitWidth),
6102                              Op1KnownZero, Op1KnownOne, 0))
6103       return &I;
6104
6105     // Given the known and unknown bits, compute a range that the LHS could be
6106     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6107     // EQ and NE we use unsigned values.
6108     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6109     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6110     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6111       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6112                                              Op0Min, Op0Max);
6113       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6114                                              Op1Min, Op1Max);
6115     } else {
6116       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6117                                                Op0Min, Op0Max);
6118       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6119                                                Op1Min, Op1Max);
6120     }
6121
6122     // If Min and Max are known to be the same, then SimplifyDemandedBits
6123     // figured out that the LHS is a constant.  Just constant fold this now so
6124     // that code below can assume that Min != Max.
6125     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6126       return new ICmpInst(*Context, I.getPredicate(),
6127                           Context->getConstantInt(Op0Min), Op1);
6128     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6129       return new ICmpInst(*Context, I.getPredicate(), Op0, 
6130                           Context->getConstantInt(Op1Min));
6131
6132     // Based on the range information we know about the LHS, see if we can
6133     // simplify this comparison.  For example, (x&4) < 8  is always true.
6134     switch (I.getPredicate()) {
6135     default: llvm_unreachable("Unknown icmp opcode!");
6136     case ICmpInst::ICMP_EQ:
6137       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6138         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6139       break;
6140     case ICmpInst::ICMP_NE:
6141       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6142         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6143       break;
6144     case ICmpInst::ICMP_ULT:
6145       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6146         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6147       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6148         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6149       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6150         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6151       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6152         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6153           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6154                               SubOne(CI, Context));
6155
6156         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6157         if (CI->isMinValue(true))
6158           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6159                            Context->getAllOnesValue(Op0->getType()));
6160       }
6161       break;
6162     case ICmpInst::ICMP_UGT:
6163       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6164         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6165       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6166         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6167
6168       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6169         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6170       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6171         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6172           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6173                               AddOne(CI, Context));
6174
6175         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6176         if (CI->isMaxValue(true))
6177           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6178                               Context->getNullValue(Op0->getType()));
6179       }
6180       break;
6181     case ICmpInst::ICMP_SLT:
6182       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6183         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6184       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6185         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6186       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6187         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6188       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6189         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6190           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6191                               SubOne(CI, Context));
6192       }
6193       break;
6194     case ICmpInst::ICMP_SGT:
6195       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6196         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6197       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6198         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6199
6200       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6201         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6202       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6203         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6204           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6205                               AddOne(CI, Context));
6206       }
6207       break;
6208     case ICmpInst::ICMP_SGE:
6209       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6210       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6211         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6212       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6213         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6214       break;
6215     case ICmpInst::ICMP_SLE:
6216       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6217       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6218         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6219       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6220         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6221       break;
6222     case ICmpInst::ICMP_UGE:
6223       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6224       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6225         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6226       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6227         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6228       break;
6229     case ICmpInst::ICMP_ULE:
6230       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6231       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6232         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6233       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6234         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6235       break;
6236     }
6237
6238     // Turn a signed comparison into an unsigned one if both operands
6239     // are known to have the same sign.
6240     if (I.isSignedPredicate() &&
6241         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6242          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6243       return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
6244   }
6245
6246   // Test if the ICmpInst instruction is used exclusively by a select as
6247   // part of a minimum or maximum operation. If so, refrain from doing
6248   // any other folding. This helps out other analyses which understand
6249   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6250   // and CodeGen. And in this case, at least one of the comparison
6251   // operands has at least one user besides the compare (the select),
6252   // which would often largely negate the benefit of folding anyway.
6253   if (I.hasOneUse())
6254     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6255       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6256           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6257         return 0;
6258
6259   // See if we are doing a comparison between a constant and an instruction that
6260   // can be folded into the comparison.
6261   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6262     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6263     // instruction, see if that instruction also has constants so that the 
6264     // instruction can be folded into the icmp 
6265     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6266       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6267         return Res;
6268   }
6269
6270   // Handle icmp with constant (but not simple integer constant) RHS
6271   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6272     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6273       switch (LHSI->getOpcode()) {
6274       case Instruction::GetElementPtr:
6275         if (RHSC->isNullValue()) {
6276           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6277           bool isAllZeros = true;
6278           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6279             if (!isa<Constant>(LHSI->getOperand(i)) ||
6280                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6281               isAllZeros = false;
6282               break;
6283             }
6284           if (isAllZeros)
6285             return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
6286                     Context->getNullValue(LHSI->getOperand(0)->getType()));
6287         }
6288         break;
6289
6290       case Instruction::PHI:
6291         // Only fold icmp into the PHI if the phi and fcmp are in the same
6292         // block.  If in the same block, we're encouraging jump threading.  If
6293         // not, we are just pessimizing the code by making an i1 phi.
6294         if (LHSI->getParent() == I.getParent())
6295           if (Instruction *NV = FoldOpIntoPhi(I))
6296             return NV;
6297         break;
6298       case Instruction::Select: {
6299         // If either operand of the select is a constant, we can fold the
6300         // comparison into the select arms, which will cause one to be
6301         // constant folded and the select turned into a bitwise or.
6302         Value *Op1 = 0, *Op2 = 0;
6303         if (LHSI->hasOneUse()) {
6304           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6305             // Fold the known value into the constant operand.
6306             Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6307             // Insert a new ICmp of the other select operand.
6308             Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6309                                                    LHSI->getOperand(2), RHSC,
6310                                                    I.getName()), I);
6311           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6312             // Fold the known value into the constant operand.
6313             Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6314             // Insert a new ICmp of the other select operand.
6315             Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6316                                                    LHSI->getOperand(1), RHSC,
6317                                                    I.getName()), I);
6318           }
6319         }
6320
6321         if (Op1)
6322           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6323         break;
6324       }
6325       case Instruction::Malloc:
6326         // If we have (malloc != null), and if the malloc has a single use, we
6327         // can assume it is successful and remove the malloc.
6328         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6329           AddToWorkList(LHSI);
6330           return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
6331                                                          !I.isTrueWhenEqual()));
6332         }
6333         break;
6334       }
6335   }
6336
6337   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6338   if (User *GEP = dyn_castGetElementPtr(Op0))
6339     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6340       return NI;
6341   if (User *GEP = dyn_castGetElementPtr(Op1))
6342     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6343                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6344       return NI;
6345
6346   // Test to see if the operands of the icmp are casted versions of other
6347   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6348   // now.
6349   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6350     if (isa<PointerType>(Op0->getType()) && 
6351         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6352       // We keep moving the cast from the left operand over to the right
6353       // operand, where it can often be eliminated completely.
6354       Op0 = CI->getOperand(0);
6355
6356       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6357       // so eliminate it as well.
6358       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6359         Op1 = CI2->getOperand(0);
6360
6361       // If Op1 is a constant, we can fold the cast into the constant.
6362       if (Op0->getType() != Op1->getType()) {
6363         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6364           Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
6365         } else {
6366           // Otherwise, cast the RHS right before the icmp
6367           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6368         }
6369       }
6370       return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
6371     }
6372   }
6373   
6374   if (isa<CastInst>(Op0)) {
6375     // Handle the special case of: icmp (cast bool to X), <cst>
6376     // This comes up when you have code like
6377     //   int X = A < B;
6378     //   if (X) ...
6379     // For generality, we handle any zero-extension of any operand comparison
6380     // with a constant or another cast from the same type.
6381     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6382       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6383         return R;
6384   }
6385   
6386   // See if it's the same type of instruction on the left and right.
6387   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6388     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6389       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6390           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6391         switch (Op0I->getOpcode()) {
6392         default: break;
6393         case Instruction::Add:
6394         case Instruction::Sub:
6395         case Instruction::Xor:
6396           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6397             return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
6398                                 Op1I->getOperand(0));
6399           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6400           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6401             if (CI->getValue().isSignBit()) {
6402               ICmpInst::Predicate Pred = I.isSignedPredicate()
6403                                              ? I.getUnsignedPredicate()
6404                                              : I.getSignedPredicate();
6405               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6406                                   Op1I->getOperand(0));
6407             }
6408             
6409             if (CI->getValue().isMaxSignedValue()) {
6410               ICmpInst::Predicate Pred = I.isSignedPredicate()
6411                                              ? I.getUnsignedPredicate()
6412                                              : I.getSignedPredicate();
6413               Pred = I.getSwappedPredicate(Pred);
6414               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6415                                   Op1I->getOperand(0));
6416             }
6417           }
6418           break;
6419         case Instruction::Mul:
6420           if (!I.isEquality())
6421             break;
6422
6423           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6424             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6425             // Mask = -1 >> count-trailing-zeros(Cst).
6426             if (!CI->isZero() && !CI->isOne()) {
6427               const APInt &AP = CI->getValue();
6428               ConstantInt *Mask = Context->getConstantInt(
6429                                       APInt::getLowBitsSet(AP.getBitWidth(),
6430                                                            AP.getBitWidth() -
6431                                                       AP.countTrailingZeros()));
6432               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6433                                                             Mask);
6434               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6435                                                             Mask);
6436               InsertNewInstBefore(And1, I);
6437               InsertNewInstBefore(And2, I);
6438               return new ICmpInst(*Context, I.getPredicate(), And1, And2);
6439             }
6440           }
6441           break;
6442         }
6443       }
6444     }
6445   }
6446   
6447   // ~x < ~y --> y < x
6448   { Value *A, *B;
6449     if (match(Op0, m_Not(m_Value(A)), *Context) &&
6450         match(Op1, m_Not(m_Value(B)), *Context))
6451       return new ICmpInst(*Context, I.getPredicate(), B, A);
6452   }
6453   
6454   if (I.isEquality()) {
6455     Value *A, *B, *C, *D;
6456     
6457     // -x == -y --> x == y
6458     if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6459         match(Op1, m_Neg(m_Value(B)), *Context))
6460       return new ICmpInst(*Context, I.getPredicate(), A, B);
6461     
6462     if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
6463       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6464         Value *OtherVal = A == Op1 ? B : A;
6465         return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6466                             Context->getNullValue(A->getType()));
6467       }
6468
6469       if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
6470         // A^c1 == C^c2 --> A == C^(c1^c2)
6471         ConstantInt *C1, *C2;
6472         if (match(B, m_ConstantInt(C1), *Context) &&
6473             match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
6474           Constant *NC = 
6475                        Context->getConstantInt(C1->getValue() ^ C2->getValue());
6476           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6477           return new ICmpInst(*Context, I.getPredicate(), A,
6478                               InsertNewInstBefore(Xor, I));
6479         }
6480         
6481         // A^B == A^D -> B == D
6482         if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6483         if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6484         if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6485         if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
6486       }
6487     }
6488     
6489     if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
6490         (A == Op0 || B == Op0)) {
6491       // A == (A^B)  ->  B == 0
6492       Value *OtherVal = A == Op0 ? B : A;
6493       return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6494                           Context->getNullValue(A->getType()));
6495     }
6496
6497     // (A-B) == A  ->  B == 0
6498     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
6499       return new ICmpInst(*Context, I.getPredicate(), B, 
6500                           Context->getNullValue(B->getType()));
6501
6502     // A == (A-B)  ->  B == 0
6503     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
6504       return new ICmpInst(*Context, I.getPredicate(), B,
6505                           Context->getNullValue(B->getType()));
6506     
6507     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6508     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6509         match(Op0, m_And(m_Value(A), m_Value(B)), *Context) && 
6510         match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
6511       Value *X = 0, *Y = 0, *Z = 0;
6512       
6513       if (A == C) {
6514         X = B; Y = D; Z = A;
6515       } else if (A == D) {
6516         X = B; Y = C; Z = A;
6517       } else if (B == C) {
6518         X = A; Y = D; Z = B;
6519       } else if (B == D) {
6520         X = A; Y = C; Z = B;
6521       }
6522       
6523       if (X) {   // Build (X^Y) & Z
6524         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6525         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6526         I.setOperand(0, Op1);
6527         I.setOperand(1, Context->getNullValue(Op1->getType()));
6528         return &I;
6529       }
6530     }
6531   }
6532   return Changed ? &I : 0;
6533 }
6534
6535
6536 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6537 /// and CmpRHS are both known to be integer constants.
6538 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6539                                           ConstantInt *DivRHS) {
6540   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6541   const APInt &CmpRHSV = CmpRHS->getValue();
6542   
6543   // FIXME: If the operand types don't match the type of the divide 
6544   // then don't attempt this transform. The code below doesn't have the
6545   // logic to deal with a signed divide and an unsigned compare (and
6546   // vice versa). This is because (x /s C1) <s C2  produces different 
6547   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6548   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6549   // work. :(  The if statement below tests that condition and bails 
6550   // if it finds it. 
6551   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6552   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6553     return 0;
6554   if (DivRHS->isZero())
6555     return 0; // The ProdOV computation fails on divide by zero.
6556   if (DivIsSigned && DivRHS->isAllOnesValue())
6557     return 0; // The overflow computation also screws up here
6558   if (DivRHS->isOne())
6559     return 0; // Not worth bothering, and eliminates some funny cases
6560               // with INT_MIN.
6561
6562   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6563   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6564   // C2 (CI). By solving for X we can turn this into a range check 
6565   // instead of computing a divide. 
6566   Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
6567
6568   // Determine if the product overflows by seeing if the product is
6569   // not equal to the divide. Make sure we do the same kind of divide
6570   // as in the LHS instruction that we're folding. 
6571   bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6572                  Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
6573
6574   // Get the ICmp opcode
6575   ICmpInst::Predicate Pred = ICI.getPredicate();
6576
6577   // Figure out the interval that is being checked.  For example, a comparison
6578   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6579   // Compute this interval based on the constants involved and the signedness of
6580   // the compare/divide.  This computes a half-open interval, keeping track of
6581   // whether either value in the interval overflows.  After analysis each
6582   // overflow variable is set to 0 if it's corresponding bound variable is valid
6583   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6584   int LoOverflow = 0, HiOverflow = 0;
6585   Constant *LoBound = 0, *HiBound = 0;
6586   
6587   if (!DivIsSigned) {  // udiv
6588     // e.g. X/5 op 3  --> [15, 20)
6589     LoBound = Prod;
6590     HiOverflow = LoOverflow = ProdOV;
6591     if (!HiOverflow)
6592       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6593   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6594     if (CmpRHSV == 0) {       // (X / pos) op 0
6595       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6596       LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS, 
6597                                                                     Context)));
6598       HiBound = DivRHS;
6599     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6600       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6601       HiOverflow = LoOverflow = ProdOV;
6602       if (!HiOverflow)
6603         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6604     } else {                       // (X / pos) op neg
6605       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6606       HiBound = AddOne(Prod, Context);
6607       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6608       if (!LoOverflow) {
6609         ConstantInt* DivNeg =
6610                          cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6611         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6612                                      true) ? -1 : 0;
6613        }
6614     }
6615   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6616     if (CmpRHSV == 0) {       // (X / neg) op 0
6617       // e.g. X/-5 op 0  --> [-4, 5)
6618       LoBound = AddOne(DivRHS, Context);
6619       HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6620       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6621         HiOverflow = 1;            // [INTMIN+1, overflow)
6622         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6623       }
6624     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6625       // e.g. X/-5 op 3  --> [-19, -14)
6626       HiBound = AddOne(Prod, Context);
6627       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6628       if (!LoOverflow)
6629         LoOverflow = AddWithOverflow(LoBound, HiBound,
6630                                      DivRHS, Context, true) ? -1 : 0;
6631     } else {                       // (X / neg) op neg
6632       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6633       LoOverflow = HiOverflow = ProdOV;
6634       if (!HiOverflow)
6635         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6636     }
6637     
6638     // Dividing by a negative swaps the condition.  LT <-> GT
6639     Pred = ICmpInst::getSwappedPredicate(Pred);
6640   }
6641
6642   Value *X = DivI->getOperand(0);
6643   switch (Pred) {
6644   default: llvm_unreachable("Unhandled icmp opcode!");
6645   case ICmpInst::ICMP_EQ:
6646     if (LoOverflow && HiOverflow)
6647       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6648     else if (HiOverflow)
6649       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6650                           ICmpInst::ICMP_UGE, X, LoBound);
6651     else if (LoOverflow)
6652       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6653                           ICmpInst::ICMP_ULT, X, HiBound);
6654     else
6655       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6656   case ICmpInst::ICMP_NE:
6657     if (LoOverflow && HiOverflow)
6658       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6659     else if (HiOverflow)
6660       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6661                           ICmpInst::ICMP_ULT, X, LoBound);
6662     else if (LoOverflow)
6663       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6664                           ICmpInst::ICMP_UGE, X, HiBound);
6665     else
6666       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6667   case ICmpInst::ICMP_ULT:
6668   case ICmpInst::ICMP_SLT:
6669     if (LoOverflow == +1)   // Low bound is greater than input range.
6670       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6671     if (LoOverflow == -1)   // Low bound is less than input range.
6672       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6673     return new ICmpInst(*Context, Pred, X, LoBound);
6674   case ICmpInst::ICMP_UGT:
6675   case ICmpInst::ICMP_SGT:
6676     if (HiOverflow == +1)       // High bound greater than input range.
6677       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6678     else if (HiOverflow == -1)  // High bound less than input range.
6679       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6680     if (Pred == ICmpInst::ICMP_UGT)
6681       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
6682     else
6683       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
6684   }
6685 }
6686
6687
6688 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6689 ///
6690 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6691                                                           Instruction *LHSI,
6692                                                           ConstantInt *RHS) {
6693   const APInt &RHSV = RHS->getValue();
6694   
6695   switch (LHSI->getOpcode()) {
6696   case Instruction::Trunc:
6697     if (ICI.isEquality() && LHSI->hasOneUse()) {
6698       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6699       // of the high bits truncated out of x are known.
6700       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6701              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6702       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6703       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6704       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6705       
6706       // If all the high bits are known, we can do this xform.
6707       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6708         // Pull in the high bits from known-ones set.
6709         APInt NewRHS(RHS->getValue());
6710         NewRHS.zext(SrcBits);
6711         NewRHS |= KnownOne;
6712         return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
6713                             Context->getConstantInt(NewRHS));
6714       }
6715     }
6716     break;
6717       
6718   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6719     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6720       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6721       // fold the xor.
6722       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6723           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6724         Value *CompareVal = LHSI->getOperand(0);
6725         
6726         // If the sign bit of the XorCST is not set, there is no change to
6727         // the operation, just stop using the Xor.
6728         if (!XorCST->getValue().isNegative()) {
6729           ICI.setOperand(0, CompareVal);
6730           AddToWorkList(LHSI);
6731           return &ICI;
6732         }
6733         
6734         // Was the old condition true if the operand is positive?
6735         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6736         
6737         // If so, the new one isn't.
6738         isTrueIfPositive ^= true;
6739         
6740         if (isTrueIfPositive)
6741           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
6742                               SubOne(RHS, Context));
6743         else
6744           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
6745                               AddOne(RHS, Context));
6746       }
6747
6748       if (LHSI->hasOneUse()) {
6749         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6750         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6751           const APInt &SignBit = XorCST->getValue();
6752           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6753                                          ? ICI.getUnsignedPredicate()
6754                                          : ICI.getSignedPredicate();
6755           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6756                               Context->getConstantInt(RHSV ^ SignBit));
6757         }
6758
6759         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6760         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6761           const APInt &NotSignBit = XorCST->getValue();
6762           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6763                                          ? ICI.getUnsignedPredicate()
6764                                          : ICI.getSignedPredicate();
6765           Pred = ICI.getSwappedPredicate(Pred);
6766           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6767                               Context->getConstantInt(RHSV ^ NotSignBit));
6768         }
6769       }
6770     }
6771     break;
6772   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6773     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6774         LHSI->getOperand(0)->hasOneUse()) {
6775       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6776       
6777       // If the LHS is an AND of a truncating cast, we can widen the
6778       // and/compare to be the input width without changing the value
6779       // produced, eliminating a cast.
6780       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6781         // We can do this transformation if either the AND constant does not
6782         // have its sign bit set or if it is an equality comparison. 
6783         // Extending a relational comparison when we're checking the sign
6784         // bit would not work.
6785         if (Cast->hasOneUse() &&
6786             (ICI.isEquality() ||
6787              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6788           uint32_t BitWidth = 
6789             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6790           APInt NewCST = AndCST->getValue();
6791           NewCST.zext(BitWidth);
6792           APInt NewCI = RHSV;
6793           NewCI.zext(BitWidth);
6794           Instruction *NewAnd = 
6795             BinaryOperator::CreateAnd(Cast->getOperand(0),
6796                                Context->getConstantInt(NewCST),LHSI->getName());
6797           InsertNewInstBefore(NewAnd, ICI);
6798           return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
6799                               Context->getConstantInt(NewCI));
6800         }
6801       }
6802       
6803       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6804       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6805       // happens a LOT in code produced by the C front-end, for bitfield
6806       // access.
6807       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6808       if (Shift && !Shift->isShift())
6809         Shift = 0;
6810       
6811       ConstantInt *ShAmt;
6812       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6813       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6814       const Type *AndTy = AndCST->getType();          // Type of the and.
6815       
6816       // We can fold this as long as we can't shift unknown bits
6817       // into the mask.  This can only happen with signed shift
6818       // rights, as they sign-extend.
6819       if (ShAmt) {
6820         bool CanFold = Shift->isLogicalShift();
6821         if (!CanFold) {
6822           // To test for the bad case of the signed shr, see if any
6823           // of the bits shifted in could be tested after the mask.
6824           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6825           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6826           
6827           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6828           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6829                AndCST->getValue()) == 0)
6830             CanFold = true;
6831         }
6832         
6833         if (CanFold) {
6834           Constant *NewCst;
6835           if (Shift->getOpcode() == Instruction::Shl)
6836             NewCst = Context->getConstantExprLShr(RHS, ShAmt);
6837           else
6838             NewCst = Context->getConstantExprShl(RHS, ShAmt);
6839           
6840           // Check to see if we are shifting out any of the bits being
6841           // compared.
6842           if (Context->getConstantExpr(Shift->getOpcode(),
6843                                        NewCst, ShAmt) != RHS) {
6844             // If we shifted bits out, the fold is not going to work out.
6845             // As a special case, check to see if this means that the
6846             // result is always true or false now.
6847             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6848               return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6849             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6850               return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6851           } else {
6852             ICI.setOperand(1, NewCst);
6853             Constant *NewAndCST;
6854             if (Shift->getOpcode() == Instruction::Shl)
6855               NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
6856             else
6857               NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
6858             LHSI->setOperand(1, NewAndCST);
6859             LHSI->setOperand(0, Shift->getOperand(0));
6860             AddToWorkList(Shift); // Shift is dead.
6861             AddUsesToWorkList(ICI);
6862             return &ICI;
6863           }
6864         }
6865       }
6866       
6867       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6868       // preferable because it allows the C<<Y expression to be hoisted out
6869       // of a loop if Y is invariant and X is not.
6870       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6871           ICI.isEquality() && !Shift->isArithmeticShift() &&
6872           !isa<Constant>(Shift->getOperand(0))) {
6873         // Compute C << Y.
6874         Value *NS;
6875         if (Shift->getOpcode() == Instruction::LShr) {
6876           NS = BinaryOperator::CreateShl(AndCST, 
6877                                          Shift->getOperand(1), "tmp");
6878         } else {
6879           // Insert a logical shift.
6880           NS = BinaryOperator::CreateLShr(AndCST,
6881                                           Shift->getOperand(1), "tmp");
6882         }
6883         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6884         
6885         // Compute X & (C << Y).
6886         Instruction *NewAnd = 
6887           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6888         InsertNewInstBefore(NewAnd, ICI);
6889         
6890         ICI.setOperand(0, NewAnd);
6891         return &ICI;
6892       }
6893     }
6894     break;
6895     
6896   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6897     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6898     if (!ShAmt) break;
6899     
6900     uint32_t TypeBits = RHSV.getBitWidth();
6901     
6902     // Check that the shift amount is in range.  If not, don't perform
6903     // undefined shifts.  When the shift is visited it will be
6904     // simplified.
6905     if (ShAmt->uge(TypeBits))
6906       break;
6907     
6908     if (ICI.isEquality()) {
6909       // If we are comparing against bits always shifted out, the
6910       // comparison cannot succeed.
6911       Constant *Comp =
6912         Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6913                                                                  ShAmt);
6914       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6915         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6916         Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
6917         return ReplaceInstUsesWith(ICI, Cst);
6918       }
6919       
6920       if (LHSI->hasOneUse()) {
6921         // Otherwise strength reduce the shift into an and.
6922         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6923         Constant *Mask =
6924           Context->getConstantInt(APInt::getLowBitsSet(TypeBits, 
6925                                                        TypeBits-ShAmtVal));
6926         
6927         Instruction *AndI =
6928           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6929                                     Mask, LHSI->getName()+".mask");
6930         Value *And = InsertNewInstBefore(AndI, ICI);
6931         return new ICmpInst(*Context, ICI.getPredicate(), And,
6932                             Context->getConstantInt(RHSV.lshr(ShAmtVal)));
6933       }
6934     }
6935     
6936     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6937     bool TrueIfSigned = false;
6938     if (LHSI->hasOneUse() &&
6939         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6940       // (X << 31) <s 0  --> (X&1) != 0
6941       Constant *Mask = Context->getConstantInt(APInt(TypeBits, 1) <<
6942                                            (TypeBits-ShAmt->getZExtValue()-1));
6943       Instruction *AndI =
6944         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6945                                   Mask, LHSI->getName()+".mask");
6946       Value *And = InsertNewInstBefore(AndI, ICI);
6947       
6948       return new ICmpInst(*Context,
6949                           TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6950                           And, Context->getNullValue(And->getType()));
6951     }
6952     break;
6953   }
6954     
6955   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6956   case Instruction::AShr: {
6957     // Only handle equality comparisons of shift-by-constant.
6958     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6959     if (!ShAmt || !ICI.isEquality()) break;
6960
6961     // Check that the shift amount is in range.  If not, don't perform
6962     // undefined shifts.  When the shift is visited it will be
6963     // simplified.
6964     uint32_t TypeBits = RHSV.getBitWidth();
6965     if (ShAmt->uge(TypeBits))
6966       break;
6967     
6968     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6969       
6970     // If we are comparing against bits always shifted out, the
6971     // comparison cannot succeed.
6972     APInt Comp = RHSV << ShAmtVal;
6973     if (LHSI->getOpcode() == Instruction::LShr)
6974       Comp = Comp.lshr(ShAmtVal);
6975     else
6976       Comp = Comp.ashr(ShAmtVal);
6977     
6978     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6979       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6980       Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
6981       return ReplaceInstUsesWith(ICI, Cst);
6982     }
6983     
6984     // Otherwise, check to see if the bits shifted out are known to be zero.
6985     // If so, we can compare against the unshifted value:
6986     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6987     if (LHSI->hasOneUse() &&
6988         MaskedValueIsZero(LHSI->getOperand(0), 
6989                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6990       return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
6991                           Context->getConstantExprShl(RHS, ShAmt));
6992     }
6993       
6994     if (LHSI->hasOneUse()) {
6995       // Otherwise strength reduce the shift into an and.
6996       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6997       Constant *Mask = Context->getConstantInt(Val);
6998       
6999       Instruction *AndI =
7000         BinaryOperator::CreateAnd(LHSI->getOperand(0),
7001                                   Mask, LHSI->getName()+".mask");
7002       Value *And = InsertNewInstBefore(AndI, ICI);
7003       return new ICmpInst(*Context, ICI.getPredicate(), And,
7004                           Context->getConstantExprShl(RHS, ShAmt));
7005     }
7006     break;
7007   }
7008     
7009   case Instruction::SDiv:
7010   case Instruction::UDiv:
7011     // Fold: icmp pred ([us]div X, C1), C2 -> range test
7012     // Fold this div into the comparison, producing a range check. 
7013     // Determine, based on the divide type, what the range is being 
7014     // checked.  If there is an overflow on the low or high side, remember 
7015     // it, otherwise compute the range [low, hi) bounding the new value.
7016     // See: InsertRangeTest above for the kinds of replacements possible.
7017     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7018       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7019                                           DivRHS))
7020         return R;
7021     break;
7022
7023   case Instruction::Add:
7024     // Fold: icmp pred (add, X, C1), C2
7025
7026     if (!ICI.isEquality()) {
7027       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7028       if (!LHSC) break;
7029       const APInt &LHSV = LHSC->getValue();
7030
7031       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7032                             .subtract(LHSV);
7033
7034       if (ICI.isSignedPredicate()) {
7035         if (CR.getLower().isSignBit()) {
7036           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7037                               Context->getConstantInt(CR.getUpper()));
7038         } else if (CR.getUpper().isSignBit()) {
7039           return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7040                               Context->getConstantInt(CR.getLower()));
7041         }
7042       } else {
7043         if (CR.getLower().isMinValue()) {
7044           return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7045                               Context->getConstantInt(CR.getUpper()));
7046         } else if (CR.getUpper().isMinValue()) {
7047           return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7048                               Context->getConstantInt(CR.getLower()));
7049         }
7050       }
7051     }
7052     break;
7053   }
7054   
7055   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7056   if (ICI.isEquality()) {
7057     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7058     
7059     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7060     // the second operand is a constant, simplify a bit.
7061     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7062       switch (BO->getOpcode()) {
7063       case Instruction::SRem:
7064         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7065         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7066           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7067           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7068             Instruction *NewRem =
7069               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
7070                                          BO->getName());
7071             InsertNewInstBefore(NewRem, ICI);
7072             return new ICmpInst(*Context, ICI.getPredicate(), NewRem, 
7073                                 Context->getNullValue(BO->getType()));
7074           }
7075         }
7076         break;
7077       case Instruction::Add:
7078         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7079         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7080           if (BO->hasOneUse())
7081             return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7082                                 Context->getConstantExprSub(RHS, BOp1C));
7083         } else if (RHSV == 0) {
7084           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7085           // efficiently invertible, or if the add has just this one use.
7086           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7087           
7088           if (Value *NegVal = dyn_castNegVal(BOp1, Context))
7089             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
7090           else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
7091             return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
7092           else if (BO->hasOneUse()) {
7093             Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
7094             InsertNewInstBefore(Neg, ICI);
7095             Neg->takeName(BO);
7096             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
7097           }
7098         }
7099         break;
7100       case Instruction::Xor:
7101         // For the xor case, we can xor two constants together, eliminating
7102         // the explicit xor.
7103         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7104           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0), 
7105                               Context->getConstantExprXor(RHS, BOC));
7106         
7107         // FALLTHROUGH
7108       case Instruction::Sub:
7109         // Replace (([sub|xor] A, B) != 0) with (A != B)
7110         if (RHSV == 0)
7111           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7112                               BO->getOperand(1));
7113         break;
7114         
7115       case Instruction::Or:
7116         // If bits are being or'd in that are not present in the constant we
7117         // are comparing against, then the comparison could never succeed!
7118         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7119           Constant *NotCI = Context->getConstantExprNot(RHS);
7120           if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7121             return ReplaceInstUsesWith(ICI,
7122                                        Context->getConstantInt(Type::Int1Ty, 
7123                                        isICMP_NE));
7124         }
7125         break;
7126         
7127       case Instruction::And:
7128         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7129           // If bits are being compared against that are and'd out, then the
7130           // comparison can never succeed!
7131           if ((RHSV & ~BOC->getValue()) != 0)
7132             return ReplaceInstUsesWith(ICI,
7133                                        Context->getConstantInt(Type::Int1Ty,
7134                                        isICMP_NE));
7135           
7136           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7137           if (RHS == BOC && RHSV.isPowerOf2())
7138             return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
7139                                 ICmpInst::ICMP_NE, LHSI,
7140                                 Context->getNullValue(RHS->getType()));
7141           
7142           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7143           if (BOC->getValue().isSignBit()) {
7144             Value *X = BO->getOperand(0);
7145             Constant *Zero = Context->getNullValue(X->getType());
7146             ICmpInst::Predicate pred = isICMP_NE ? 
7147               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7148             return new ICmpInst(*Context, pred, X, Zero);
7149           }
7150           
7151           // ((X & ~7) == 0) --> X < 8
7152           if (RHSV == 0 && isHighOnes(BOC)) {
7153             Value *X = BO->getOperand(0);
7154             Constant *NegX = Context->getConstantExprNeg(BOC);
7155             ICmpInst::Predicate pred = isICMP_NE ? 
7156               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7157             return new ICmpInst(*Context, pred, X, NegX);
7158           }
7159         }
7160       default: break;
7161       }
7162     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7163       // Handle icmp {eq|ne} <intrinsic>, intcst.
7164       if (II->getIntrinsicID() == Intrinsic::bswap) {
7165         AddToWorkList(II);
7166         ICI.setOperand(0, II->getOperand(1));
7167         ICI.setOperand(1, Context->getConstantInt(RHSV.byteSwap()));
7168         return &ICI;
7169       }
7170     }
7171   }
7172   return 0;
7173 }
7174
7175 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7176 /// We only handle extending casts so far.
7177 ///
7178 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7179   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7180   Value *LHSCIOp        = LHSCI->getOperand(0);
7181   const Type *SrcTy     = LHSCIOp->getType();
7182   const Type *DestTy    = LHSCI->getType();
7183   Value *RHSCIOp;
7184
7185   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7186   // integer type is the same size as the pointer type.
7187   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7188       getTargetData().getPointerSizeInBits() == 
7189          cast<IntegerType>(DestTy)->getBitWidth()) {
7190     Value *RHSOp = 0;
7191     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7192       RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
7193     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7194       RHSOp = RHSC->getOperand(0);
7195       // If the pointer types don't match, insert a bitcast.
7196       if (LHSCIOp->getType() != RHSOp->getType())
7197         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
7198     }
7199
7200     if (RHSOp)
7201       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
7202   }
7203   
7204   // The code below only handles extension cast instructions, so far.
7205   // Enforce this.
7206   if (LHSCI->getOpcode() != Instruction::ZExt &&
7207       LHSCI->getOpcode() != Instruction::SExt)
7208     return 0;
7209
7210   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7211   bool isSignedCmp = ICI.isSignedPredicate();
7212
7213   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7214     // Not an extension from the same type?
7215     RHSCIOp = CI->getOperand(0);
7216     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7217       return 0;
7218     
7219     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7220     // and the other is a zext), then we can't handle this.
7221     if (CI->getOpcode() != LHSCI->getOpcode())
7222       return 0;
7223
7224     // Deal with equality cases early.
7225     if (ICI.isEquality())
7226       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7227
7228     // A signed comparison of sign extended values simplifies into a
7229     // signed comparison.
7230     if (isSignedCmp && isSignedExt)
7231       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7232
7233     // The other three cases all fold into an unsigned comparison.
7234     return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7235   }
7236
7237   // If we aren't dealing with a constant on the RHS, exit early
7238   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7239   if (!CI)
7240     return 0;
7241
7242   // Compute the constant that would happen if we truncated to SrcTy then
7243   // reextended to DestTy.
7244   Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7245   Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7246                                                 Res1, DestTy);
7247
7248   // If the re-extended constant didn't change...
7249   if (Res2 == CI) {
7250     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7251     // For example, we might have:
7252     //    %A = sext i16 %X to i32
7253     //    %B = icmp ugt i32 %A, 1330
7254     // It is incorrect to transform this into 
7255     //    %B = icmp ugt i16 %X, 1330
7256     // because %A may have negative value. 
7257     //
7258     // However, we allow this when the compare is EQ/NE, because they are
7259     // signless.
7260     if (isSignedExt == isSignedCmp || ICI.isEquality())
7261       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
7262     return 0;
7263   }
7264
7265   // The re-extended constant changed so the constant cannot be represented 
7266   // in the shorter type. Consequently, we cannot emit a simple comparison.
7267
7268   // First, handle some easy cases. We know the result cannot be equal at this
7269   // point so handle the ICI.isEquality() cases
7270   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7271     return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
7272   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7273     return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
7274
7275   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7276   // should have been folded away previously and not enter in here.
7277   Value *Result;
7278   if (isSignedCmp) {
7279     // We're performing a signed comparison.
7280     if (cast<ConstantInt>(CI)->getValue().isNegative())
7281       Result = Context->getConstantIntFalse();          // X < (small) --> false
7282     else
7283       Result = Context->getConstantIntTrue();           // X < (large) --> true
7284   } else {
7285     // We're performing an unsigned comparison.
7286     if (isSignedExt) {
7287       // We're performing an unsigned comp with a sign extended value.
7288       // This is true if the input is >= 0. [aka >s -1]
7289       Constant *NegOne = Context->getAllOnesValue(SrcTy);
7290       Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT, 
7291                                    LHSCIOp, NegOne, ICI.getName()), ICI);
7292     } else {
7293       // Unsigned extend & unsigned compare -> always true.
7294       Result = Context->getConstantIntTrue();
7295     }
7296   }
7297
7298   // Finally, return the value computed.
7299   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7300       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7301     return ReplaceInstUsesWith(ICI, Result);
7302
7303   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7304           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7305          "ICmp should be folded!");
7306   if (Constant *CI = dyn_cast<Constant>(Result))
7307     return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
7308   return BinaryOperator::CreateNot(*Context, Result);
7309 }
7310
7311 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7312   return commonShiftTransforms(I);
7313 }
7314
7315 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7316   return commonShiftTransforms(I);
7317 }
7318
7319 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7320   if (Instruction *R = commonShiftTransforms(I))
7321     return R;
7322   
7323   Value *Op0 = I.getOperand(0);
7324   
7325   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7326   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7327     if (CSI->isAllOnesValue())
7328       return ReplaceInstUsesWith(I, CSI);
7329
7330   // See if we can turn a signed shr into an unsigned shr.
7331   if (MaskedValueIsZero(Op0,
7332                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7333     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7334
7335   // Arithmetic shifting an all-sign-bit value is a no-op.
7336   unsigned NumSignBits = ComputeNumSignBits(Op0);
7337   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7338     return ReplaceInstUsesWith(I, Op0);
7339
7340   return 0;
7341 }
7342
7343 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7344   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7345   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7346
7347   // shl X, 0 == X and shr X, 0 == X
7348   // shl 0, X == 0 and shr 0, X == 0
7349   if (Op1 == Context->getNullValue(Op1->getType()) ||
7350       Op0 == Context->getNullValue(Op0->getType()))
7351     return ReplaceInstUsesWith(I, Op0);
7352   
7353   if (isa<UndefValue>(Op0)) {            
7354     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7355       return ReplaceInstUsesWith(I, Op0);
7356     else                                    // undef << X -> 0, undef >>u X -> 0
7357       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7358   }
7359   if (isa<UndefValue>(Op1)) {
7360     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7361       return ReplaceInstUsesWith(I, Op0);          
7362     else                                     // X << undef, X >>u undef -> 0
7363       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7364   }
7365
7366   // See if we can fold away this shift.
7367   if (SimplifyDemandedInstructionBits(I))
7368     return &I;
7369
7370   // Try to fold constant and into select arguments.
7371   if (isa<Constant>(Op0))
7372     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7373       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7374         return R;
7375
7376   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7377     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7378       return Res;
7379   return 0;
7380 }
7381
7382 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7383                                                BinaryOperator &I) {
7384   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7385
7386   // See if we can simplify any instructions used by the instruction whose sole 
7387   // purpose is to compute bits we don't care about.
7388   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7389   
7390   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7391   // a signed shift.
7392   //
7393   if (Op1->uge(TypeBits)) {
7394     if (I.getOpcode() != Instruction::AShr)
7395       return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
7396     else {
7397       I.setOperand(1, Context->getConstantInt(I.getType(), TypeBits-1));
7398       return &I;
7399     }
7400   }
7401   
7402   // ((X*C1) << C2) == (X * (C1 << C2))
7403   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7404     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7405       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7406         return BinaryOperator::CreateMul(BO->getOperand(0),
7407                                         Context->getConstantExprShl(BOOp, Op1));
7408   
7409   // Try to fold constant and into select arguments.
7410   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7411     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7412       return R;
7413   if (isa<PHINode>(Op0))
7414     if (Instruction *NV = FoldOpIntoPhi(I))
7415       return NV;
7416   
7417   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7418   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7419     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7420     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7421     // place.  Don't try to do this transformation in this case.  Also, we
7422     // require that the input operand is a shift-by-constant so that we have
7423     // confidence that the shifts will get folded together.  We could do this
7424     // xform in more cases, but it is unlikely to be profitable.
7425     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7426         isa<ConstantInt>(TrOp->getOperand(1))) {
7427       // Okay, we'll do this xform.  Make the shift of shift.
7428       Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
7429       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7430                                                 I.getName());
7431       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7432
7433       // For logical shifts, the truncation has the effect of making the high
7434       // part of the register be zeros.  Emulate this by inserting an AND to
7435       // clear the top bits as needed.  This 'and' will usually be zapped by
7436       // other xforms later if dead.
7437       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7438       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7439       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7440       
7441       // The mask we constructed says what the trunc would do if occurring
7442       // between the shifts.  We want to know the effect *after* the second
7443       // shift.  We know that it is a logical shift by a constant, so adjust the
7444       // mask as appropriate.
7445       if (I.getOpcode() == Instruction::Shl)
7446         MaskV <<= Op1->getZExtValue();
7447       else {
7448         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7449         MaskV = MaskV.lshr(Op1->getZExtValue());
7450       }
7451
7452       Instruction *And =
7453         BinaryOperator::CreateAnd(NSh, Context->getConstantInt(MaskV), 
7454                                   TI->getName());
7455       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7456
7457       // Return the value truncated to the interesting size.
7458       return new TruncInst(And, I.getType());
7459     }
7460   }
7461   
7462   if (Op0->hasOneUse()) {
7463     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7464       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7465       Value *V1, *V2;
7466       ConstantInt *CC;
7467       switch (Op0BO->getOpcode()) {
7468         default: break;
7469         case Instruction::Add:
7470         case Instruction::And:
7471         case Instruction::Or:
7472         case Instruction::Xor: {
7473           // These operators commute.
7474           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7475           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7476               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7477                     m_Specific(Op1)), *Context)){
7478             Instruction *YS = BinaryOperator::CreateShl(
7479                                             Op0BO->getOperand(0), Op1,
7480                                             Op0BO->getName());
7481             InsertNewInstBefore(YS, I); // (Y << C)
7482             Instruction *X = 
7483               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7484                                      Op0BO->getOperand(1)->getName());
7485             InsertNewInstBefore(X, I);  // (X + (Y << C))
7486             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7487             return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7488                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7489           }
7490           
7491           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7492           Value *Op0BOOp1 = Op0BO->getOperand(1);
7493           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7494               match(Op0BOOp1, 
7495                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7496                           m_ConstantInt(CC)), *Context) &&
7497               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7498             Instruction *YS = BinaryOperator::CreateShl(
7499                                                      Op0BO->getOperand(0), Op1,
7500                                                      Op0BO->getName());
7501             InsertNewInstBefore(YS, I); // (Y << C)
7502             Instruction *XM =
7503               BinaryOperator::CreateAnd(V1,
7504                                         Context->getConstantExprShl(CC, Op1),
7505                                         V1->getName()+".mask");
7506             InsertNewInstBefore(XM, I); // X & (CC << C)
7507             
7508             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7509           }
7510         }
7511           
7512         // FALL THROUGH.
7513         case Instruction::Sub: {
7514           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7515           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7516               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7517                     m_Specific(Op1)), *Context)){
7518             Instruction *YS = BinaryOperator::CreateShl(
7519                                                      Op0BO->getOperand(1), Op1,
7520                                                      Op0BO->getName());
7521             InsertNewInstBefore(YS, I); // (Y << C)
7522             Instruction *X =
7523               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7524                                      Op0BO->getOperand(0)->getName());
7525             InsertNewInstBefore(X, I);  // (X + (Y << C))
7526             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7527             return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7528                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7529           }
7530           
7531           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7532           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7533               match(Op0BO->getOperand(0),
7534                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7535                           m_ConstantInt(CC)), *Context) && V2 == Op1 &&
7536               cast<BinaryOperator>(Op0BO->getOperand(0))
7537                   ->getOperand(0)->hasOneUse()) {
7538             Instruction *YS = BinaryOperator::CreateShl(
7539                                                      Op0BO->getOperand(1), Op1,
7540                                                      Op0BO->getName());
7541             InsertNewInstBefore(YS, I); // (Y << C)
7542             Instruction *XM =
7543               BinaryOperator::CreateAnd(V1, 
7544                                         Context->getConstantExprShl(CC, Op1),
7545                                         V1->getName()+".mask");
7546             InsertNewInstBefore(XM, I); // X & (CC << C)
7547             
7548             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7549           }
7550           
7551           break;
7552         }
7553       }
7554       
7555       
7556       // If the operand is an bitwise operator with a constant RHS, and the
7557       // shift is the only use, we can pull it out of the shift.
7558       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7559         bool isValid = true;     // Valid only for And, Or, Xor
7560         bool highBitSet = false; // Transform if high bit of constant set?
7561         
7562         switch (Op0BO->getOpcode()) {
7563           default: isValid = false; break;   // Do not perform transform!
7564           case Instruction::Add:
7565             isValid = isLeftShift;
7566             break;
7567           case Instruction::Or:
7568           case Instruction::Xor:
7569             highBitSet = false;
7570             break;
7571           case Instruction::And:
7572             highBitSet = true;
7573             break;
7574         }
7575         
7576         // If this is a signed shift right, and the high bit is modified
7577         // by the logical operation, do not perform the transformation.
7578         // The highBitSet boolean indicates the value of the high bit of
7579         // the constant which would cause it to be modified for this
7580         // operation.
7581         //
7582         if (isValid && I.getOpcode() == Instruction::AShr)
7583           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7584         
7585         if (isValid) {
7586           Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
7587           
7588           Instruction *NewShift =
7589             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7590           InsertNewInstBefore(NewShift, I);
7591           NewShift->takeName(Op0BO);
7592           
7593           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7594                                         NewRHS);
7595         }
7596       }
7597     }
7598   }
7599   
7600   // Find out if this is a shift of a shift by a constant.
7601   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7602   if (ShiftOp && !ShiftOp->isShift())
7603     ShiftOp = 0;
7604   
7605   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7606     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7607     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7608     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7609     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7610     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7611     Value *X = ShiftOp->getOperand(0);
7612     
7613     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7614     
7615     const IntegerType *Ty = cast<IntegerType>(I.getType());
7616     
7617     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7618     if (I.getOpcode() == ShiftOp->getOpcode()) {
7619       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7620       // saturates.
7621       if (AmtSum >= TypeBits) {
7622         if (I.getOpcode() != Instruction::AShr)
7623           return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7624         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7625       }
7626       
7627       return BinaryOperator::Create(I.getOpcode(), X,
7628                                     Context->getConstantInt(Ty, AmtSum));
7629     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7630                I.getOpcode() == Instruction::AShr) {
7631       if (AmtSum >= TypeBits)
7632         return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7633       
7634       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7635       return BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, AmtSum));
7636     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7637                I.getOpcode() == Instruction::LShr) {
7638       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7639       if (AmtSum >= TypeBits)
7640         AmtSum = TypeBits-1;
7641       
7642       Instruction *Shift =
7643         BinaryOperator::CreateAShr(X, Context->getConstantInt(Ty, AmtSum));
7644       InsertNewInstBefore(Shift, I);
7645
7646       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7647       return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7648     }
7649     
7650     // Okay, if we get here, one shift must be left, and the other shift must be
7651     // right.  See if the amounts are equal.
7652     if (ShiftAmt1 == ShiftAmt2) {
7653       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7654       if (I.getOpcode() == Instruction::Shl) {
7655         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7656         return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7657       }
7658       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7659       if (I.getOpcode() == Instruction::LShr) {
7660         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7661         return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7662       }
7663       // We can simplify ((X << C) >>s C) into a trunc + sext.
7664       // NOTE: we could do this for any C, but that would make 'unusual' integer
7665       // types.  For now, just stick to ones well-supported by the code
7666       // generators.
7667       const Type *SExtType = 0;
7668       switch (Ty->getBitWidth() - ShiftAmt1) {
7669       case 1  :
7670       case 8  :
7671       case 16 :
7672       case 32 :
7673       case 64 :
7674       case 128:
7675         SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
7676         break;
7677       default: break;
7678       }
7679       if (SExtType) {
7680         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7681         InsertNewInstBefore(NewTrunc, I);
7682         return new SExtInst(NewTrunc, Ty);
7683       }
7684       // Otherwise, we can't handle it yet.
7685     } else if (ShiftAmt1 < ShiftAmt2) {
7686       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7687       
7688       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7689       if (I.getOpcode() == Instruction::Shl) {
7690         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7691                ShiftOp->getOpcode() == Instruction::AShr);
7692         Instruction *Shift =
7693           BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7694         InsertNewInstBefore(Shift, I);
7695         
7696         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7697         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7698       }
7699       
7700       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7701       if (I.getOpcode() == Instruction::LShr) {
7702         assert(ShiftOp->getOpcode() == Instruction::Shl);
7703         Instruction *Shift =
7704           BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, ShiftDiff));
7705         InsertNewInstBefore(Shift, I);
7706         
7707         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7708         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7709       }
7710       
7711       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7712     } else {
7713       assert(ShiftAmt2 < ShiftAmt1);
7714       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7715
7716       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7717       if (I.getOpcode() == Instruction::Shl) {
7718         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7719                ShiftOp->getOpcode() == Instruction::AShr);
7720         Instruction *Shift =
7721           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7722                                  Context->getConstantInt(Ty, ShiftDiff));
7723         InsertNewInstBefore(Shift, I);
7724         
7725         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7726         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7727       }
7728       
7729       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7730       if (I.getOpcode() == Instruction::LShr) {
7731         assert(ShiftOp->getOpcode() == Instruction::Shl);
7732         Instruction *Shift =
7733           BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7734         InsertNewInstBefore(Shift, I);
7735         
7736         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7737         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7738       }
7739       
7740       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7741     }
7742   }
7743   return 0;
7744 }
7745
7746
7747 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7748 /// expression.  If so, decompose it, returning some value X, such that Val is
7749 /// X*Scale+Offset.
7750 ///
7751 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7752                                         int &Offset, LLVMContext *Context) {
7753   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7754   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7755     Offset = CI->getZExtValue();
7756     Scale  = 0;
7757     return Context->getConstantInt(Type::Int32Ty, 0);
7758   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7759     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7760       if (I->getOpcode() == Instruction::Shl) {
7761         // This is a value scaled by '1 << the shift amt'.
7762         Scale = 1U << RHS->getZExtValue();
7763         Offset = 0;
7764         return I->getOperand(0);
7765       } else if (I->getOpcode() == Instruction::Mul) {
7766         // This value is scaled by 'RHS'.
7767         Scale = RHS->getZExtValue();
7768         Offset = 0;
7769         return I->getOperand(0);
7770       } else if (I->getOpcode() == Instruction::Add) {
7771         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7772         // where C1 is divisible by C2.
7773         unsigned SubScale;
7774         Value *SubVal = 
7775           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7776                                     Offset, Context);
7777         Offset += RHS->getZExtValue();
7778         Scale = SubScale;
7779         return SubVal;
7780       }
7781     }
7782   }
7783
7784   // Otherwise, we can't look past this.
7785   Scale = 1;
7786   Offset = 0;
7787   return Val;
7788 }
7789
7790
7791 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7792 /// try to eliminate the cast by moving the type information into the alloc.
7793 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7794                                                    AllocationInst &AI) {
7795   const PointerType *PTy = cast<PointerType>(CI.getType());
7796   
7797   // Remove any uses of AI that are dead.
7798   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7799   
7800   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7801     Instruction *User = cast<Instruction>(*UI++);
7802     if (isInstructionTriviallyDead(User)) {
7803       while (UI != E && *UI == User)
7804         ++UI; // If this instruction uses AI more than once, don't break UI.
7805       
7806       ++NumDeadInst;
7807       DOUT << "IC: DCE: " << *User;
7808       EraseInstFromFunction(*User);
7809     }
7810   }
7811   
7812   // Get the type really allocated and the type casted to.
7813   const Type *AllocElTy = AI.getAllocatedType();
7814   const Type *CastElTy = PTy->getElementType();
7815   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7816
7817   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7818   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7819   if (CastElTyAlign < AllocElTyAlign) return 0;
7820
7821   // If the allocation has multiple uses, only promote it if we are strictly
7822   // increasing the alignment of the resultant allocation.  If we keep it the
7823   // same, we open the door to infinite loops of various kinds.  (A reference
7824   // from a dbg.declare doesn't count as a use for this purpose.)
7825   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7826       CastElTyAlign == AllocElTyAlign) return 0;
7827
7828   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7829   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7830   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7831
7832   // See if we can satisfy the modulus by pulling a scale out of the array
7833   // size argument.
7834   unsigned ArraySizeScale;
7835   int ArrayOffset;
7836   Value *NumElements = // See if the array size is a decomposable linear expr.
7837     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7838                               ArrayOffset, Context);
7839  
7840   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7841   // do the xform.
7842   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7843       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7844
7845   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7846   Value *Amt = 0;
7847   if (Scale == 1) {
7848     Amt = NumElements;
7849   } else {
7850     // If the allocation size is constant, form a constant mul expression
7851     Amt = Context->getConstantInt(Type::Int32Ty, Scale);
7852     if (isa<ConstantInt>(NumElements))
7853       Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
7854                                  cast<ConstantInt>(Amt));
7855     // otherwise multiply the amount and the number of elements
7856     else {
7857       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7858       Amt = InsertNewInstBefore(Tmp, AI);
7859     }
7860   }
7861   
7862   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7863     Value *Off = Context->getConstantInt(Type::Int32Ty, Offset, true);
7864     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7865     Amt = InsertNewInstBefore(Tmp, AI);
7866   }
7867   
7868   AllocationInst *New;
7869   if (isa<MallocInst>(AI))
7870     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7871   else
7872     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7873   InsertNewInstBefore(New, AI);
7874   New->takeName(&AI);
7875   
7876   // If the allocation has one real use plus a dbg.declare, just remove the
7877   // declare.
7878   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7879     EraseInstFromFunction(*DI);
7880   }
7881   // If the allocation has multiple real uses, insert a cast and change all
7882   // things that used it to use the new cast.  This will also hack on CI, but it
7883   // will die soon.
7884   else if (!AI.hasOneUse()) {
7885     AddUsesToWorkList(AI);
7886     // New is the allocation instruction, pointer typed. AI is the original
7887     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7888     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7889     InsertNewInstBefore(NewCast, AI);
7890     AI.replaceAllUsesWith(NewCast);
7891   }
7892   return ReplaceInstUsesWith(CI, New);
7893 }
7894
7895 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7896 /// and return it as type Ty without inserting any new casts and without
7897 /// changing the computed value.  This is used by code that tries to decide
7898 /// whether promoting or shrinking integer operations to wider or smaller types
7899 /// will allow us to eliminate a truncate or extend.
7900 ///
7901 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7902 /// extension operation if Ty is larger.
7903 ///
7904 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7905 /// should return true if trunc(V) can be computed by computing V in the smaller
7906 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7907 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7908 /// efficiently truncated.
7909 ///
7910 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7911 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7912 /// the final result.
7913 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7914                                               unsigned CastOpc,
7915                                               int &NumCastsRemoved){
7916   // We can always evaluate constants in another type.
7917   if (isa<Constant>(V))
7918     return true;
7919   
7920   Instruction *I = dyn_cast<Instruction>(V);
7921   if (!I) return false;
7922   
7923   const Type *OrigTy = V->getType();
7924   
7925   // If this is an extension or truncate, we can often eliminate it.
7926   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7927     // If this is a cast from the destination type, we can trivially eliminate
7928     // it, and this will remove a cast overall.
7929     if (I->getOperand(0)->getType() == Ty) {
7930       // If the first operand is itself a cast, and is eliminable, do not count
7931       // this as an eliminable cast.  We would prefer to eliminate those two
7932       // casts first.
7933       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7934         ++NumCastsRemoved;
7935       return true;
7936     }
7937   }
7938
7939   // We can't extend or shrink something that has multiple uses: doing so would
7940   // require duplicating the instruction in general, which isn't profitable.
7941   if (!I->hasOneUse()) return false;
7942
7943   unsigned Opc = I->getOpcode();
7944   switch (Opc) {
7945   case Instruction::Add:
7946   case Instruction::Sub:
7947   case Instruction::Mul:
7948   case Instruction::And:
7949   case Instruction::Or:
7950   case Instruction::Xor:
7951     // These operators can all arbitrarily be extended or truncated.
7952     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7953                                       NumCastsRemoved) &&
7954            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7955                                       NumCastsRemoved);
7956
7957   case Instruction::UDiv:
7958   case Instruction::URem: {
7959     // UDiv and URem can be truncated if all the truncated bits are zero.
7960     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7961     uint32_t BitWidth = Ty->getScalarSizeInBits();
7962     if (BitWidth < OrigBitWidth) {
7963       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7964       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7965           MaskedValueIsZero(I->getOperand(1), Mask)) {
7966         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7967                                           NumCastsRemoved) &&
7968                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7969                                           NumCastsRemoved);
7970       }
7971     }
7972     break;
7973   }
7974   case Instruction::Shl:
7975     // If we are truncating the result of this SHL, and if it's a shift of a
7976     // constant amount, we can always perform a SHL in a smaller type.
7977     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7978       uint32_t BitWidth = Ty->getScalarSizeInBits();
7979       if (BitWidth < OrigTy->getScalarSizeInBits() &&
7980           CI->getLimitedValue(BitWidth) < BitWidth)
7981         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7982                                           NumCastsRemoved);
7983     }
7984     break;
7985   case Instruction::LShr:
7986     // If this is a truncate of a logical shr, we can truncate it to a smaller
7987     // lshr iff we know that the bits we would otherwise be shifting in are
7988     // already zeros.
7989     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7990       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7991       uint32_t BitWidth = Ty->getScalarSizeInBits();
7992       if (BitWidth < OrigBitWidth &&
7993           MaskedValueIsZero(I->getOperand(0),
7994             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7995           CI->getLimitedValue(BitWidth) < BitWidth) {
7996         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7997                                           NumCastsRemoved);
7998       }
7999     }
8000     break;
8001   case Instruction::ZExt:
8002   case Instruction::SExt:
8003   case Instruction::Trunc:
8004     // If this is the same kind of case as our original (e.g. zext+zext), we
8005     // can safely replace it.  Note that replacing it does not reduce the number
8006     // of casts in the input.
8007     if (Opc == CastOpc)
8008       return true;
8009
8010     // sext (zext ty1), ty2 -> zext ty2
8011     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
8012       return true;
8013     break;
8014   case Instruction::Select: {
8015     SelectInst *SI = cast<SelectInst>(I);
8016     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8017                                       NumCastsRemoved) &&
8018            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8019                                       NumCastsRemoved);
8020   }
8021   case Instruction::PHI: {
8022     // We can change a phi if we can change all operands.
8023     PHINode *PN = cast<PHINode>(I);
8024     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8025       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8026                                       NumCastsRemoved))
8027         return false;
8028     return true;
8029   }
8030   default:
8031     // TODO: Can handle more cases here.
8032     break;
8033   }
8034   
8035   return false;
8036 }
8037
8038 /// EvaluateInDifferentType - Given an expression that 
8039 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8040 /// evaluate the expression.
8041 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
8042                                              bool isSigned) {
8043   if (Constant *C = dyn_cast<Constant>(V))
8044     return Context->getConstantExprIntegerCast(C, Ty,
8045                                                isSigned /*Sext or ZExt*/);
8046
8047   // Otherwise, it must be an instruction.
8048   Instruction *I = cast<Instruction>(V);
8049   Instruction *Res = 0;
8050   unsigned Opc = I->getOpcode();
8051   switch (Opc) {
8052   case Instruction::Add:
8053   case Instruction::Sub:
8054   case Instruction::Mul:
8055   case Instruction::And:
8056   case Instruction::Or:
8057   case Instruction::Xor:
8058   case Instruction::AShr:
8059   case Instruction::LShr:
8060   case Instruction::Shl:
8061   case Instruction::UDiv:
8062   case Instruction::URem: {
8063     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8064     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8065     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8066     break;
8067   }    
8068   case Instruction::Trunc:
8069   case Instruction::ZExt:
8070   case Instruction::SExt:
8071     // If the source type of the cast is the type we're trying for then we can
8072     // just return the source.  There's no need to insert it because it is not
8073     // new.
8074     if (I->getOperand(0)->getType() == Ty)
8075       return I->getOperand(0);
8076     
8077     // Otherwise, must be the same type of cast, so just reinsert a new one.
8078     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8079                            Ty);
8080     break;
8081   case Instruction::Select: {
8082     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8083     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8084     Res = SelectInst::Create(I->getOperand(0), True, False);
8085     break;
8086   }
8087   case Instruction::PHI: {
8088     PHINode *OPN = cast<PHINode>(I);
8089     PHINode *NPN = PHINode::Create(Ty);
8090     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8091       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8092       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8093     }
8094     Res = NPN;
8095     break;
8096   }
8097   default: 
8098     // TODO: Can handle more cases here.
8099     llvm_unreachable("Unreachable!");
8100     break;
8101   }
8102   
8103   Res->takeName(I);
8104   return InsertNewInstBefore(Res, *I);
8105 }
8106
8107 /// @brief Implement the transforms common to all CastInst visitors.
8108 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8109   Value *Src = CI.getOperand(0);
8110
8111   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8112   // eliminate it now.
8113   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8114     if (Instruction::CastOps opc = 
8115         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8116       // The first cast (CSrc) is eliminable so we need to fix up or replace
8117       // the second cast (CI). CSrc will then have a good chance of being dead.
8118       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8119     }
8120   }
8121
8122   // If we are casting a select then fold the cast into the select
8123   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8124     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8125       return NV;
8126
8127   // If we are casting a PHI then fold the cast into the PHI
8128   if (isa<PHINode>(Src))
8129     if (Instruction *NV = FoldOpIntoPhi(CI))
8130       return NV;
8131   
8132   return 0;
8133 }
8134
8135 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8136 /// or not there is a sequence of GEP indices into the type that will land us at
8137 /// the specified offset.  If so, fill them into NewIndices and return the
8138 /// resultant element type, otherwise return null.
8139 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8140                                        SmallVectorImpl<Value*> &NewIndices,
8141                                        const TargetData *TD,
8142                                        LLVMContext *Context) {
8143   if (!Ty->isSized()) return 0;
8144   
8145   // Start with the index over the outer type.  Note that the type size
8146   // might be zero (even if the offset isn't zero) if the indexed type
8147   // is something like [0 x {int, int}]
8148   const Type *IntPtrTy = TD->getIntPtrType();
8149   int64_t FirstIdx = 0;
8150   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8151     FirstIdx = Offset/TySize;
8152     Offset -= FirstIdx*TySize;
8153     
8154     // Handle hosts where % returns negative instead of values [0..TySize).
8155     if (Offset < 0) {
8156       --FirstIdx;
8157       Offset += TySize;
8158       assert(Offset >= 0);
8159     }
8160     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8161   }
8162   
8163   NewIndices.push_back(Context->getConstantInt(IntPtrTy, FirstIdx));
8164     
8165   // Index into the types.  If we fail, set OrigBase to null.
8166   while (Offset) {
8167     // Indexing into tail padding between struct/array elements.
8168     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8169       return 0;
8170     
8171     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8172       const StructLayout *SL = TD->getStructLayout(STy);
8173       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8174              "Offset must stay within the indexed type");
8175       
8176       unsigned Elt = SL->getElementContainingOffset(Offset);
8177       NewIndices.push_back(Context->getConstantInt(Type::Int32Ty, Elt));
8178       
8179       Offset -= SL->getElementOffset(Elt);
8180       Ty = STy->getElementType(Elt);
8181     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8182       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8183       assert(EltSize && "Cannot index into a zero-sized array");
8184       NewIndices.push_back(Context->getConstantInt(IntPtrTy,Offset/EltSize));
8185       Offset %= EltSize;
8186       Ty = AT->getElementType();
8187     } else {
8188       // Otherwise, we can't index into the middle of this atomic type, bail.
8189       return 0;
8190     }
8191   }
8192   
8193   return Ty;
8194 }
8195
8196 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8197 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8198   Value *Src = CI.getOperand(0);
8199   
8200   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8201     // If casting the result of a getelementptr instruction with no offset, turn
8202     // this into a cast of the original pointer!
8203     if (GEP->hasAllZeroIndices()) {
8204       // Changing the cast operand is usually not a good idea but it is safe
8205       // here because the pointer operand is being replaced with another 
8206       // pointer operand so the opcode doesn't need to change.
8207       AddToWorkList(GEP);
8208       CI.setOperand(0, GEP->getOperand(0));
8209       return &CI;
8210     }
8211     
8212     // If the GEP has a single use, and the base pointer is a bitcast, and the
8213     // GEP computes a constant offset, see if we can convert these three
8214     // instructions into fewer.  This typically happens with unions and other
8215     // non-type-safe code.
8216     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8217       if (GEP->hasAllConstantIndices()) {
8218         // We are guaranteed to get a constant from EmitGEPOffset.
8219         ConstantInt *OffsetV =
8220                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8221         int64_t Offset = OffsetV->getSExtValue();
8222         
8223         // Get the base pointer input of the bitcast, and the type it points to.
8224         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8225         const Type *GEPIdxTy =
8226           cast<PointerType>(OrigBase->getType())->getElementType();
8227         SmallVector<Value*, 8> NewIndices;
8228         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8229           // If we were able to index down into an element, create the GEP
8230           // and bitcast the result.  This eliminates one bitcast, potentially
8231           // two.
8232           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
8233                                                         NewIndices.begin(),
8234                                                         NewIndices.end(), "");
8235           InsertNewInstBefore(NGEP, CI);
8236           NGEP->takeName(GEP);
8237           
8238           if (isa<BitCastInst>(CI))
8239             return new BitCastInst(NGEP, CI.getType());
8240           assert(isa<PtrToIntInst>(CI));
8241           return new PtrToIntInst(NGEP, CI.getType());
8242         }
8243       }      
8244     }
8245   }
8246     
8247   return commonCastTransforms(CI);
8248 }
8249
8250 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8251 /// type like i42.  We don't want to introduce operations on random non-legal
8252 /// integer types where they don't already exist in the code.  In the future,
8253 /// we should consider making this based off target-data, so that 32-bit targets
8254 /// won't get i64 operations etc.
8255 static bool isSafeIntegerType(const Type *Ty) {
8256   switch (Ty->getPrimitiveSizeInBits()) {
8257   case 8:
8258   case 16:
8259   case 32:
8260   case 64:
8261     return true;
8262   default: 
8263     return false;
8264   }
8265 }
8266
8267 /// commonIntCastTransforms - This function implements the common transforms
8268 /// for trunc, zext, and sext.
8269 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8270   if (Instruction *Result = commonCastTransforms(CI))
8271     return Result;
8272
8273   Value *Src = CI.getOperand(0);
8274   const Type *SrcTy = Src->getType();
8275   const Type *DestTy = CI.getType();
8276   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8277   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8278
8279   // See if we can simplify any instructions used by the LHS whose sole 
8280   // purpose is to compute bits we don't care about.
8281   if (SimplifyDemandedInstructionBits(CI))
8282     return &CI;
8283
8284   // If the source isn't an instruction or has more than one use then we
8285   // can't do anything more. 
8286   Instruction *SrcI = dyn_cast<Instruction>(Src);
8287   if (!SrcI || !Src->hasOneUse())
8288     return 0;
8289
8290   // Attempt to propagate the cast into the instruction for int->int casts.
8291   int NumCastsRemoved = 0;
8292   // Only do this if the dest type is a simple type, don't convert the
8293   // expression tree to something weird like i93 unless the source is also
8294   // strange.
8295   if ((isSafeIntegerType(DestTy->getScalarType()) ||
8296        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8297       CanEvaluateInDifferentType(SrcI, DestTy,
8298                                  CI.getOpcode(), NumCastsRemoved)) {
8299     // If this cast is a truncate, evaluting in a different type always
8300     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8301     // we need to do an AND to maintain the clear top-part of the computation,
8302     // so we require that the input have eliminated at least one cast.  If this
8303     // is a sign extension, we insert two new casts (to do the extension) so we
8304     // require that two casts have been eliminated.
8305     bool DoXForm = false;
8306     bool JustReplace = false;
8307     switch (CI.getOpcode()) {
8308     default:
8309       // All the others use floating point so we shouldn't actually 
8310       // get here because of the check above.
8311       llvm_unreachable("Unknown cast type");
8312     case Instruction::Trunc:
8313       DoXForm = true;
8314       break;
8315     case Instruction::ZExt: {
8316       DoXForm = NumCastsRemoved >= 1;
8317       if (!DoXForm && 0) {
8318         // If it's unnecessary to issue an AND to clear the high bits, it's
8319         // always profitable to do this xform.
8320         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8321         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8322         if (MaskedValueIsZero(TryRes, Mask))
8323           return ReplaceInstUsesWith(CI, TryRes);
8324         
8325         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8326           if (TryI->use_empty())
8327             EraseInstFromFunction(*TryI);
8328       }
8329       break;
8330     }
8331     case Instruction::SExt: {
8332       DoXForm = NumCastsRemoved >= 2;
8333       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8334         // If we do not have to emit the truncate + sext pair, then it's always
8335         // profitable to do this xform.
8336         //
8337         // It's not safe to eliminate the trunc + sext pair if one of the
8338         // eliminated cast is a truncate. e.g.
8339         // t2 = trunc i32 t1 to i16
8340         // t3 = sext i16 t2 to i32
8341         // !=
8342         // i32 t1
8343         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8344         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8345         if (NumSignBits > (DestBitSize - SrcBitSize))
8346           return ReplaceInstUsesWith(CI, TryRes);
8347         
8348         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8349           if (TryI->use_empty())
8350             EraseInstFromFunction(*TryI);
8351       }
8352       break;
8353     }
8354     }
8355     
8356     if (DoXForm) {
8357       DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8358            << " cast: " << CI;
8359       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8360                                            CI.getOpcode() == Instruction::SExt);
8361       if (JustReplace)
8362         // Just replace this cast with the result.
8363         return ReplaceInstUsesWith(CI, Res);
8364
8365       assert(Res->getType() == DestTy);
8366       switch (CI.getOpcode()) {
8367       default: llvm_unreachable("Unknown cast type!");
8368       case Instruction::Trunc:
8369         // Just replace this cast with the result.
8370         return ReplaceInstUsesWith(CI, Res);
8371       case Instruction::ZExt: {
8372         assert(SrcBitSize < DestBitSize && "Not a zext?");
8373
8374         // If the high bits are already zero, just replace this cast with the
8375         // result.
8376         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8377         if (MaskedValueIsZero(Res, Mask))
8378           return ReplaceInstUsesWith(CI, Res);
8379
8380         // We need to emit an AND to clear the high bits.
8381         Constant *C = Context->getConstantInt(APInt::getLowBitsSet(DestBitSize,
8382                                                             SrcBitSize));
8383         return BinaryOperator::CreateAnd(Res, C);
8384       }
8385       case Instruction::SExt: {
8386         // If the high bits are already filled with sign bit, just replace this
8387         // cast with the result.
8388         unsigned NumSignBits = ComputeNumSignBits(Res);
8389         if (NumSignBits > (DestBitSize - SrcBitSize))
8390           return ReplaceInstUsesWith(CI, Res);
8391
8392         // We need to emit a cast to truncate, then a cast to sext.
8393         return CastInst::Create(Instruction::SExt,
8394             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8395                              CI), DestTy);
8396       }
8397       }
8398     }
8399   }
8400   
8401   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8402   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8403
8404   switch (SrcI->getOpcode()) {
8405   case Instruction::Add:
8406   case Instruction::Mul:
8407   case Instruction::And:
8408   case Instruction::Or:
8409   case Instruction::Xor:
8410     // If we are discarding information, rewrite.
8411     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8412       // Don't insert two casts unless at least one can be eliminated.
8413       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8414           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8415         Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8416         Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8417         return BinaryOperator::Create(
8418             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8419       }
8420     }
8421
8422     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8423     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8424         SrcI->getOpcode() == Instruction::Xor &&
8425         Op1 == Context->getConstantIntTrue() &&
8426         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8427       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8428       return BinaryOperator::CreateXor(New,
8429                                       Context->getConstantInt(CI.getType(), 1));
8430     }
8431     break;
8432
8433   case Instruction::Shl: {
8434     // Canonicalize trunc inside shl, if we can.
8435     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8436     if (CI && DestBitSize < SrcBitSize &&
8437         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8438       Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8439       Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8440       return BinaryOperator::CreateShl(Op0c, Op1c);
8441     }
8442     break;
8443   }
8444   }
8445   return 0;
8446 }
8447
8448 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8449   if (Instruction *Result = commonIntCastTransforms(CI))
8450     return Result;
8451   
8452   Value *Src = CI.getOperand(0);
8453   const Type *Ty = CI.getType();
8454   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8455   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8456
8457   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8458   if (DestBitWidth == 1 &&
8459       isa<VectorType>(Ty) == isa<VectorType>(Src->getType())) {
8460     Constant *One = Context->getConstantInt(Src->getType(), 1);
8461     Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8462     Value *Zero = Context->getNullValue(Src->getType());
8463     return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
8464   }
8465
8466   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8467   ConstantInt *ShAmtV = 0;
8468   Value *ShiftOp = 0;
8469   if (Src->hasOneUse() &&
8470       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
8471     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8472     
8473     // Get a mask for the bits shifting in.
8474     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8475     if (MaskedValueIsZero(ShiftOp, Mask)) {
8476       if (ShAmt >= DestBitWidth)        // All zeros.
8477         return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
8478       
8479       // Okay, we can shrink this.  Truncate the input, then return a new
8480       // shift.
8481       Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8482       Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
8483       return BinaryOperator::CreateLShr(V1, V2);
8484     }
8485   }
8486   
8487   return 0;
8488 }
8489
8490 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8491 /// in order to eliminate the icmp.
8492 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8493                                              bool DoXform) {
8494   // If we are just checking for a icmp eq of a single bit and zext'ing it
8495   // to an integer, then shift the bit to the appropriate place and then
8496   // cast to integer to avoid the comparison.
8497   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8498     const APInt &Op1CV = Op1C->getValue();
8499       
8500     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8501     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8502     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8503         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8504       if (!DoXform) return ICI;
8505
8506       Value *In = ICI->getOperand(0);
8507       Value *Sh = Context->getConstantInt(In->getType(),
8508                                    In->getType()->getScalarSizeInBits()-1);
8509       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8510                                                         In->getName()+".lobit"),
8511                                CI);
8512       if (In->getType() != CI.getType())
8513         In = CastInst::CreateIntegerCast(In, CI.getType(),
8514                                          false/*ZExt*/, "tmp", &CI);
8515
8516       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8517         Constant *One = Context->getConstantInt(In->getType(), 1);
8518         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8519                                                          In->getName()+".not"),
8520                                  CI);
8521       }
8522
8523       return ReplaceInstUsesWith(CI, In);
8524     }
8525       
8526       
8527       
8528     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8529     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8530     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8531     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8532     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8533     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8534     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8535     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8536     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8537         // This only works for EQ and NE
8538         ICI->isEquality()) {
8539       // If Op1C some other power of two, convert:
8540       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8541       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8542       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8543       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8544         
8545       APInt KnownZeroMask(~KnownZero);
8546       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8547         if (!DoXform) return ICI;
8548
8549         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8550         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8551           // (X&4) == 2 --> false
8552           // (X&4) != 2 --> true
8553           Constant *Res = Context->getConstantInt(Type::Int1Ty, isNE);
8554           Res = Context->getConstantExprZExt(Res, CI.getType());
8555           return ReplaceInstUsesWith(CI, Res);
8556         }
8557           
8558         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8559         Value *In = ICI->getOperand(0);
8560         if (ShiftAmt) {
8561           // Perform a logical shr by shiftamt.
8562           // Insert the shift to put the result in the low bit.
8563           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8564                               Context->getConstantInt(In->getType(), ShiftAmt),
8565                                                    In->getName()+".lobit"), CI);
8566         }
8567           
8568         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8569           Constant *One = Context->getConstantInt(In->getType(), 1);
8570           In = BinaryOperator::CreateXor(In, One, "tmp");
8571           InsertNewInstBefore(cast<Instruction>(In), CI);
8572         }
8573           
8574         if (CI.getType() == In->getType())
8575           return ReplaceInstUsesWith(CI, In);
8576         else
8577           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8578       }
8579     }
8580   }
8581
8582   return 0;
8583 }
8584
8585 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8586   // If one of the common conversion will work ..
8587   if (Instruction *Result = commonIntCastTransforms(CI))
8588     return Result;
8589
8590   Value *Src = CI.getOperand(0);
8591
8592   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8593   // types and if the sizes are just right we can convert this into a logical
8594   // 'and' which will be much cheaper than the pair of casts.
8595   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8596     // Get the sizes of the types involved.  We know that the intermediate type
8597     // will be smaller than A or C, but don't know the relation between A and C.
8598     Value *A = CSrc->getOperand(0);
8599     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8600     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8601     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8602     // If we're actually extending zero bits, then if
8603     // SrcSize <  DstSize: zext(a & mask)
8604     // SrcSize == DstSize: a & mask
8605     // SrcSize  > DstSize: trunc(a) & mask
8606     if (SrcSize < DstSize) {
8607       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8608       Constant *AndConst = Context->getConstantInt(A->getType(), AndValue);
8609       Instruction *And =
8610         BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8611       InsertNewInstBefore(And, CI);
8612       return new ZExtInst(And, CI.getType());
8613     } else if (SrcSize == DstSize) {
8614       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8615       return BinaryOperator::CreateAnd(A, Context->getConstantInt(A->getType(),
8616                                                            AndValue));
8617     } else if (SrcSize > DstSize) {
8618       Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8619       InsertNewInstBefore(Trunc, CI);
8620       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8621       return BinaryOperator::CreateAnd(Trunc, 
8622                                        Context->getConstantInt(Trunc->getType(),
8623                                                                AndValue));
8624     }
8625   }
8626
8627   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8628     return transformZExtICmp(ICI, CI);
8629
8630   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8631   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8632     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8633     // of the (zext icmp) will be transformed.
8634     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8635     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8636     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8637         (transformZExtICmp(LHS, CI, false) ||
8638          transformZExtICmp(RHS, CI, false))) {
8639       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8640       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8641       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8642     }
8643   }
8644
8645   // zext(trunc(t) & C) -> (t & zext(C)).
8646   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8647     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8648       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8649         Value *TI0 = TI->getOperand(0);
8650         if (TI0->getType() == CI.getType())
8651           return
8652             BinaryOperator::CreateAnd(TI0,
8653                                 Context->getConstantExprZExt(C, CI.getType()));
8654       }
8655
8656   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8657   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8658     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8659       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8660         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8661             And->getOperand(1) == C)
8662           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8663             Value *TI0 = TI->getOperand(0);
8664             if (TI0->getType() == CI.getType()) {
8665               Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
8666               Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8667               InsertNewInstBefore(NewAnd, *And);
8668               return BinaryOperator::CreateXor(NewAnd, ZC);
8669             }
8670           }
8671
8672   return 0;
8673 }
8674
8675 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8676   if (Instruction *I = commonIntCastTransforms(CI))
8677     return I;
8678   
8679   Value *Src = CI.getOperand(0);
8680   
8681   // Canonicalize sign-extend from i1 to a select.
8682   if (Src->getType() == Type::Int1Ty)
8683     return SelectInst::Create(Src,
8684                               Context->getAllOnesValue(CI.getType()),
8685                               Context->getNullValue(CI.getType()));
8686
8687   // See if the value being truncated is already sign extended.  If so, just
8688   // eliminate the trunc/sext pair.
8689   if (Operator::getOpcode(Src) == Instruction::Trunc) {
8690     Value *Op = cast<User>(Src)->getOperand(0);
8691     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8692     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8693     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8694     unsigned NumSignBits = ComputeNumSignBits(Op);
8695
8696     if (OpBits == DestBits) {
8697       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8698       // bits, it is already ready.
8699       if (NumSignBits > DestBits-MidBits)
8700         return ReplaceInstUsesWith(CI, Op);
8701     } else if (OpBits < DestBits) {
8702       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8703       // bits, just sext from i32.
8704       if (NumSignBits > OpBits-MidBits)
8705         return new SExtInst(Op, CI.getType(), "tmp");
8706     } else {
8707       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8708       // bits, just truncate to i32.
8709       if (NumSignBits > OpBits-MidBits)
8710         return new TruncInst(Op, CI.getType(), "tmp");
8711     }
8712   }
8713
8714   // If the input is a shl/ashr pair of a same constant, then this is a sign
8715   // extension from a smaller value.  If we could trust arbitrary bitwidth
8716   // integers, we could turn this into a truncate to the smaller bit and then
8717   // use a sext for the whole extension.  Since we don't, look deeper and check
8718   // for a truncate.  If the source and dest are the same type, eliminate the
8719   // trunc and extend and just do shifts.  For example, turn:
8720   //   %a = trunc i32 %i to i8
8721   //   %b = shl i8 %a, 6
8722   //   %c = ashr i8 %b, 6
8723   //   %d = sext i8 %c to i32
8724   // into:
8725   //   %a = shl i32 %i, 30
8726   //   %d = ashr i32 %a, 30
8727   Value *A = 0;
8728   ConstantInt *BA = 0, *CA = 0;
8729   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8730                         m_ConstantInt(CA)), *Context) &&
8731       BA == CA && isa<TruncInst>(A)) {
8732     Value *I = cast<TruncInst>(A)->getOperand(0);
8733     if (I->getType() == CI.getType()) {
8734       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8735       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8736       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8737       Constant *ShAmtV = Context->getConstantInt(CI.getType(), ShAmt);
8738       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8739                                                         CI.getName()), CI);
8740       return BinaryOperator::CreateAShr(I, ShAmtV);
8741     }
8742   }
8743   
8744   return 0;
8745 }
8746
8747 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8748 /// in the specified FP type without changing its value.
8749 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8750                               LLVMContext *Context) {
8751   bool losesInfo;
8752   APFloat F = CFP->getValueAPF();
8753   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8754   if (!losesInfo)
8755     return Context->getConstantFP(F);
8756   return 0;
8757 }
8758
8759 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8760 /// through it until we get the source value.
8761 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8762   if (Instruction *I = dyn_cast<Instruction>(V))
8763     if (I->getOpcode() == Instruction::FPExt)
8764       return LookThroughFPExtensions(I->getOperand(0), Context);
8765   
8766   // If this value is a constant, return the constant in the smallest FP type
8767   // that can accurately represent it.  This allows us to turn
8768   // (float)((double)X+2.0) into x+2.0f.
8769   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8770     if (CFP->getType() == Type::PPC_FP128Ty)
8771       return V;  // No constant folding of this.
8772     // See if the value can be truncated to float and then reextended.
8773     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8774       return V;
8775     if (CFP->getType() == Type::DoubleTy)
8776       return V;  // Won't shrink.
8777     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8778       return V;
8779     // Don't try to shrink to various long double types.
8780   }
8781   
8782   return V;
8783 }
8784
8785 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8786   if (Instruction *I = commonCastTransforms(CI))
8787     return I;
8788   
8789   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8790   // smaller than the destination type, we can eliminate the truncate by doing
8791   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8792   // many builtins (sqrt, etc).
8793   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8794   if (OpI && OpI->hasOneUse()) {
8795     switch (OpI->getOpcode()) {
8796     default: break;
8797     case Instruction::FAdd:
8798     case Instruction::FSub:
8799     case Instruction::FMul:
8800     case Instruction::FDiv:
8801     case Instruction::FRem:
8802       const Type *SrcTy = OpI->getType();
8803       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8804       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8805       if (LHSTrunc->getType() != SrcTy && 
8806           RHSTrunc->getType() != SrcTy) {
8807         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8808         // If the source types were both smaller than the destination type of
8809         // the cast, do this xform.
8810         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8811             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8812           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8813                                       CI.getType(), CI);
8814           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8815                                       CI.getType(), CI);
8816           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8817         }
8818       }
8819       break;  
8820     }
8821   }
8822   return 0;
8823 }
8824
8825 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8826   return commonCastTransforms(CI);
8827 }
8828
8829 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8830   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8831   if (OpI == 0)
8832     return commonCastTransforms(FI);
8833
8834   // fptoui(uitofp(X)) --> X
8835   // fptoui(sitofp(X)) --> X
8836   // This is safe if the intermediate type has enough bits in its mantissa to
8837   // accurately represent all values of X.  For example, do not do this with
8838   // i64->float->i64.  This is also safe for sitofp case, because any negative
8839   // 'X' value would cause an undefined result for the fptoui. 
8840   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8841       OpI->getOperand(0)->getType() == FI.getType() &&
8842       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8843                     OpI->getType()->getFPMantissaWidth())
8844     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8845
8846   return commonCastTransforms(FI);
8847 }
8848
8849 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8850   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8851   if (OpI == 0)
8852     return commonCastTransforms(FI);
8853   
8854   // fptosi(sitofp(X)) --> X
8855   // fptosi(uitofp(X)) --> X
8856   // This is safe if the intermediate type has enough bits in its mantissa to
8857   // accurately represent all values of X.  For example, do not do this with
8858   // i64->float->i64.  This is also safe for sitofp case, because any negative
8859   // 'X' value would cause an undefined result for the fptoui. 
8860   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8861       OpI->getOperand(0)->getType() == FI.getType() &&
8862       (int)FI.getType()->getScalarSizeInBits() <=
8863                     OpI->getType()->getFPMantissaWidth())
8864     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8865   
8866   return commonCastTransforms(FI);
8867 }
8868
8869 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8870   return commonCastTransforms(CI);
8871 }
8872
8873 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8874   return commonCastTransforms(CI);
8875 }
8876
8877 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8878   // If the destination integer type is smaller than the intptr_t type for
8879   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8880   // trunc to be exposed to other transforms.  Don't do this for extending
8881   // ptrtoint's, because we don't know if the target sign or zero extends its
8882   // pointers.
8883   if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8884     Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8885                                                     TD->getIntPtrType(),
8886                                                     "tmp"), CI);
8887     return new TruncInst(P, CI.getType());
8888   }
8889   
8890   return commonPointerCastTransforms(CI);
8891 }
8892
8893 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8894   // If the source integer type is larger than the intptr_t type for
8895   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8896   // allows the trunc to be exposed to other transforms.  Don't do this for
8897   // extending inttoptr's, because we don't know if the target sign or zero
8898   // extends to pointers.
8899   if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
8900       TD->getPointerSizeInBits()) {
8901     Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8902                                                  TD->getIntPtrType(),
8903                                                  "tmp"), CI);
8904     return new IntToPtrInst(P, CI.getType());
8905   }
8906   
8907   if (Instruction *I = commonCastTransforms(CI))
8908     return I;
8909   
8910   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8911   if (!DestPointee->isSized()) return 0;
8912
8913   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8914   ConstantInt *Cst;
8915   Value *X;
8916   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8917                                     m_ConstantInt(Cst)), *Context)) {
8918     // If the source and destination operands have the same type, see if this
8919     // is a single-index GEP.
8920     if (X->getType() == CI.getType()) {
8921       // Get the size of the pointee type.
8922       uint64_t Size = TD->getTypeAllocSize(DestPointee);
8923
8924       // Convert the constant to intptr type.
8925       APInt Offset = Cst->getValue();
8926       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8927
8928       // If Offset is evenly divisible by Size, we can do this xform.
8929       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8930         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8931         GetElementPtrInst *GEP =
8932           GetElementPtrInst::Create(X, Context->getConstantInt(Offset));
8933         // A gep synthesized from inttoptr+add+ptrtoint must be assumed to
8934         // potentially overflow, in the absense of further analysis.
8935         cast<GEPOperator>(GEP)->setHasNoPointerOverflow(false);
8936         return GEP;
8937       }
8938     }
8939     // TODO: Could handle other cases, e.g. where add is indexing into field of
8940     // struct etc.
8941   } else if (CI.getOperand(0)->hasOneUse() &&
8942              match(CI.getOperand(0), m_Add(m_Value(X),
8943                    m_ConstantInt(Cst)), *Context)) {
8944     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8945     // "inttoptr+GEP" instead of "add+intptr".
8946     
8947     // Get the size of the pointee type.
8948     uint64_t Size = TD->getTypeAllocSize(DestPointee);
8949     
8950     // Convert the constant to intptr type.
8951     APInt Offset = Cst->getValue();
8952     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8953     
8954     // If Offset is evenly divisible by Size, we can do this xform.
8955     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8956       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8957       
8958       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8959                                                             "tmp"), CI);
8960       GetElementPtrInst *GEP =
8961         GetElementPtrInst::Create(P, Context->getConstantInt(Offset), "tmp");
8962       // A gep synthesized from inttoptr+add+ptrtoint must be assumed to
8963       // potentially overflow, in the absense of further analysis.
8964       cast<GEPOperator>(GEP)->setHasNoPointerOverflow(false);
8965       return GEP;
8966     }
8967   }
8968   return 0;
8969 }
8970
8971 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8972   // If the operands are integer typed then apply the integer transforms,
8973   // otherwise just apply the common ones.
8974   Value *Src = CI.getOperand(0);
8975   const Type *SrcTy = Src->getType();
8976   const Type *DestTy = CI.getType();
8977
8978   if (isa<PointerType>(SrcTy)) {
8979     if (Instruction *I = commonPointerCastTransforms(CI))
8980       return I;
8981   } else {
8982     if (Instruction *Result = commonCastTransforms(CI))
8983       return Result;
8984   }
8985
8986
8987   // Get rid of casts from one type to the same type. These are useless and can
8988   // be replaced by the operand.
8989   if (DestTy == Src->getType())
8990     return ReplaceInstUsesWith(CI, Src);
8991
8992   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8993     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8994     const Type *DstElTy = DstPTy->getElementType();
8995     const Type *SrcElTy = SrcPTy->getElementType();
8996     
8997     // If the address spaces don't match, don't eliminate the bitcast, which is
8998     // required for changing types.
8999     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9000       return 0;
9001     
9002     // If we are casting a malloc or alloca to a pointer to a type of the same
9003     // size, rewrite the allocation instruction to allocate the "right" type.
9004     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
9005       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9006         return V;
9007     
9008     // If the source and destination are pointers, and this cast is equivalent
9009     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
9010     // This can enhance SROA and other transforms that want type-safe pointers.
9011     Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
9012     unsigned NumZeros = 0;
9013     while (SrcElTy != DstElTy && 
9014            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9015            SrcElTy->getNumContainedTypes() /* not "{}" */) {
9016       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9017       ++NumZeros;
9018     }
9019
9020     // If we found a path from the src to dest, create the getelementptr now.
9021     if (SrcElTy == DstElTy) {
9022       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
9023       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
9024                                        ((Instruction*) NULL));
9025     }
9026   }
9027
9028   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9029     if (SVI->hasOneUse()) {
9030       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
9031       // a bitconvert to a vector with the same # elts.
9032       if (isa<VectorType>(DestTy) && 
9033           cast<VectorType>(DestTy)->getNumElements() ==
9034                 SVI->getType()->getNumElements() &&
9035           SVI->getType()->getNumElements() ==
9036             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9037         CastInst *Tmp;
9038         // If either of the operands is a cast from CI.getType(), then
9039         // evaluating the shuffle in the casted destination's type will allow
9040         // us to eliminate at least one cast.
9041         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
9042              Tmp->getOperand(0)->getType() == DestTy) ||
9043             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
9044              Tmp->getOperand(0)->getType() == DestTy)) {
9045           Value *LHS = InsertCastBefore(Instruction::BitCast,
9046                                         SVI->getOperand(0), DestTy, CI);
9047           Value *RHS = InsertCastBefore(Instruction::BitCast,
9048                                         SVI->getOperand(1), DestTy, CI);
9049           // Return a new shuffle vector.  Use the same element ID's, as we
9050           // know the vector types match #elts.
9051           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9052         }
9053       }
9054     }
9055   }
9056   return 0;
9057 }
9058
9059 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9060 ///   %C = or %A, %B
9061 ///   %D = select %cond, %C, %A
9062 /// into:
9063 ///   %C = select %cond, %B, 0
9064 ///   %D = or %A, %C
9065 ///
9066 /// Assuming that the specified instruction is an operand to the select, return
9067 /// a bitmask indicating which operands of this instruction are foldable if they
9068 /// equal the other incoming value of the select.
9069 ///
9070 static unsigned GetSelectFoldableOperands(Instruction *I) {
9071   switch (I->getOpcode()) {
9072   case Instruction::Add:
9073   case Instruction::Mul:
9074   case Instruction::And:
9075   case Instruction::Or:
9076   case Instruction::Xor:
9077     return 3;              // Can fold through either operand.
9078   case Instruction::Sub:   // Can only fold on the amount subtracted.
9079   case Instruction::Shl:   // Can only fold on the shift amount.
9080   case Instruction::LShr:
9081   case Instruction::AShr:
9082     return 1;
9083   default:
9084     return 0;              // Cannot fold
9085   }
9086 }
9087
9088 /// GetSelectFoldableConstant - For the same transformation as the previous
9089 /// function, return the identity constant that goes into the select.
9090 static Constant *GetSelectFoldableConstant(Instruction *I,
9091                                            LLVMContext *Context) {
9092   switch (I->getOpcode()) {
9093   default: llvm_unreachable("This cannot happen!");
9094   case Instruction::Add:
9095   case Instruction::Sub:
9096   case Instruction::Or:
9097   case Instruction::Xor:
9098   case Instruction::Shl:
9099   case Instruction::LShr:
9100   case Instruction::AShr:
9101     return Context->getNullValue(I->getType());
9102   case Instruction::And:
9103     return Context->getAllOnesValue(I->getType());
9104   case Instruction::Mul:
9105     return Context->getConstantInt(I->getType(), 1);
9106   }
9107 }
9108
9109 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9110 /// have the same opcode and only one use each.  Try to simplify this.
9111 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9112                                           Instruction *FI) {
9113   if (TI->getNumOperands() == 1) {
9114     // If this is a non-volatile load or a cast from the same type,
9115     // merge.
9116     if (TI->isCast()) {
9117       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9118         return 0;
9119     } else {
9120       return 0;  // unknown unary op.
9121     }
9122
9123     // Fold this by inserting a select from the input values.
9124     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9125                                            FI->getOperand(0), SI.getName()+".v");
9126     InsertNewInstBefore(NewSI, SI);
9127     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9128                             TI->getType());
9129   }
9130
9131   // Only handle binary operators here.
9132   if (!isa<BinaryOperator>(TI))
9133     return 0;
9134
9135   // Figure out if the operations have any operands in common.
9136   Value *MatchOp, *OtherOpT, *OtherOpF;
9137   bool MatchIsOpZero;
9138   if (TI->getOperand(0) == FI->getOperand(0)) {
9139     MatchOp  = TI->getOperand(0);
9140     OtherOpT = TI->getOperand(1);
9141     OtherOpF = FI->getOperand(1);
9142     MatchIsOpZero = true;
9143   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9144     MatchOp  = TI->getOperand(1);
9145     OtherOpT = TI->getOperand(0);
9146     OtherOpF = FI->getOperand(0);
9147     MatchIsOpZero = false;
9148   } else if (!TI->isCommutative()) {
9149     return 0;
9150   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9151     MatchOp  = TI->getOperand(0);
9152     OtherOpT = TI->getOperand(1);
9153     OtherOpF = FI->getOperand(0);
9154     MatchIsOpZero = true;
9155   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9156     MatchOp  = TI->getOperand(1);
9157     OtherOpT = TI->getOperand(0);
9158     OtherOpF = FI->getOperand(1);
9159     MatchIsOpZero = true;
9160   } else {
9161     return 0;
9162   }
9163
9164   // If we reach here, they do have operations in common.
9165   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9166                                          OtherOpF, SI.getName()+".v");
9167   InsertNewInstBefore(NewSI, SI);
9168
9169   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9170     if (MatchIsOpZero)
9171       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9172     else
9173       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9174   }
9175   llvm_unreachable("Shouldn't get here");
9176   return 0;
9177 }
9178
9179 static bool isSelect01(Constant *C1, Constant *C2) {
9180   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9181   if (!C1I)
9182     return false;
9183   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9184   if (!C2I)
9185     return false;
9186   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9187 }
9188
9189 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9190 /// facilitate further optimization.
9191 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9192                                             Value *FalseVal) {
9193   // See the comment above GetSelectFoldableOperands for a description of the
9194   // transformation we are doing here.
9195   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9196     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9197         !isa<Constant>(FalseVal)) {
9198       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9199         unsigned OpToFold = 0;
9200         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9201           OpToFold = 1;
9202         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9203           OpToFold = 2;
9204         }
9205
9206         if (OpToFold) {
9207           Constant *C = GetSelectFoldableConstant(TVI, Context);
9208           Value *OOp = TVI->getOperand(2-OpToFold);
9209           // Avoid creating select between 2 constants unless it's selecting
9210           // between 0 and 1.
9211           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9212             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9213             InsertNewInstBefore(NewSel, SI);
9214             NewSel->takeName(TVI);
9215             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9216               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9217             llvm_unreachable("Unknown instruction!!");
9218           }
9219         }
9220       }
9221     }
9222   }
9223
9224   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9225     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9226         !isa<Constant>(TrueVal)) {
9227       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9228         unsigned OpToFold = 0;
9229         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9230           OpToFold = 1;
9231         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9232           OpToFold = 2;
9233         }
9234
9235         if (OpToFold) {
9236           Constant *C = GetSelectFoldableConstant(FVI, Context);
9237           Value *OOp = FVI->getOperand(2-OpToFold);
9238           // Avoid creating select between 2 constants unless it's selecting
9239           // between 0 and 1.
9240           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9241             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9242             InsertNewInstBefore(NewSel, SI);
9243             NewSel->takeName(FVI);
9244             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9245               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9246             llvm_unreachable("Unknown instruction!!");
9247           }
9248         }
9249       }
9250     }
9251   }
9252
9253   return 0;
9254 }
9255
9256 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9257 /// ICmpInst as its first operand.
9258 ///
9259 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9260                                                    ICmpInst *ICI) {
9261   bool Changed = false;
9262   ICmpInst::Predicate Pred = ICI->getPredicate();
9263   Value *CmpLHS = ICI->getOperand(0);
9264   Value *CmpRHS = ICI->getOperand(1);
9265   Value *TrueVal = SI.getTrueValue();
9266   Value *FalseVal = SI.getFalseValue();
9267
9268   // Check cases where the comparison is with a constant that
9269   // can be adjusted to fit the min/max idiom. We may edit ICI in
9270   // place here, so make sure the select is the only user.
9271   if (ICI->hasOneUse())
9272     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9273       switch (Pred) {
9274       default: break;
9275       case ICmpInst::ICMP_ULT:
9276       case ICmpInst::ICMP_SLT: {
9277         // X < MIN ? T : F  -->  F
9278         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9279           return ReplaceInstUsesWith(SI, FalseVal);
9280         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9281         Constant *AdjustedRHS = SubOne(CI, Context);
9282         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9283             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9284           Pred = ICmpInst::getSwappedPredicate(Pred);
9285           CmpRHS = AdjustedRHS;
9286           std::swap(FalseVal, TrueVal);
9287           ICI->setPredicate(Pred);
9288           ICI->setOperand(1, CmpRHS);
9289           SI.setOperand(1, TrueVal);
9290           SI.setOperand(2, FalseVal);
9291           Changed = true;
9292         }
9293         break;
9294       }
9295       case ICmpInst::ICMP_UGT:
9296       case ICmpInst::ICMP_SGT: {
9297         // X > MAX ? T : F  -->  F
9298         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9299           return ReplaceInstUsesWith(SI, FalseVal);
9300         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9301         Constant *AdjustedRHS = AddOne(CI, Context);
9302         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9303             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9304           Pred = ICmpInst::getSwappedPredicate(Pred);
9305           CmpRHS = AdjustedRHS;
9306           std::swap(FalseVal, TrueVal);
9307           ICI->setPredicate(Pred);
9308           ICI->setOperand(1, CmpRHS);
9309           SI.setOperand(1, TrueVal);
9310           SI.setOperand(2, FalseVal);
9311           Changed = true;
9312         }
9313         break;
9314       }
9315       }
9316
9317       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9318       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9319       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9320       if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9321           match(FalseVal, m_ConstantInt<0>(), *Context))
9322         Pred = ICI->getPredicate();
9323       else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9324                match(FalseVal, m_ConstantInt<-1>(), *Context))
9325         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9326       
9327       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9328         // If we are just checking for a icmp eq of a single bit and zext'ing it
9329         // to an integer, then shift the bit to the appropriate place and then
9330         // cast to integer to avoid the comparison.
9331         const APInt &Op1CV = CI->getValue();
9332     
9333         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9334         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9335         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9336             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9337           Value *In = ICI->getOperand(0);
9338           Value *Sh = Context->getConstantInt(In->getType(),
9339                                        In->getType()->getScalarSizeInBits()-1);
9340           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9341                                                           In->getName()+".lobit"),
9342                                    *ICI);
9343           if (In->getType() != SI.getType())
9344             In = CastInst::CreateIntegerCast(In, SI.getType(),
9345                                              true/*SExt*/, "tmp", ICI);
9346     
9347           if (Pred == ICmpInst::ICMP_SGT)
9348             In = InsertNewInstBefore(BinaryOperator::CreateNot(*Context, In,
9349                                        In->getName()+".not"), *ICI);
9350     
9351           return ReplaceInstUsesWith(SI, In);
9352         }
9353       }
9354     }
9355
9356   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9357     // Transform (X == Y) ? X : Y  -> Y
9358     if (Pred == ICmpInst::ICMP_EQ)
9359       return ReplaceInstUsesWith(SI, FalseVal);
9360     // Transform (X != Y) ? X : Y  -> X
9361     if (Pred == ICmpInst::ICMP_NE)
9362       return ReplaceInstUsesWith(SI, TrueVal);
9363     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9364
9365   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9366     // Transform (X == Y) ? Y : X  -> X
9367     if (Pred == ICmpInst::ICMP_EQ)
9368       return ReplaceInstUsesWith(SI, FalseVal);
9369     // Transform (X != Y) ? Y : X  -> Y
9370     if (Pred == ICmpInst::ICMP_NE)
9371       return ReplaceInstUsesWith(SI, TrueVal);
9372     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9373   }
9374
9375   /// NOTE: if we wanted to, this is where to detect integer ABS
9376
9377   return Changed ? &SI : 0;
9378 }
9379
9380 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9381   Value *CondVal = SI.getCondition();
9382   Value *TrueVal = SI.getTrueValue();
9383   Value *FalseVal = SI.getFalseValue();
9384
9385   // select true, X, Y  -> X
9386   // select false, X, Y -> Y
9387   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9388     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9389
9390   // select C, X, X -> X
9391   if (TrueVal == FalseVal)
9392     return ReplaceInstUsesWith(SI, TrueVal);
9393
9394   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9395     return ReplaceInstUsesWith(SI, FalseVal);
9396   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9397     return ReplaceInstUsesWith(SI, TrueVal);
9398   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9399     if (isa<Constant>(TrueVal))
9400       return ReplaceInstUsesWith(SI, TrueVal);
9401     else
9402       return ReplaceInstUsesWith(SI, FalseVal);
9403   }
9404
9405   if (SI.getType() == Type::Int1Ty) {
9406     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9407       if (C->getZExtValue()) {
9408         // Change: A = select B, true, C --> A = or B, C
9409         return BinaryOperator::CreateOr(CondVal, FalseVal);
9410       } else {
9411         // Change: A = select B, false, C --> A = and !B, C
9412         Value *NotCond =
9413           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9414                                              "not."+CondVal->getName()), SI);
9415         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9416       }
9417     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9418       if (C->getZExtValue() == false) {
9419         // Change: A = select B, C, false --> A = and B, C
9420         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9421       } else {
9422         // Change: A = select B, C, true --> A = or !B, C
9423         Value *NotCond =
9424           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9425                                              "not."+CondVal->getName()), SI);
9426         return BinaryOperator::CreateOr(NotCond, TrueVal);
9427       }
9428     }
9429     
9430     // select a, b, a  -> a&b
9431     // select a, a, b  -> a|b
9432     if (CondVal == TrueVal)
9433       return BinaryOperator::CreateOr(CondVal, FalseVal);
9434     else if (CondVal == FalseVal)
9435       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9436   }
9437
9438   // Selecting between two integer constants?
9439   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9440     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9441       // select C, 1, 0 -> zext C to int
9442       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9443         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9444       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9445         // select C, 0, 1 -> zext !C to int
9446         Value *NotCond =
9447           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9448                                                "not."+CondVal->getName()), SI);
9449         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9450       }
9451
9452       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9453         // If one of the constants is zero (we know they can't both be) and we
9454         // have an icmp instruction with zero, and we have an 'and' with the
9455         // non-constant value, eliminate this whole mess.  This corresponds to
9456         // cases like this: ((X & 27) ? 27 : 0)
9457         if (TrueValC->isZero() || FalseValC->isZero())
9458           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9459               cast<Constant>(IC->getOperand(1))->isNullValue())
9460             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9461               if (ICA->getOpcode() == Instruction::And &&
9462                   isa<ConstantInt>(ICA->getOperand(1)) &&
9463                   (ICA->getOperand(1) == TrueValC ||
9464                    ICA->getOperand(1) == FalseValC) &&
9465                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9466                 // Okay, now we know that everything is set up, we just don't
9467                 // know whether we have a icmp_ne or icmp_eq and whether the 
9468                 // true or false val is the zero.
9469                 bool ShouldNotVal = !TrueValC->isZero();
9470                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9471                 Value *V = ICA;
9472                 if (ShouldNotVal)
9473                   V = InsertNewInstBefore(BinaryOperator::Create(
9474                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9475                 return ReplaceInstUsesWith(SI, V);
9476               }
9477       }
9478     }
9479
9480   // See if we are selecting two values based on a comparison of the two values.
9481   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9482     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9483       // Transform (X == Y) ? X : Y  -> Y
9484       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9485         // This is not safe in general for floating point:  
9486         // consider X== -0, Y== +0.
9487         // It becomes safe if either operand is a nonzero constant.
9488         ConstantFP *CFPt, *CFPf;
9489         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9490               !CFPt->getValueAPF().isZero()) ||
9491             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9492              !CFPf->getValueAPF().isZero()))
9493         return ReplaceInstUsesWith(SI, FalseVal);
9494       }
9495       // Transform (X != Y) ? X : Y  -> X
9496       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9497         return ReplaceInstUsesWith(SI, TrueVal);
9498       // NOTE: if we wanted to, this is where to detect MIN/MAX
9499
9500     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9501       // Transform (X == Y) ? Y : X  -> X
9502       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9503         // This is not safe in general for floating point:  
9504         // consider X== -0, Y== +0.
9505         // It becomes safe if either operand is a nonzero constant.
9506         ConstantFP *CFPt, *CFPf;
9507         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9508               !CFPt->getValueAPF().isZero()) ||
9509             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9510              !CFPf->getValueAPF().isZero()))
9511           return ReplaceInstUsesWith(SI, FalseVal);
9512       }
9513       // Transform (X != Y) ? Y : X  -> Y
9514       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9515         return ReplaceInstUsesWith(SI, TrueVal);
9516       // NOTE: if we wanted to, this is where to detect MIN/MAX
9517     }
9518     // NOTE: if we wanted to, this is where to detect ABS
9519   }
9520
9521   // See if we are selecting two values based on a comparison of the two values.
9522   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9523     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9524       return Result;
9525
9526   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9527     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9528       if (TI->hasOneUse() && FI->hasOneUse()) {
9529         Instruction *AddOp = 0, *SubOp = 0;
9530
9531         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9532         if (TI->getOpcode() == FI->getOpcode())
9533           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9534             return IV;
9535
9536         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9537         // even legal for FP.
9538         if ((TI->getOpcode() == Instruction::Sub &&
9539              FI->getOpcode() == Instruction::Add) ||
9540             (TI->getOpcode() == Instruction::FSub &&
9541              FI->getOpcode() == Instruction::FAdd)) {
9542           AddOp = FI; SubOp = TI;
9543         } else if ((FI->getOpcode() == Instruction::Sub &&
9544                     TI->getOpcode() == Instruction::Add) ||
9545                    (FI->getOpcode() == Instruction::FSub &&
9546                     TI->getOpcode() == Instruction::FAdd)) {
9547           AddOp = TI; SubOp = FI;
9548         }
9549
9550         if (AddOp) {
9551           Value *OtherAddOp = 0;
9552           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9553             OtherAddOp = AddOp->getOperand(1);
9554           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9555             OtherAddOp = AddOp->getOperand(0);
9556           }
9557
9558           if (OtherAddOp) {
9559             // So at this point we know we have (Y -> OtherAddOp):
9560             //        select C, (add X, Y), (sub X, Z)
9561             Value *NegVal;  // Compute -Z
9562             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9563               NegVal = Context->getConstantExprNeg(C);
9564             } else {
9565               NegVal = InsertNewInstBefore(
9566                     BinaryOperator::CreateNeg(*Context, SubOp->getOperand(1),
9567                                               "tmp"), SI);
9568             }
9569
9570             Value *NewTrueOp = OtherAddOp;
9571             Value *NewFalseOp = NegVal;
9572             if (AddOp != TI)
9573               std::swap(NewTrueOp, NewFalseOp);
9574             Instruction *NewSel =
9575               SelectInst::Create(CondVal, NewTrueOp,
9576                                  NewFalseOp, SI.getName() + ".p");
9577
9578             NewSel = InsertNewInstBefore(NewSel, SI);
9579             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9580           }
9581         }
9582       }
9583
9584   // See if we can fold the select into one of our operands.
9585   if (SI.getType()->isInteger()) {
9586     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9587     if (FoldI)
9588       return FoldI;
9589   }
9590
9591   if (BinaryOperator::isNot(CondVal)) {
9592     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9593     SI.setOperand(1, FalseVal);
9594     SI.setOperand(2, TrueVal);
9595     return &SI;
9596   }
9597
9598   return 0;
9599 }
9600
9601 /// EnforceKnownAlignment - If the specified pointer points to an object that
9602 /// we control, modify the object's alignment to PrefAlign. This isn't
9603 /// often possible though. If alignment is important, a more reliable approach
9604 /// is to simply align all global variables and allocation instructions to
9605 /// their preferred alignment from the beginning.
9606 ///
9607 static unsigned EnforceKnownAlignment(Value *V,
9608                                       unsigned Align, unsigned PrefAlign) {
9609
9610   User *U = dyn_cast<User>(V);
9611   if (!U) return Align;
9612
9613   switch (Operator::getOpcode(U)) {
9614   default: break;
9615   case Instruction::BitCast:
9616     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9617   case Instruction::GetElementPtr: {
9618     // If all indexes are zero, it is just the alignment of the base pointer.
9619     bool AllZeroOperands = true;
9620     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9621       if (!isa<Constant>(*i) ||
9622           !cast<Constant>(*i)->isNullValue()) {
9623         AllZeroOperands = false;
9624         break;
9625       }
9626
9627     if (AllZeroOperands) {
9628       // Treat this like a bitcast.
9629       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9630     }
9631     break;
9632   }
9633   }
9634
9635   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9636     // If there is a large requested alignment and we can, bump up the alignment
9637     // of the global.
9638     if (!GV->isDeclaration()) {
9639       if (GV->getAlignment() >= PrefAlign)
9640         Align = GV->getAlignment();
9641       else {
9642         GV->setAlignment(PrefAlign);
9643         Align = PrefAlign;
9644       }
9645     }
9646   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9647     // If there is a requested alignment and if this is an alloca, round up.  We
9648     // don't do this for malloc, because some systems can't respect the request.
9649     if (isa<AllocaInst>(AI)) {
9650       if (AI->getAlignment() >= PrefAlign)
9651         Align = AI->getAlignment();
9652       else {
9653         AI->setAlignment(PrefAlign);
9654         Align = PrefAlign;
9655       }
9656     }
9657   }
9658
9659   return Align;
9660 }
9661
9662 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9663 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9664 /// and it is more than the alignment of the ultimate object, see if we can
9665 /// increase the alignment of the ultimate object, making this check succeed.
9666 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9667                                                   unsigned PrefAlign) {
9668   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9669                       sizeof(PrefAlign) * CHAR_BIT;
9670   APInt Mask = APInt::getAllOnesValue(BitWidth);
9671   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9672   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9673   unsigned TrailZ = KnownZero.countTrailingOnes();
9674   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9675
9676   if (PrefAlign > Align)
9677     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9678   
9679     // We don't need to make any adjustment.
9680   return Align;
9681 }
9682
9683 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9684   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9685   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9686   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9687   unsigned CopyAlign = MI->getAlignment();
9688
9689   if (CopyAlign < MinAlign) {
9690     MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(), 
9691                                              MinAlign, false));
9692     return MI;
9693   }
9694   
9695   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9696   // load/store.
9697   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9698   if (MemOpLength == 0) return 0;
9699   
9700   // Source and destination pointer types are always "i8*" for intrinsic.  See
9701   // if the size is something we can handle with a single primitive load/store.
9702   // A single load+store correctly handles overlapping memory in the memmove
9703   // case.
9704   unsigned Size = MemOpLength->getZExtValue();
9705   if (Size == 0) return MI;  // Delete this mem transfer.
9706   
9707   if (Size > 8 || (Size&(Size-1)))
9708     return 0;  // If not 1/2/4/8 bytes, exit.
9709   
9710   // Use an integer load+store unless we can find something better.
9711   Type *NewPtrTy =
9712                 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
9713   
9714   // Memcpy forces the use of i8* for the source and destination.  That means
9715   // that if you're using memcpy to move one double around, you'll get a cast
9716   // from double* to i8*.  We'd much rather use a double load+store rather than
9717   // an i64 load+store, here because this improves the odds that the source or
9718   // dest address will be promotable.  See if we can find a better type than the
9719   // integer datatype.
9720   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9721     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9722     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9723       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9724       // down through these levels if so.
9725       while (!SrcETy->isSingleValueType()) {
9726         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9727           if (STy->getNumElements() == 1)
9728             SrcETy = STy->getElementType(0);
9729           else
9730             break;
9731         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9732           if (ATy->getNumElements() == 1)
9733             SrcETy = ATy->getElementType();
9734           else
9735             break;
9736         } else
9737           break;
9738       }
9739       
9740       if (SrcETy->isSingleValueType())
9741         NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
9742     }
9743   }
9744   
9745   
9746   // If the memcpy/memmove provides better alignment info than we can
9747   // infer, use it.
9748   SrcAlign = std::max(SrcAlign, CopyAlign);
9749   DstAlign = std::max(DstAlign, CopyAlign);
9750   
9751   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9752   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9753   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9754   InsertNewInstBefore(L, *MI);
9755   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9756
9757   // Set the size of the copy to 0, it will be deleted on the next iteration.
9758   MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
9759   return MI;
9760 }
9761
9762 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9763   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9764   if (MI->getAlignment() < Alignment) {
9765     MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9766                                              Alignment, false));
9767     return MI;
9768   }
9769   
9770   // Extract the length and alignment and fill if they are constant.
9771   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9772   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9773   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9774     return 0;
9775   uint64_t Len = LenC->getZExtValue();
9776   Alignment = MI->getAlignment();
9777   
9778   // If the length is zero, this is a no-op
9779   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9780   
9781   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9782   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9783     const Type *ITy = Context->getIntegerType(Len*8);  // n=1 -> i8.
9784     
9785     Value *Dest = MI->getDest();
9786     Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
9787
9788     // Alignment 0 is identity for alignment 1 for memset, but not store.
9789     if (Alignment == 0) Alignment = 1;
9790     
9791     // Extract the fill value and store.
9792     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9793     InsertNewInstBefore(new StoreInst(Context->getConstantInt(ITy, Fill),
9794                                       Dest, false, Alignment), *MI);
9795     
9796     // Set the size of the copy to 0, it will be deleted on the next iteration.
9797     MI->setLength(Context->getNullValue(LenC->getType()));
9798     return MI;
9799   }
9800
9801   return 0;
9802 }
9803
9804
9805 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9806 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9807 /// the heavy lifting.
9808 ///
9809 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9810   // If the caller function is nounwind, mark the call as nounwind, even if the
9811   // callee isn't.
9812   if (CI.getParent()->getParent()->doesNotThrow() &&
9813       !CI.doesNotThrow()) {
9814     CI.setDoesNotThrow();
9815     return &CI;
9816   }
9817   
9818   
9819   
9820   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9821   if (!II) return visitCallSite(&CI);
9822   
9823   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9824   // visitCallSite.
9825   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9826     bool Changed = false;
9827
9828     // memmove/cpy/set of zero bytes is a noop.
9829     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9830       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9831
9832       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9833         if (CI->getZExtValue() == 1) {
9834           // Replace the instruction with just byte operations.  We would
9835           // transform other cases to loads/stores, but we don't know if
9836           // alignment is sufficient.
9837         }
9838     }
9839
9840     // If we have a memmove and the source operation is a constant global,
9841     // then the source and dest pointers can't alias, so we can change this
9842     // into a call to memcpy.
9843     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9844       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9845         if (GVSrc->isConstant()) {
9846           Module *M = CI.getParent()->getParent()->getParent();
9847           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9848           const Type *Tys[1];
9849           Tys[0] = CI.getOperand(3)->getType();
9850           CI.setOperand(0, 
9851                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9852           Changed = true;
9853         }
9854
9855       // memmove(x,x,size) -> noop.
9856       if (MMI->getSource() == MMI->getDest())
9857         return EraseInstFromFunction(CI);
9858     }
9859
9860     // If we can determine a pointer alignment that is bigger than currently
9861     // set, update the alignment.
9862     if (isa<MemTransferInst>(MI)) {
9863       if (Instruction *I = SimplifyMemTransfer(MI))
9864         return I;
9865     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9866       if (Instruction *I = SimplifyMemSet(MSI))
9867         return I;
9868     }
9869           
9870     if (Changed) return II;
9871   }
9872   
9873   switch (II->getIntrinsicID()) {
9874   default: break;
9875   case Intrinsic::bswap:
9876     // bswap(bswap(x)) -> x
9877     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9878       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9879         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9880     break;
9881   case Intrinsic::ppc_altivec_lvx:
9882   case Intrinsic::ppc_altivec_lvxl:
9883   case Intrinsic::x86_sse_loadu_ps:
9884   case Intrinsic::x86_sse2_loadu_pd:
9885   case Intrinsic::x86_sse2_loadu_dq:
9886     // Turn PPC lvx     -> load if the pointer is known aligned.
9887     // Turn X86 loadups -> load if the pointer is known aligned.
9888     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9889       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9890                                    Context->getPointerTypeUnqual(II->getType()),
9891                                        CI);
9892       return new LoadInst(Ptr);
9893     }
9894     break;
9895   case Intrinsic::ppc_altivec_stvx:
9896   case Intrinsic::ppc_altivec_stvxl:
9897     // Turn stvx -> store if the pointer is known aligned.
9898     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9899       const Type *OpPtrTy = 
9900         Context->getPointerTypeUnqual(II->getOperand(1)->getType());
9901       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9902       return new StoreInst(II->getOperand(1), Ptr);
9903     }
9904     break;
9905   case Intrinsic::x86_sse_storeu_ps:
9906   case Intrinsic::x86_sse2_storeu_pd:
9907   case Intrinsic::x86_sse2_storeu_dq:
9908     // Turn X86 storeu -> store if the pointer is known aligned.
9909     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9910       const Type *OpPtrTy = 
9911         Context->getPointerTypeUnqual(II->getOperand(2)->getType());
9912       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9913       return new StoreInst(II->getOperand(2), Ptr);
9914     }
9915     break;
9916     
9917   case Intrinsic::x86_sse_cvttss2si: {
9918     // These intrinsics only demands the 0th element of its input vector.  If
9919     // we can simplify the input based on that, do so now.
9920     unsigned VWidth =
9921       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9922     APInt DemandedElts(VWidth, 1);
9923     APInt UndefElts(VWidth, 0);
9924     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9925                                               UndefElts)) {
9926       II->setOperand(1, V);
9927       return II;
9928     }
9929     break;
9930   }
9931     
9932   case Intrinsic::ppc_altivec_vperm:
9933     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9934     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9935       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9936       
9937       // Check that all of the elements are integer constants or undefs.
9938       bool AllEltsOk = true;
9939       for (unsigned i = 0; i != 16; ++i) {
9940         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9941             !isa<UndefValue>(Mask->getOperand(i))) {
9942           AllEltsOk = false;
9943           break;
9944         }
9945       }
9946       
9947       if (AllEltsOk) {
9948         // Cast the input vectors to byte vectors.
9949         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9950         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9951         Value *Result = Context->getUndef(Op0->getType());
9952         
9953         // Only extract each element once.
9954         Value *ExtractedElts[32];
9955         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9956         
9957         for (unsigned i = 0; i != 16; ++i) {
9958           if (isa<UndefValue>(Mask->getOperand(i)))
9959             continue;
9960           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9961           Idx &= 31;  // Match the hardware behavior.
9962           
9963           if (ExtractedElts[Idx] == 0) {
9964             Instruction *Elt = 
9965               new ExtractElementInst(Idx < 16 ? Op0 : Op1, 
9966                   Context->getConstantInt(Type::Int32Ty, Idx&15, false), "tmp");
9967             InsertNewInstBefore(Elt, CI);
9968             ExtractedElts[Idx] = Elt;
9969           }
9970         
9971           // Insert this value into the result vector.
9972           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9973                                Context->getConstantInt(Type::Int32Ty, i, false), 
9974                                "tmp");
9975           InsertNewInstBefore(cast<Instruction>(Result), CI);
9976         }
9977         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9978       }
9979     }
9980     break;
9981
9982   case Intrinsic::stackrestore: {
9983     // If the save is right next to the restore, remove the restore.  This can
9984     // happen when variable allocas are DCE'd.
9985     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9986       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9987         BasicBlock::iterator BI = SS;
9988         if (&*++BI == II)
9989           return EraseInstFromFunction(CI);
9990       }
9991     }
9992     
9993     // Scan down this block to see if there is another stack restore in the
9994     // same block without an intervening call/alloca.
9995     BasicBlock::iterator BI = II;
9996     TerminatorInst *TI = II->getParent()->getTerminator();
9997     bool CannotRemove = false;
9998     for (++BI; &*BI != TI; ++BI) {
9999       if (isa<AllocaInst>(BI)) {
10000         CannotRemove = true;
10001         break;
10002       }
10003       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10004         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10005           // If there is a stackrestore below this one, remove this one.
10006           if (II->getIntrinsicID() == Intrinsic::stackrestore)
10007             return EraseInstFromFunction(CI);
10008           // Otherwise, ignore the intrinsic.
10009         } else {
10010           // If we found a non-intrinsic call, we can't remove the stack
10011           // restore.
10012           CannotRemove = true;
10013           break;
10014         }
10015       }
10016     }
10017     
10018     // If the stack restore is in a return/unwind block and if there are no
10019     // allocas or calls between the restore and the return, nuke the restore.
10020     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10021       return EraseInstFromFunction(CI);
10022     break;
10023   }
10024   }
10025
10026   return visitCallSite(II);
10027 }
10028
10029 // InvokeInst simplification
10030 //
10031 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10032   return visitCallSite(&II);
10033 }
10034
10035 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
10036 /// passed through the varargs area, we can eliminate the use of the cast.
10037 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10038                                          const CastInst * const CI,
10039                                          const TargetData * const TD,
10040                                          const int ix) {
10041   if (!CI->isLosslessCast())
10042     return false;
10043
10044   // The size of ByVal arguments is derived from the type, so we
10045   // can't change to a type with a different size.  If the size were
10046   // passed explicitly we could avoid this check.
10047   if (!CS.paramHasAttr(ix, Attribute::ByVal))
10048     return true;
10049
10050   const Type* SrcTy = 
10051             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10052   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10053   if (!SrcTy->isSized() || !DstTy->isSized())
10054     return false;
10055   if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10056     return false;
10057   return true;
10058 }
10059
10060 // visitCallSite - Improvements for call and invoke instructions.
10061 //
10062 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10063   bool Changed = false;
10064
10065   // If the callee is a constexpr cast of a function, attempt to move the cast
10066   // to the arguments of the call/invoke.
10067   if (transformConstExprCastCall(CS)) return 0;
10068
10069   Value *Callee = CS.getCalledValue();
10070
10071   if (Function *CalleeF = dyn_cast<Function>(Callee))
10072     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10073       Instruction *OldCall = CS.getInstruction();
10074       // If the call and callee calling conventions don't match, this call must
10075       // be unreachable, as the call is undefined.
10076       new StoreInst(Context->getConstantIntTrue(),
10077                 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), 
10078                                   OldCall);
10079       if (!OldCall->use_empty())
10080         OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
10081       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10082         return EraseInstFromFunction(*OldCall);
10083       return 0;
10084     }
10085
10086   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10087     // This instruction is not reachable, just remove it.  We insert a store to
10088     // undef so that we know that this code is not reachable, despite the fact
10089     // that we can't modify the CFG here.
10090     new StoreInst(Context->getConstantIntTrue(),
10091                Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10092                   CS.getInstruction());
10093
10094     if (!CS.getInstruction()->use_empty())
10095       CS.getInstruction()->
10096         replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
10097
10098     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10099       // Don't break the CFG, insert a dummy cond branch.
10100       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10101                          Context->getConstantIntTrue(), II);
10102     }
10103     return EraseInstFromFunction(*CS.getInstruction());
10104   }
10105
10106   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10107     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10108       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10109         return transformCallThroughTrampoline(CS);
10110
10111   const PointerType *PTy = cast<PointerType>(Callee->getType());
10112   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10113   if (FTy->isVarArg()) {
10114     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10115     // See if we can optimize any arguments passed through the varargs area of
10116     // the call.
10117     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10118            E = CS.arg_end(); I != E; ++I, ++ix) {
10119       CastInst *CI = dyn_cast<CastInst>(*I);
10120       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10121         *I = CI->getOperand(0);
10122         Changed = true;
10123       }
10124     }
10125   }
10126
10127   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10128     // Inline asm calls cannot throw - mark them 'nounwind'.
10129     CS.setDoesNotThrow();
10130     Changed = true;
10131   }
10132
10133   return Changed ? CS.getInstruction() : 0;
10134 }
10135
10136 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10137 // attempt to move the cast to the arguments of the call/invoke.
10138 //
10139 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10140   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10141   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10142   if (CE->getOpcode() != Instruction::BitCast || 
10143       !isa<Function>(CE->getOperand(0)))
10144     return false;
10145   Function *Callee = cast<Function>(CE->getOperand(0));
10146   Instruction *Caller = CS.getInstruction();
10147   const AttrListPtr &CallerPAL = CS.getAttributes();
10148
10149   // Okay, this is a cast from a function to a different type.  Unless doing so
10150   // would cause a type conversion of one of our arguments, change this call to
10151   // be a direct call with arguments casted to the appropriate types.
10152   //
10153   const FunctionType *FT = Callee->getFunctionType();
10154   const Type *OldRetTy = Caller->getType();
10155   const Type *NewRetTy = FT->getReturnType();
10156
10157   if (isa<StructType>(NewRetTy))
10158     return false; // TODO: Handle multiple return values.
10159
10160   // Check to see if we are changing the return type...
10161   if (OldRetTy != NewRetTy) {
10162     if (Callee->isDeclaration() &&
10163         // Conversion is ok if changing from one pointer type to another or from
10164         // a pointer to an integer of the same size.
10165         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
10166           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
10167       return false;   // Cannot transform this return value.
10168
10169     if (!Caller->use_empty() &&
10170         // void -> non-void is handled specially
10171         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
10172       return false;   // Cannot transform this return value.
10173
10174     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10175       Attributes RAttrs = CallerPAL.getRetAttributes();
10176       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10177         return false;   // Attribute not compatible with transformed value.
10178     }
10179
10180     // If the callsite is an invoke instruction, and the return value is used by
10181     // a PHI node in a successor, we cannot change the return type of the call
10182     // because there is no place to put the cast instruction (without breaking
10183     // the critical edge).  Bail out in this case.
10184     if (!Caller->use_empty())
10185       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10186         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10187              UI != E; ++UI)
10188           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10189             if (PN->getParent() == II->getNormalDest() ||
10190                 PN->getParent() == II->getUnwindDest())
10191               return false;
10192   }
10193
10194   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10195   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10196
10197   CallSite::arg_iterator AI = CS.arg_begin();
10198   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10199     const Type *ParamTy = FT->getParamType(i);
10200     const Type *ActTy = (*AI)->getType();
10201
10202     if (!CastInst::isCastable(ActTy, ParamTy))
10203       return false;   // Cannot transform this parameter value.
10204
10205     if (CallerPAL.getParamAttributes(i + 1) 
10206         & Attribute::typeIncompatible(ParamTy))
10207       return false;   // Attribute not compatible with transformed value.
10208
10209     // Converting from one pointer type to another or between a pointer and an
10210     // integer of the same size is safe even if we do not have a body.
10211     bool isConvertible = ActTy == ParamTy ||
10212       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10213        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
10214     if (Callee->isDeclaration() && !isConvertible) return false;
10215   }
10216
10217   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10218       Callee->isDeclaration())
10219     return false;   // Do not delete arguments unless we have a function body.
10220
10221   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10222       !CallerPAL.isEmpty())
10223     // In this case we have more arguments than the new function type, but we
10224     // won't be dropping them.  Check that these extra arguments have attributes
10225     // that are compatible with being a vararg call argument.
10226     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10227       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10228         break;
10229       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10230       if (PAttrs & Attribute::VarArgsIncompatible)
10231         return false;
10232     }
10233
10234   // Okay, we decided that this is a safe thing to do: go ahead and start
10235   // inserting cast instructions as necessary...
10236   std::vector<Value*> Args;
10237   Args.reserve(NumActualArgs);
10238   SmallVector<AttributeWithIndex, 8> attrVec;
10239   attrVec.reserve(NumCommonArgs);
10240
10241   // Get any return attributes.
10242   Attributes RAttrs = CallerPAL.getRetAttributes();
10243
10244   // If the return value is not being used, the type may not be compatible
10245   // with the existing attributes.  Wipe out any problematic attributes.
10246   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10247
10248   // Add the new return attributes.
10249   if (RAttrs)
10250     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10251
10252   AI = CS.arg_begin();
10253   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10254     const Type *ParamTy = FT->getParamType(i);
10255     if ((*AI)->getType() == ParamTy) {
10256       Args.push_back(*AI);
10257     } else {
10258       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10259           false, ParamTy, false);
10260       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10261       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10262     }
10263
10264     // Add any parameter attributes.
10265     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10266       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10267   }
10268
10269   // If the function takes more arguments than the call was taking, add them
10270   // now...
10271   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10272     Args.push_back(Context->getNullValue(FT->getParamType(i)));
10273
10274   // If we are removing arguments to the function, emit an obnoxious warning...
10275   if (FT->getNumParams() < NumActualArgs) {
10276     if (!FT->isVarArg()) {
10277       cerr << "WARNING: While resolving call to function '"
10278            << Callee->getName() << "' arguments were dropped!\n";
10279     } else {
10280       // Add all of the arguments in their promoted form to the arg list...
10281       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10282         const Type *PTy = getPromotedType((*AI)->getType());
10283         if (PTy != (*AI)->getType()) {
10284           // Must promote to pass through va_arg area!
10285           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
10286                                                                 PTy, false);
10287           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10288           InsertNewInstBefore(Cast, *Caller);
10289           Args.push_back(Cast);
10290         } else {
10291           Args.push_back(*AI);
10292         }
10293
10294         // Add any parameter attributes.
10295         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10296           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10297       }
10298     }
10299   }
10300
10301   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10302     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10303
10304   if (NewRetTy == Type::VoidTy)
10305     Caller->setName("");   // Void type should not have a name.
10306
10307   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
10308
10309   Instruction *NC;
10310   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10311     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10312                             Args.begin(), Args.end(),
10313                             Caller->getName(), Caller);
10314     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10315     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10316   } else {
10317     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10318                           Caller->getName(), Caller);
10319     CallInst *CI = cast<CallInst>(Caller);
10320     if (CI->isTailCall())
10321       cast<CallInst>(NC)->setTailCall();
10322     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10323     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10324   }
10325
10326   // Insert a cast of the return type as necessary.
10327   Value *NV = NC;
10328   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10329     if (NV->getType() != Type::VoidTy) {
10330       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10331                                                             OldRetTy, false);
10332       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10333
10334       // If this is an invoke instruction, we should insert it after the first
10335       // non-phi, instruction in the normal successor block.
10336       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10337         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10338         InsertNewInstBefore(NC, *I);
10339       } else {
10340         // Otherwise, it's a call, just insert cast right after the call instr
10341         InsertNewInstBefore(NC, *Caller);
10342       }
10343       AddUsersToWorkList(*Caller);
10344     } else {
10345       NV = Context->getUndef(Caller->getType());
10346     }
10347   }
10348
10349   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10350     Caller->replaceAllUsesWith(NV);
10351   Caller->eraseFromParent();
10352   RemoveFromWorkList(Caller);
10353   return true;
10354 }
10355
10356 // transformCallThroughTrampoline - Turn a call to a function created by the
10357 // init_trampoline intrinsic into a direct call to the underlying function.
10358 //
10359 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10360   Value *Callee = CS.getCalledValue();
10361   const PointerType *PTy = cast<PointerType>(Callee->getType());
10362   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10363   const AttrListPtr &Attrs = CS.getAttributes();
10364
10365   // If the call already has the 'nest' attribute somewhere then give up -
10366   // otherwise 'nest' would occur twice after splicing in the chain.
10367   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10368     return 0;
10369
10370   IntrinsicInst *Tramp =
10371     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10372
10373   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10374   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10375   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10376
10377   const AttrListPtr &NestAttrs = NestF->getAttributes();
10378   if (!NestAttrs.isEmpty()) {
10379     unsigned NestIdx = 1;
10380     const Type *NestTy = 0;
10381     Attributes NestAttr = Attribute::None;
10382
10383     // Look for a parameter marked with the 'nest' attribute.
10384     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10385          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10386       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10387         // Record the parameter type and any other attributes.
10388         NestTy = *I;
10389         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10390         break;
10391       }
10392
10393     if (NestTy) {
10394       Instruction *Caller = CS.getInstruction();
10395       std::vector<Value*> NewArgs;
10396       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10397
10398       SmallVector<AttributeWithIndex, 8> NewAttrs;
10399       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10400
10401       // Insert the nest argument into the call argument list, which may
10402       // mean appending it.  Likewise for attributes.
10403
10404       // Add any result attributes.
10405       if (Attributes Attr = Attrs.getRetAttributes())
10406         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10407
10408       {
10409         unsigned Idx = 1;
10410         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10411         do {
10412           if (Idx == NestIdx) {
10413             // Add the chain argument and attributes.
10414             Value *NestVal = Tramp->getOperand(3);
10415             if (NestVal->getType() != NestTy)
10416               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10417             NewArgs.push_back(NestVal);
10418             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10419           }
10420
10421           if (I == E)
10422             break;
10423
10424           // Add the original argument and attributes.
10425           NewArgs.push_back(*I);
10426           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10427             NewAttrs.push_back
10428               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10429
10430           ++Idx, ++I;
10431         } while (1);
10432       }
10433
10434       // Add any function attributes.
10435       if (Attributes Attr = Attrs.getFnAttributes())
10436         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10437
10438       // The trampoline may have been bitcast to a bogus type (FTy).
10439       // Handle this by synthesizing a new function type, equal to FTy
10440       // with the chain parameter inserted.
10441
10442       std::vector<const Type*> NewTypes;
10443       NewTypes.reserve(FTy->getNumParams()+1);
10444
10445       // Insert the chain's type into the list of parameter types, which may
10446       // mean appending it.
10447       {
10448         unsigned Idx = 1;
10449         FunctionType::param_iterator I = FTy->param_begin(),
10450           E = FTy->param_end();
10451
10452         do {
10453           if (Idx == NestIdx)
10454             // Add the chain's type.
10455             NewTypes.push_back(NestTy);
10456
10457           if (I == E)
10458             break;
10459
10460           // Add the original type.
10461           NewTypes.push_back(*I);
10462
10463           ++Idx, ++I;
10464         } while (1);
10465       }
10466
10467       // Replace the trampoline call with a direct call.  Let the generic
10468       // code sort out any function type mismatches.
10469       FunctionType *NewFTy =
10470                        Context->getFunctionType(FTy->getReturnType(), NewTypes, 
10471                                                 FTy->isVarArg());
10472       Constant *NewCallee =
10473         NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10474         NestF : Context->getConstantExprBitCast(NestF, 
10475                                          Context->getPointerTypeUnqual(NewFTy));
10476       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
10477
10478       Instruction *NewCaller;
10479       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10480         NewCaller = InvokeInst::Create(NewCallee,
10481                                        II->getNormalDest(), II->getUnwindDest(),
10482                                        NewArgs.begin(), NewArgs.end(),
10483                                        Caller->getName(), Caller);
10484         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10485         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10486       } else {
10487         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10488                                      Caller->getName(), Caller);
10489         if (cast<CallInst>(Caller)->isTailCall())
10490           cast<CallInst>(NewCaller)->setTailCall();
10491         cast<CallInst>(NewCaller)->
10492           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10493         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10494       }
10495       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10496         Caller->replaceAllUsesWith(NewCaller);
10497       Caller->eraseFromParent();
10498       RemoveFromWorkList(Caller);
10499       return 0;
10500     }
10501   }
10502
10503   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10504   // parameter, there is no need to adjust the argument list.  Let the generic
10505   // code sort out any function type mismatches.
10506   Constant *NewCallee =
10507     NestF->getType() == PTy ? NestF : 
10508                               Context->getConstantExprBitCast(NestF, PTy);
10509   CS.setCalledFunction(NewCallee);
10510   return CS.getInstruction();
10511 }
10512
10513 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10514 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10515 /// and a single binop.
10516 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10517   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10518   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10519   unsigned Opc = FirstInst->getOpcode();
10520   Value *LHSVal = FirstInst->getOperand(0);
10521   Value *RHSVal = FirstInst->getOperand(1);
10522     
10523   const Type *LHSType = LHSVal->getType();
10524   const Type *RHSType = RHSVal->getType();
10525   
10526   // Scan to see if all operands are the same opcode, all have one use, and all
10527   // kill their operands (i.e. the operands have one use).
10528   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10529     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10530     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10531         // Verify type of the LHS matches so we don't fold cmp's of different
10532         // types or GEP's with different index types.
10533         I->getOperand(0)->getType() != LHSType ||
10534         I->getOperand(1)->getType() != RHSType)
10535       return 0;
10536
10537     // If they are CmpInst instructions, check their predicates
10538     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10539       if (cast<CmpInst>(I)->getPredicate() !=
10540           cast<CmpInst>(FirstInst)->getPredicate())
10541         return 0;
10542     
10543     // Keep track of which operand needs a phi node.
10544     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10545     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10546   }
10547   
10548   // Otherwise, this is safe to transform!
10549   
10550   Value *InLHS = FirstInst->getOperand(0);
10551   Value *InRHS = FirstInst->getOperand(1);
10552   PHINode *NewLHS = 0, *NewRHS = 0;
10553   if (LHSVal == 0) {
10554     NewLHS = PHINode::Create(LHSType,
10555                              FirstInst->getOperand(0)->getName() + ".pn");
10556     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10557     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10558     InsertNewInstBefore(NewLHS, PN);
10559     LHSVal = NewLHS;
10560   }
10561   
10562   if (RHSVal == 0) {
10563     NewRHS = PHINode::Create(RHSType,
10564                              FirstInst->getOperand(1)->getName() + ".pn");
10565     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10566     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10567     InsertNewInstBefore(NewRHS, PN);
10568     RHSVal = NewRHS;
10569   }
10570   
10571   // Add all operands to the new PHIs.
10572   if (NewLHS || NewRHS) {
10573     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10574       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10575       if (NewLHS) {
10576         Value *NewInLHS = InInst->getOperand(0);
10577         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10578       }
10579       if (NewRHS) {
10580         Value *NewInRHS = InInst->getOperand(1);
10581         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10582       }
10583     }
10584   }
10585     
10586   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10587     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10588   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10589   return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10590                          LHSVal, RHSVal);
10591 }
10592
10593 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10594   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10595   
10596   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10597                                         FirstInst->op_end());
10598   // This is true if all GEP bases are allocas and if all indices into them are
10599   // constants.
10600   bool AllBasePointersAreAllocas = true;
10601   
10602   // Scan to see if all operands are the same opcode, all have one use, and all
10603   // kill their operands (i.e. the operands have one use).
10604   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10605     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10606     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10607       GEP->getNumOperands() != FirstInst->getNumOperands())
10608       return 0;
10609
10610     // Keep track of whether or not all GEPs are of alloca pointers.
10611     if (AllBasePointersAreAllocas &&
10612         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10613          !GEP->hasAllConstantIndices()))
10614       AllBasePointersAreAllocas = false;
10615     
10616     // Compare the operand lists.
10617     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10618       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10619         continue;
10620       
10621       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10622       // if one of the PHIs has a constant for the index.  The index may be
10623       // substantially cheaper to compute for the constants, so making it a
10624       // variable index could pessimize the path.  This also handles the case
10625       // for struct indices, which must always be constant.
10626       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10627           isa<ConstantInt>(GEP->getOperand(op)))
10628         return 0;
10629       
10630       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10631         return 0;
10632       FixedOperands[op] = 0;  // Needs a PHI.
10633     }
10634   }
10635   
10636   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10637   // bother doing this transformation.  At best, this will just save a bit of
10638   // offset calculation, but all the predecessors will have to materialize the
10639   // stack address into a register anyway.  We'd actually rather *clone* the
10640   // load up into the predecessors so that we have a load of a gep of an alloca,
10641   // which can usually all be folded into the load.
10642   if (AllBasePointersAreAllocas)
10643     return 0;
10644   
10645   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10646   // that is variable.
10647   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10648   
10649   bool HasAnyPHIs = false;
10650   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10651     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10652     Value *FirstOp = FirstInst->getOperand(i);
10653     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10654                                      FirstOp->getName()+".pn");
10655     InsertNewInstBefore(NewPN, PN);
10656     
10657     NewPN->reserveOperandSpace(e);
10658     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10659     OperandPhis[i] = NewPN;
10660     FixedOperands[i] = NewPN;
10661     HasAnyPHIs = true;
10662   }
10663
10664   
10665   // Add all operands to the new PHIs.
10666   if (HasAnyPHIs) {
10667     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10668       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10669       BasicBlock *InBB = PN.getIncomingBlock(i);
10670       
10671       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10672         if (PHINode *OpPhi = OperandPhis[op])
10673           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10674     }
10675   }
10676   
10677   Value *Base = FixedOperands[0];
10678   return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10679                                    FixedOperands.end());
10680 }
10681
10682
10683 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10684 /// sink the load out of the block that defines it.  This means that it must be
10685 /// obvious the value of the load is not changed from the point of the load to
10686 /// the end of the block it is in.
10687 ///
10688 /// Finally, it is safe, but not profitable, to sink a load targetting a
10689 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10690 /// to a register.
10691 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10692   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10693   
10694   for (++BBI; BBI != E; ++BBI)
10695     if (BBI->mayWriteToMemory())
10696       return false;
10697   
10698   // Check for non-address taken alloca.  If not address-taken already, it isn't
10699   // profitable to do this xform.
10700   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10701     bool isAddressTaken = false;
10702     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10703          UI != E; ++UI) {
10704       if (isa<LoadInst>(UI)) continue;
10705       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10706         // If storing TO the alloca, then the address isn't taken.
10707         if (SI->getOperand(1) == AI) continue;
10708       }
10709       isAddressTaken = true;
10710       break;
10711     }
10712     
10713     if (!isAddressTaken && AI->isStaticAlloca())
10714       return false;
10715   }
10716   
10717   // If this load is a load from a GEP with a constant offset from an alloca,
10718   // then we don't want to sink it.  In its present form, it will be
10719   // load [constant stack offset].  Sinking it will cause us to have to
10720   // materialize the stack addresses in each predecessor in a register only to
10721   // do a shared load from register in the successor.
10722   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10723     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10724       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10725         return false;
10726   
10727   return true;
10728 }
10729
10730
10731 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10732 // operator and they all are only used by the PHI, PHI together their
10733 // inputs, and do the operation once, to the result of the PHI.
10734 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10735   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10736
10737   // Scan the instruction, looking for input operations that can be folded away.
10738   // If all input operands to the phi are the same instruction (e.g. a cast from
10739   // the same type or "+42") we can pull the operation through the PHI, reducing
10740   // code size and simplifying code.
10741   Constant *ConstantOp = 0;
10742   const Type *CastSrcTy = 0;
10743   bool isVolatile = false;
10744   if (isa<CastInst>(FirstInst)) {
10745     CastSrcTy = FirstInst->getOperand(0)->getType();
10746   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10747     // Can fold binop, compare or shift here if the RHS is a constant, 
10748     // otherwise call FoldPHIArgBinOpIntoPHI.
10749     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10750     if (ConstantOp == 0)
10751       return FoldPHIArgBinOpIntoPHI(PN);
10752   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10753     isVolatile = LI->isVolatile();
10754     // We can't sink the load if the loaded value could be modified between the
10755     // load and the PHI.
10756     if (LI->getParent() != PN.getIncomingBlock(0) ||
10757         !isSafeAndProfitableToSinkLoad(LI))
10758       return 0;
10759     
10760     // If the PHI is of volatile loads and the load block has multiple
10761     // successors, sinking it would remove a load of the volatile value from
10762     // the path through the other successor.
10763     if (isVolatile &&
10764         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10765       return 0;
10766     
10767   } else if (isa<GetElementPtrInst>(FirstInst)) {
10768     return FoldPHIArgGEPIntoPHI(PN);
10769   } else {
10770     return 0;  // Cannot fold this operation.
10771   }
10772
10773   // Check to see if all arguments are the same operation.
10774   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10775     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10776     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10777     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10778       return 0;
10779     if (CastSrcTy) {
10780       if (I->getOperand(0)->getType() != CastSrcTy)
10781         return 0;  // Cast operation must match.
10782     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10783       // We can't sink the load if the loaded value could be modified between 
10784       // the load and the PHI.
10785       if (LI->isVolatile() != isVolatile ||
10786           LI->getParent() != PN.getIncomingBlock(i) ||
10787           !isSafeAndProfitableToSinkLoad(LI))
10788         return 0;
10789       
10790       // If the PHI is of volatile loads and the load block has multiple
10791       // successors, sinking it would remove a load of the volatile value from
10792       // the path through the other successor.
10793       if (isVolatile &&
10794           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10795         return 0;
10796       
10797     } else if (I->getOperand(1) != ConstantOp) {
10798       return 0;
10799     }
10800   }
10801
10802   // Okay, they are all the same operation.  Create a new PHI node of the
10803   // correct type, and PHI together all of the LHS's of the instructions.
10804   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10805                                    PN.getName()+".in");
10806   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10807
10808   Value *InVal = FirstInst->getOperand(0);
10809   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10810
10811   // Add all operands to the new PHI.
10812   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10813     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10814     if (NewInVal != InVal)
10815       InVal = 0;
10816     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10817   }
10818
10819   Value *PhiVal;
10820   if (InVal) {
10821     // The new PHI unions all of the same values together.  This is really
10822     // common, so we handle it intelligently here for compile-time speed.
10823     PhiVal = InVal;
10824     delete NewPN;
10825   } else {
10826     InsertNewInstBefore(NewPN, PN);
10827     PhiVal = NewPN;
10828   }
10829
10830   // Insert and return the new operation.
10831   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10832     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10833   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10834     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10835   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10836     return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10837                            PhiVal, ConstantOp);
10838   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10839   
10840   // If this was a volatile load that we are merging, make sure to loop through
10841   // and mark all the input loads as non-volatile.  If we don't do this, we will
10842   // insert a new volatile load and the old ones will not be deletable.
10843   if (isVolatile)
10844     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10845       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10846   
10847   return new LoadInst(PhiVal, "", isVolatile);
10848 }
10849
10850 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10851 /// that is dead.
10852 static bool DeadPHICycle(PHINode *PN,
10853                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10854   if (PN->use_empty()) return true;
10855   if (!PN->hasOneUse()) return false;
10856
10857   // Remember this node, and if we find the cycle, return.
10858   if (!PotentiallyDeadPHIs.insert(PN))
10859     return true;
10860   
10861   // Don't scan crazily complex things.
10862   if (PotentiallyDeadPHIs.size() == 16)
10863     return false;
10864
10865   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10866     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10867
10868   return false;
10869 }
10870
10871 /// PHIsEqualValue - Return true if this phi node is always equal to
10872 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10873 ///   z = some value; x = phi (y, z); y = phi (x, z)
10874 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10875                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10876   // See if we already saw this PHI node.
10877   if (!ValueEqualPHIs.insert(PN))
10878     return true;
10879   
10880   // Don't scan crazily complex things.
10881   if (ValueEqualPHIs.size() == 16)
10882     return false;
10883  
10884   // Scan the operands to see if they are either phi nodes or are equal to
10885   // the value.
10886   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10887     Value *Op = PN->getIncomingValue(i);
10888     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10889       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10890         return false;
10891     } else if (Op != NonPhiInVal)
10892       return false;
10893   }
10894   
10895   return true;
10896 }
10897
10898
10899 // PHINode simplification
10900 //
10901 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10902   // If LCSSA is around, don't mess with Phi nodes
10903   if (MustPreserveLCSSA) return 0;
10904   
10905   if (Value *V = PN.hasConstantValue())
10906     return ReplaceInstUsesWith(PN, V);
10907
10908   // If all PHI operands are the same operation, pull them through the PHI,
10909   // reducing code size.
10910   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10911       isa<Instruction>(PN.getIncomingValue(1)) &&
10912       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10913       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10914       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10915       // than themselves more than once.
10916       PN.getIncomingValue(0)->hasOneUse())
10917     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10918       return Result;
10919
10920   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10921   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10922   // PHI)... break the cycle.
10923   if (PN.hasOneUse()) {
10924     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10925     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10926       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10927       PotentiallyDeadPHIs.insert(&PN);
10928       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10929         return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10930     }
10931    
10932     // If this phi has a single use, and if that use just computes a value for
10933     // the next iteration of a loop, delete the phi.  This occurs with unused
10934     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10935     // common case here is good because the only other things that catch this
10936     // are induction variable analysis (sometimes) and ADCE, which is only run
10937     // late.
10938     if (PHIUser->hasOneUse() &&
10939         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10940         PHIUser->use_back() == &PN) {
10941       return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10942     }
10943   }
10944
10945   // We sometimes end up with phi cycles that non-obviously end up being the
10946   // same value, for example:
10947   //   z = some value; x = phi (y, z); y = phi (x, z)
10948   // where the phi nodes don't necessarily need to be in the same block.  Do a
10949   // quick check to see if the PHI node only contains a single non-phi value, if
10950   // so, scan to see if the phi cycle is actually equal to that value.
10951   {
10952     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10953     // Scan for the first non-phi operand.
10954     while (InValNo != NumOperandVals && 
10955            isa<PHINode>(PN.getIncomingValue(InValNo)))
10956       ++InValNo;
10957
10958     if (InValNo != NumOperandVals) {
10959       Value *NonPhiInVal = PN.getOperand(InValNo);
10960       
10961       // Scan the rest of the operands to see if there are any conflicts, if so
10962       // there is no need to recursively scan other phis.
10963       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10964         Value *OpVal = PN.getIncomingValue(InValNo);
10965         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10966           break;
10967       }
10968       
10969       // If we scanned over all operands, then we have one unique value plus
10970       // phi values.  Scan PHI nodes to see if they all merge in each other or
10971       // the value.
10972       if (InValNo == NumOperandVals) {
10973         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10974         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10975           return ReplaceInstUsesWith(PN, NonPhiInVal);
10976       }
10977     }
10978   }
10979   return 0;
10980 }
10981
10982 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10983                                    Instruction *InsertPoint,
10984                                    InstCombiner *IC) {
10985   unsigned PtrSize = DTy->getScalarSizeInBits();
10986   unsigned VTySize = V->getType()->getScalarSizeInBits();
10987   // We must cast correctly to the pointer type. Ensure that we
10988   // sign extend the integer value if it is smaller as this is
10989   // used for address computation.
10990   Instruction::CastOps opcode = 
10991      (VTySize < PtrSize ? Instruction::SExt :
10992       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10993   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10994 }
10995
10996
10997 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10998   Value *PtrOp = GEP.getOperand(0);
10999   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
11000   // If so, eliminate the noop.
11001   if (GEP.getNumOperands() == 1)
11002     return ReplaceInstUsesWith(GEP, PtrOp);
11003
11004   if (isa<UndefValue>(GEP.getOperand(0)))
11005     return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
11006
11007   bool HasZeroPointerIndex = false;
11008   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11009     HasZeroPointerIndex = C->isNullValue();
11010
11011   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11012     return ReplaceInstUsesWith(GEP, PtrOp);
11013
11014   // Eliminate unneeded casts for indices.
11015   bool MadeChange = false;
11016   
11017   gep_type_iterator GTI = gep_type_begin(GEP);
11018   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11019        i != e; ++i, ++GTI) {
11020     if (isa<SequentialType>(*GTI)) {
11021       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
11022         if (CI->getOpcode() == Instruction::ZExt ||
11023             CI->getOpcode() == Instruction::SExt) {
11024           const Type *SrcTy = CI->getOperand(0)->getType();
11025           // We can eliminate a cast from i32 to i64 iff the target 
11026           // is a 32-bit pointer target.
11027           if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
11028             MadeChange = true;
11029             *i = CI->getOperand(0);
11030           }
11031         }
11032       }
11033       // If we are using a wider index than needed for this platform, shrink it
11034       // to what we need.  If narrower, sign-extend it to what we need.
11035       // If the incoming value needs a cast instruction,
11036       // insert it.  This explicit cast can make subsequent optimizations more
11037       // obvious.
11038       Value *Op = *i;
11039       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
11040         if (Constant *C = dyn_cast<Constant>(Op)) {
11041           *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
11042           MadeChange = true;
11043         } else {
11044           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11045                                 GEP);
11046           *i = Op;
11047           MadeChange = true;
11048         }
11049       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
11050         if (Constant *C = dyn_cast<Constant>(Op)) {
11051           *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
11052           MadeChange = true;
11053         } else {
11054           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11055                                 GEP);
11056           *i = Op;
11057           MadeChange = true;
11058         }
11059       }
11060     }
11061   }
11062   if (MadeChange) return &GEP;
11063
11064   // Combine Indices - If the source pointer to this getelementptr instruction
11065   // is a getelementptr instruction, combine the indices of the two
11066   // getelementptr instructions into a single instruction.
11067   //
11068   SmallVector<Value*, 8> SrcGEPOperands;
11069   if (User *Src = dyn_castGetElementPtr(PtrOp))
11070     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
11071
11072   if (!SrcGEPOperands.empty()) {
11073     // Note that if our source is a gep chain itself that we wait for that
11074     // chain to be resolved before we perform this transformation.  This
11075     // avoids us creating a TON of code in some cases.
11076     //
11077     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11078         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11079       return 0;   // Wait until our source is folded to completion.
11080
11081     SmallVector<Value*, 8> Indices;
11082
11083     // Find out whether the last index in the source GEP is a sequential idx.
11084     bool EndsWithSequential = false;
11085     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11086            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11087       EndsWithSequential = !isa<StructType>(*I);
11088
11089     // Can we combine the two pointer arithmetics offsets?
11090     if (EndsWithSequential) {
11091       // Replace: gep (gep %P, long B), long A, ...
11092       // With:    T = long A+B; gep %P, T, ...
11093       //
11094       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
11095       if (SO1 == Context->getNullValue(SO1->getType())) {
11096         Sum = GO1;
11097       } else if (GO1 == Context->getNullValue(GO1->getType())) {
11098         Sum = SO1;
11099       } else {
11100         // If they aren't the same type, convert both to an integer of the
11101         // target's pointer size.
11102         if (SO1->getType() != GO1->getType()) {
11103           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
11104             SO1 =
11105                 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
11106           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
11107             GO1 =
11108                 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
11109           } else {
11110             unsigned PS = TD->getPointerSizeInBits();
11111             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
11112               // Convert GO1 to SO1's type.
11113               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11114
11115             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
11116               // Convert SO1 to GO1's type.
11117               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11118             } else {
11119               const Type *PT = TD->getIntPtrType();
11120               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11121               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11122             }
11123           }
11124         }
11125         if (isa<Constant>(SO1) && isa<Constant>(GO1))
11126           Sum = Context->getConstantExprAdd(cast<Constant>(SO1), 
11127                                             cast<Constant>(GO1));
11128         else {
11129           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11130           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11131         }
11132       }
11133
11134       // Recycle the GEP we already have if possible.
11135       if (SrcGEPOperands.size() == 2) {
11136         GEP.setOperand(0, SrcGEPOperands[0]);
11137         GEP.setOperand(1, Sum);
11138         return &GEP;
11139       } else {
11140         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11141                        SrcGEPOperands.end()-1);
11142         Indices.push_back(Sum);
11143         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11144       }
11145     } else if (isa<Constant>(*GEP.idx_begin()) &&
11146                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11147                SrcGEPOperands.size() != 1) {
11148       // Otherwise we can do the fold if the first index of the GEP is a zero
11149       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11150                      SrcGEPOperands.end());
11151       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11152     }
11153
11154     if (!Indices.empty())
11155       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11156                                        Indices.end(), GEP.getName());
11157
11158   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11159     // GEP of global variable.  If all of the indices for this GEP are
11160     // constants, we can promote this to a constexpr instead of an instruction.
11161
11162     // Scan for nonconstants...
11163     SmallVector<Constant*, 8> Indices;
11164     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11165     for (; I != E && isa<Constant>(*I); ++I)
11166       Indices.push_back(cast<Constant>(*I));
11167
11168     if (I == E) {  // If they are all constants...
11169       Constant *CE = Context->getConstantExprGetElementPtr(GV,
11170                                                     &Indices[0],Indices.size());
11171
11172       // Replace all uses of the GEP with the new constexpr...
11173       return ReplaceInstUsesWith(GEP, CE);
11174     }
11175   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
11176     if (!isa<PointerType>(X->getType())) {
11177       // Not interesting.  Source pointer must be a cast from pointer.
11178     } else if (HasZeroPointerIndex) {
11179       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11180       // into     : GEP [10 x i8]* X, i32 0, ...
11181       //
11182       // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11183       //           into     : GEP i8* X, ...
11184       // 
11185       // This occurs when the program declares an array extern like "int X[];"
11186       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11187       const PointerType *XTy = cast<PointerType>(X->getType());
11188       if (const ArrayType *CATy =
11189           dyn_cast<ArrayType>(CPTy->getElementType())) {
11190         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11191         if (CATy->getElementType() == XTy->getElementType()) {
11192           // -> GEP i8* X, ...
11193           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11194           return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11195                                            GEP.getName());
11196         } else if (const ArrayType *XATy =
11197                  dyn_cast<ArrayType>(XTy->getElementType())) {
11198           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11199           if (CATy->getElementType() == XATy->getElementType()) {
11200             // -> GEP [10 x i8]* X, i32 0, ...
11201             // At this point, we know that the cast source type is a pointer
11202             // to an array of the same type as the destination pointer
11203             // array.  Because the array type is never stepped over (there
11204             // is a leading zero) we can fold the cast into this GEP.
11205             GEP.setOperand(0, X);
11206             return &GEP;
11207           }
11208         }
11209       }
11210     } else if (GEP.getNumOperands() == 2) {
11211       // Transform things like:
11212       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11213       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11214       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11215       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11216       if (isa<ArrayType>(SrcElTy) &&
11217           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11218           TD->getTypeAllocSize(ResElTy)) {
11219         Value *Idx[2];
11220         Idx[0] = Context->getNullValue(Type::Int32Ty);
11221         Idx[1] = GEP.getOperand(1);
11222         Value *V = InsertNewInstBefore(
11223                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
11224         // V and GEP are both pointer types --> BitCast
11225         return new BitCastInst(V, GEP.getType());
11226       }
11227       
11228       // Transform things like:
11229       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11230       //   (where tmp = 8*tmp2) into:
11231       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11232       
11233       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
11234         uint64_t ArrayEltSize =
11235             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11236         
11237         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11238         // allow either a mul, shift, or constant here.
11239         Value *NewIdx = 0;
11240         ConstantInt *Scale = 0;
11241         if (ArrayEltSize == 1) {
11242           NewIdx = GEP.getOperand(1);
11243           Scale = 
11244                Context->getConstantInt(cast<IntegerType>(NewIdx->getType()), 1);
11245         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11246           NewIdx = Context->getConstantInt(CI->getType(), 1);
11247           Scale = CI;
11248         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11249           if (Inst->getOpcode() == Instruction::Shl &&
11250               isa<ConstantInt>(Inst->getOperand(1))) {
11251             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11252             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11253             Scale = Context->getConstantInt(cast<IntegerType>(Inst->getType()),
11254                                      1ULL << ShAmtVal);
11255             NewIdx = Inst->getOperand(0);
11256           } else if (Inst->getOpcode() == Instruction::Mul &&
11257                      isa<ConstantInt>(Inst->getOperand(1))) {
11258             Scale = cast<ConstantInt>(Inst->getOperand(1));
11259             NewIdx = Inst->getOperand(0);
11260           }
11261         }
11262         
11263         // If the index will be to exactly the right offset with the scale taken
11264         // out, perform the transformation. Note, we don't know whether Scale is
11265         // signed or not. We'll use unsigned version of division/modulo
11266         // operation after making sure Scale doesn't have the sign bit set.
11267         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11268             Scale->getZExtValue() % ArrayEltSize == 0) {
11269           Scale = Context->getConstantInt(Scale->getType(),
11270                                    Scale->getZExtValue() / ArrayEltSize);
11271           if (Scale->getZExtValue() != 1) {
11272             Constant *C =
11273                    Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
11274                                                        false /*ZExt*/);
11275             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11276             NewIdx = InsertNewInstBefore(Sc, GEP);
11277           }
11278
11279           // Insert the new GEP instruction.
11280           Value *Idx[2];
11281           Idx[0] = Context->getNullValue(Type::Int32Ty);
11282           Idx[1] = NewIdx;
11283           Instruction *NewGEP =
11284             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11285           NewGEP = InsertNewInstBefore(NewGEP, GEP);
11286           // The NewGEP must be pointer typed, so must the old one -> BitCast
11287           return new BitCastInst(NewGEP, GEP.getType());
11288         }
11289       }
11290     }
11291   }
11292   
11293   /// See if we can simplify:
11294   ///   X = bitcast A to B*
11295   ///   Y = gep X, <...constant indices...>
11296   /// into a gep of the original struct.  This is important for SROA and alias
11297   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11298   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11299     if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11300       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11301       // a constant back from EmitGEPOffset.
11302       ConstantInt *OffsetV =
11303                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11304       int64_t Offset = OffsetV->getSExtValue();
11305       
11306       // If this GEP instruction doesn't move the pointer, just replace the GEP
11307       // with a bitcast of the real input to the dest type.
11308       if (Offset == 0) {
11309         // If the bitcast is of an allocation, and the allocation will be
11310         // converted to match the type of the cast, don't touch this.
11311         if (isa<AllocationInst>(BCI->getOperand(0))) {
11312           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11313           if (Instruction *I = visitBitCast(*BCI)) {
11314             if (I != BCI) {
11315               I->takeName(BCI);
11316               BCI->getParent()->getInstList().insert(BCI, I);
11317               ReplaceInstUsesWith(*BCI, I);
11318             }
11319             return &GEP;
11320           }
11321         }
11322         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11323       }
11324       
11325       // Otherwise, if the offset is non-zero, we need to find out if there is a
11326       // field at Offset in 'A's type.  If so, we can pull the cast through the
11327       // GEP.
11328       SmallVector<Value*, 8> NewIndices;
11329       const Type *InTy =
11330         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11331       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11332         Instruction *NGEP =
11333            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11334                                      NewIndices.end());
11335         if (NGEP->getType() == GEP.getType()) return NGEP;
11336         InsertNewInstBefore(NGEP, GEP);
11337         NGEP->takeName(&GEP);
11338         return new BitCastInst(NGEP, GEP.getType());
11339       }
11340     }
11341   }    
11342     
11343   return 0;
11344 }
11345
11346 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11347   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11348   if (AI.isArrayAllocation()) {  // Check C != 1
11349     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11350       const Type *NewTy = 
11351         Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
11352       AllocationInst *New = 0;
11353
11354       // Create and insert the replacement instruction...
11355       if (isa<MallocInst>(AI))
11356         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11357       else {
11358         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11359         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11360       }
11361
11362       InsertNewInstBefore(New, AI);
11363
11364       // Scan to the end of the allocation instructions, to skip over a block of
11365       // allocas if possible...also skip interleaved debug info
11366       //
11367       BasicBlock::iterator It = New;
11368       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11369
11370       // Now that I is pointing to the first non-allocation-inst in the block,
11371       // insert our getelementptr instruction...
11372       //
11373       Value *NullIdx = Context->getNullValue(Type::Int32Ty);
11374       Value *Idx[2];
11375       Idx[0] = NullIdx;
11376       Idx[1] = NullIdx;
11377       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11378                                            New->getName()+".sub", It);
11379
11380       // Now make everything use the getelementptr instead of the original
11381       // allocation.
11382       return ReplaceInstUsesWith(AI, V);
11383     } else if (isa<UndefValue>(AI.getArraySize())) {
11384       return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11385     }
11386   }
11387
11388   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11389     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11390     // Note that we only do this for alloca's, because malloc should allocate
11391     // and return a unique pointer, even for a zero byte allocation.
11392     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11393       return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11394
11395     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11396     if (AI.getAlignment() == 0)
11397       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11398   }
11399
11400   return 0;
11401 }
11402
11403 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11404   Value *Op = FI.getOperand(0);
11405
11406   // free undef -> unreachable.
11407   if (isa<UndefValue>(Op)) {
11408     // Insert a new store to null because we cannot modify the CFG here.
11409     new StoreInst(Context->getConstantIntTrue(),
11410            Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
11411     return EraseInstFromFunction(FI);
11412   }
11413   
11414   // If we have 'free null' delete the instruction.  This can happen in stl code
11415   // when lots of inlining happens.
11416   if (isa<ConstantPointerNull>(Op))
11417     return EraseInstFromFunction(FI);
11418   
11419   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11420   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11421     FI.setOperand(0, CI->getOperand(0));
11422     return &FI;
11423   }
11424   
11425   // Change free (gep X, 0,0,0,0) into free(X)
11426   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11427     if (GEPI->hasAllZeroIndices()) {
11428       AddToWorkList(GEPI);
11429       FI.setOperand(0, GEPI->getOperand(0));
11430       return &FI;
11431     }
11432   }
11433   
11434   // Change free(malloc) into nothing, if the malloc has a single use.
11435   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11436     if (MI->hasOneUse()) {
11437       EraseInstFromFunction(FI);
11438       return EraseInstFromFunction(*MI);
11439     }
11440
11441   return 0;
11442 }
11443
11444
11445 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11446 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11447                                         const TargetData *TD) {
11448   User *CI = cast<User>(LI.getOperand(0));
11449   Value *CastOp = CI->getOperand(0);
11450   LLVMContext *Context = IC.getContext();
11451
11452   if (TD) {
11453     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11454       // Instead of loading constant c string, use corresponding integer value
11455       // directly if string length is small enough.
11456       std::string Str;
11457       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11458         unsigned len = Str.length();
11459         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11460         unsigned numBits = Ty->getPrimitiveSizeInBits();
11461         // Replace LI with immediate integer store.
11462         if ((numBits >> 3) == len + 1) {
11463           APInt StrVal(numBits, 0);
11464           APInt SingleChar(numBits, 0);
11465           if (TD->isLittleEndian()) {
11466             for (signed i = len-1; i >= 0; i--) {
11467               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11468               StrVal = (StrVal << 8) | SingleChar;
11469             }
11470           } else {
11471             for (unsigned i = 0; i < len; i++) {
11472               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11473               StrVal = (StrVal << 8) | SingleChar;
11474             }
11475             // Append NULL at the end.
11476             SingleChar = 0;
11477             StrVal = (StrVal << 8) | SingleChar;
11478           }
11479           Value *NL = Context->getConstantInt(StrVal);
11480           return IC.ReplaceInstUsesWith(LI, NL);
11481         }
11482       }
11483     }
11484   }
11485
11486   const PointerType *DestTy = cast<PointerType>(CI->getType());
11487   const Type *DestPTy = DestTy->getElementType();
11488   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11489
11490     // If the address spaces don't match, don't eliminate the cast.
11491     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11492       return 0;
11493
11494     const Type *SrcPTy = SrcTy->getElementType();
11495
11496     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11497          isa<VectorType>(DestPTy)) {
11498       // If the source is an array, the code below will not succeed.  Check to
11499       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11500       // constants.
11501       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11502         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11503           if (ASrcTy->getNumElements() != 0) {
11504             Value *Idxs[2];
11505             Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11506             CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
11507             SrcTy = cast<PointerType>(CastOp->getType());
11508             SrcPTy = SrcTy->getElementType();
11509           }
11510
11511       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11512             isa<VectorType>(SrcPTy)) &&
11513           // Do not allow turning this into a load of an integer, which is then
11514           // casted to a pointer, this pessimizes pointer analysis a lot.
11515           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11516           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11517                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11518
11519         // Okay, we are casting from one integer or pointer type to another of
11520         // the same size.  Instead of casting the pointer before the load, cast
11521         // the result of the loaded value.
11522         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11523                                                              CI->getName(),
11524                                                          LI.isVolatile()),LI);
11525         // Now cast the result of the load.
11526         return new BitCastInst(NewLoad, LI.getType());
11527       }
11528     }
11529   }
11530   return 0;
11531 }
11532
11533 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11534   Value *Op = LI.getOperand(0);
11535
11536   // Attempt to improve the alignment.
11537   unsigned KnownAlign =
11538     GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11539   if (KnownAlign >
11540       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11541                                 LI.getAlignment()))
11542     LI.setAlignment(KnownAlign);
11543
11544   // load (cast X) --> cast (load X) iff safe
11545   if (isa<CastInst>(Op))
11546     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11547       return Res;
11548
11549   // None of the following transforms are legal for volatile loads.
11550   if (LI.isVolatile()) return 0;
11551   
11552   // Do really simple store-to-load forwarding and load CSE, to catch cases
11553   // where there are several consequtive memory accesses to the same location,
11554   // separated by a few arithmetic operations.
11555   BasicBlock::iterator BBI = &LI;
11556   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11557     return ReplaceInstUsesWith(LI, AvailableVal);
11558
11559   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11560     const Value *GEPI0 = GEPI->getOperand(0);
11561     // TODO: Consider a target hook for valid address spaces for this xform.
11562     if (isa<ConstantPointerNull>(GEPI0) &&
11563         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11564       // Insert a new store to null instruction before the load to indicate
11565       // that this code is not reachable.  We do this instead of inserting
11566       // an unreachable instruction directly because we cannot modify the
11567       // CFG.
11568       new StoreInst(Context->getUndef(LI.getType()),
11569                     Context->getNullValue(Op->getType()), &LI);
11570       return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11571     }
11572   } 
11573
11574   if (Constant *C = dyn_cast<Constant>(Op)) {
11575     // load null/undef -> undef
11576     // TODO: Consider a target hook for valid address spaces for this xform.
11577     if (isa<UndefValue>(C) || (C->isNullValue() && 
11578         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11579       // Insert a new store to null instruction before the load to indicate that
11580       // this code is not reachable.  We do this instead of inserting an
11581       // unreachable instruction directly because we cannot modify the CFG.
11582       new StoreInst(Context->getUndef(LI.getType()),
11583                     Context->getNullValue(Op->getType()), &LI);
11584       return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11585     }
11586
11587     // Instcombine load (constant global) into the value loaded.
11588     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11589       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11590         return ReplaceInstUsesWith(LI, GV->getInitializer());
11591
11592     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11593     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11594       if (CE->getOpcode() == Instruction::GetElementPtr) {
11595         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11596           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11597             if (Constant *V = 
11598                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE, 
11599                                                       Context))
11600               return ReplaceInstUsesWith(LI, V);
11601         if (CE->getOperand(0)->isNullValue()) {
11602           // Insert a new store to null instruction before the load to indicate
11603           // that this code is not reachable.  We do this instead of inserting
11604           // an unreachable instruction directly because we cannot modify the
11605           // CFG.
11606           new StoreInst(Context->getUndef(LI.getType()),
11607                         Context->getNullValue(Op->getType()), &LI);
11608           return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11609         }
11610
11611       } else if (CE->isCast()) {
11612         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11613           return Res;
11614       }
11615     }
11616   }
11617     
11618   // If this load comes from anywhere in a constant global, and if the global
11619   // is all undef or zero, we know what it loads.
11620   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11621     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11622       if (GV->getInitializer()->isNullValue())
11623         return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
11624       else if (isa<UndefValue>(GV->getInitializer()))
11625         return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11626     }
11627   }
11628
11629   if (Op->hasOneUse()) {
11630     // Change select and PHI nodes to select values instead of addresses: this
11631     // helps alias analysis out a lot, allows many others simplifications, and
11632     // exposes redundancy in the code.
11633     //
11634     // Note that we cannot do the transformation unless we know that the
11635     // introduced loads cannot trap!  Something like this is valid as long as
11636     // the condition is always false: load (select bool %C, int* null, int* %G),
11637     // but it would not be valid if we transformed it to load from null
11638     // unconditionally.
11639     //
11640     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11641       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11642       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11643           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11644         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11645                                      SI->getOperand(1)->getName()+".val"), LI);
11646         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11647                                      SI->getOperand(2)->getName()+".val"), LI);
11648         return SelectInst::Create(SI->getCondition(), V1, V2);
11649       }
11650
11651       // load (select (cond, null, P)) -> load P
11652       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11653         if (C->isNullValue()) {
11654           LI.setOperand(0, SI->getOperand(2));
11655           return &LI;
11656         }
11657
11658       // load (select (cond, P, null)) -> load P
11659       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11660         if (C->isNullValue()) {
11661           LI.setOperand(0, SI->getOperand(1));
11662           return &LI;
11663         }
11664     }
11665   }
11666   return 0;
11667 }
11668
11669 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11670 /// when possible.  This makes it generally easy to do alias analysis and/or
11671 /// SROA/mem2reg of the memory object.
11672 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11673   User *CI = cast<User>(SI.getOperand(1));
11674   Value *CastOp = CI->getOperand(0);
11675   LLVMContext *Context = IC.getContext();
11676
11677   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11678   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11679   if (SrcTy == 0) return 0;
11680   
11681   const Type *SrcPTy = SrcTy->getElementType();
11682
11683   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11684     return 0;
11685   
11686   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11687   /// to its first element.  This allows us to handle things like:
11688   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11689   /// on 32-bit hosts.
11690   SmallVector<Value*, 4> NewGEPIndices;
11691   
11692   // If the source is an array, the code below will not succeed.  Check to
11693   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11694   // constants.
11695   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11696     // Index through pointer.
11697     Constant *Zero = Context->getNullValue(Type::Int32Ty);
11698     NewGEPIndices.push_back(Zero);
11699     
11700     while (1) {
11701       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11702         if (!STy->getNumElements()) /* Struct can be empty {} */
11703           break;
11704         NewGEPIndices.push_back(Zero);
11705         SrcPTy = STy->getElementType(0);
11706       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11707         NewGEPIndices.push_back(Zero);
11708         SrcPTy = ATy->getElementType();
11709       } else {
11710         break;
11711       }
11712     }
11713     
11714     SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
11715   }
11716
11717   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11718     return 0;
11719   
11720   // If the pointers point into different address spaces or if they point to
11721   // values with different sizes, we can't do the transformation.
11722   if (SrcTy->getAddressSpace() != 
11723         cast<PointerType>(CI->getType())->getAddressSpace() ||
11724       IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
11725       IC.getTargetData().getTypeSizeInBits(DestPTy))
11726     return 0;
11727
11728   // Okay, we are casting from one integer or pointer type to another of
11729   // the same size.  Instead of casting the pointer before 
11730   // the store, cast the value to be stored.
11731   Value *NewCast;
11732   Value *SIOp0 = SI.getOperand(0);
11733   Instruction::CastOps opcode = Instruction::BitCast;
11734   const Type* CastSrcTy = SIOp0->getType();
11735   const Type* CastDstTy = SrcPTy;
11736   if (isa<PointerType>(CastDstTy)) {
11737     if (CastSrcTy->isInteger())
11738       opcode = Instruction::IntToPtr;
11739   } else if (isa<IntegerType>(CastDstTy)) {
11740     if (isa<PointerType>(SIOp0->getType()))
11741       opcode = Instruction::PtrToInt;
11742   }
11743   
11744   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11745   // emit a GEP to index into its first field.
11746   if (!NewGEPIndices.empty()) {
11747     if (Constant *C = dyn_cast<Constant>(CastOp))
11748       CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0], 
11749                                               NewGEPIndices.size());
11750     else
11751       CastOp = IC.InsertNewInstBefore(
11752               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11753                                         NewGEPIndices.end()), SI);
11754   }
11755   
11756   if (Constant *C = dyn_cast<Constant>(SIOp0))
11757     NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
11758   else
11759     NewCast = IC.InsertNewInstBefore(
11760       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11761       SI);
11762   return new StoreInst(NewCast, CastOp);
11763 }
11764
11765 /// equivalentAddressValues - Test if A and B will obviously have the same
11766 /// value. This includes recognizing that %t0 and %t1 will have the same
11767 /// value in code like this:
11768 ///   %t0 = getelementptr \@a, 0, 3
11769 ///   store i32 0, i32* %t0
11770 ///   %t1 = getelementptr \@a, 0, 3
11771 ///   %t2 = load i32* %t1
11772 ///
11773 static bool equivalentAddressValues(Value *A, Value *B) {
11774   // Test if the values are trivially equivalent.
11775   if (A == B) return true;
11776   
11777   // Test if the values come form identical arithmetic instructions.
11778   if (isa<BinaryOperator>(A) ||
11779       isa<CastInst>(A) ||
11780       isa<PHINode>(A) ||
11781       isa<GetElementPtrInst>(A))
11782     if (Instruction *BI = dyn_cast<Instruction>(B))
11783       if (cast<Instruction>(A)->isIdenticalTo(BI))
11784         return true;
11785   
11786   // Otherwise they may not be equivalent.
11787   return false;
11788 }
11789
11790 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11791 // return the llvm.dbg.declare.
11792 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11793   if (!V->hasNUses(2))
11794     return 0;
11795   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11796        UI != E; ++UI) {
11797     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11798       return DI;
11799     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11800       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11801         return DI;
11802       }
11803   }
11804   return 0;
11805 }
11806
11807 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11808   Value *Val = SI.getOperand(0);
11809   Value *Ptr = SI.getOperand(1);
11810
11811   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11812     EraseInstFromFunction(SI);
11813     ++NumCombined;
11814     return 0;
11815   }
11816   
11817   // If the RHS is an alloca with a single use, zapify the store, making the
11818   // alloca dead.
11819   // If the RHS is an alloca with a two uses, the other one being a 
11820   // llvm.dbg.declare, zapify the store and the declare, making the
11821   // alloca dead.  We must do this to prevent declare's from affecting
11822   // codegen.
11823   if (!SI.isVolatile()) {
11824     if (Ptr->hasOneUse()) {
11825       if (isa<AllocaInst>(Ptr)) {
11826         EraseInstFromFunction(SI);
11827         ++NumCombined;
11828         return 0;
11829       }
11830       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11831         if (isa<AllocaInst>(GEP->getOperand(0))) {
11832           if (GEP->getOperand(0)->hasOneUse()) {
11833             EraseInstFromFunction(SI);
11834             ++NumCombined;
11835             return 0;
11836           }
11837           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11838             EraseInstFromFunction(*DI);
11839             EraseInstFromFunction(SI);
11840             ++NumCombined;
11841             return 0;
11842           }
11843         }
11844       }
11845     }
11846     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11847       EraseInstFromFunction(*DI);
11848       EraseInstFromFunction(SI);
11849       ++NumCombined;
11850       return 0;
11851     }
11852   }
11853
11854   // Attempt to improve the alignment.
11855   unsigned KnownAlign =
11856     GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11857   if (KnownAlign >
11858       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11859                                 SI.getAlignment()))
11860     SI.setAlignment(KnownAlign);
11861
11862   // Do really simple DSE, to catch cases where there are several consecutive
11863   // stores to the same location, separated by a few arithmetic operations. This
11864   // situation often occurs with bitfield accesses.
11865   BasicBlock::iterator BBI = &SI;
11866   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11867        --ScanInsts) {
11868     --BBI;
11869     // Don't count debug info directives, lest they affect codegen,
11870     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11871     // It is necessary for correctness to skip those that feed into a
11872     // llvm.dbg.declare, as these are not present when debugging is off.
11873     if (isa<DbgInfoIntrinsic>(BBI) ||
11874         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11875       ScanInsts++;
11876       continue;
11877     }    
11878     
11879     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11880       // Prev store isn't volatile, and stores to the same location?
11881       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11882                                                           SI.getOperand(1))) {
11883         ++NumDeadStore;
11884         ++BBI;
11885         EraseInstFromFunction(*PrevSI);
11886         continue;
11887       }
11888       break;
11889     }
11890     
11891     // If this is a load, we have to stop.  However, if the loaded value is from
11892     // the pointer we're loading and is producing the pointer we're storing,
11893     // then *this* store is dead (X = load P; store X -> P).
11894     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11895       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11896           !SI.isVolatile()) {
11897         EraseInstFromFunction(SI);
11898         ++NumCombined;
11899         return 0;
11900       }
11901       // Otherwise, this is a load from some other location.  Stores before it
11902       // may not be dead.
11903       break;
11904     }
11905     
11906     // Don't skip over loads or things that can modify memory.
11907     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11908       break;
11909   }
11910   
11911   
11912   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11913
11914   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11915   if (isa<ConstantPointerNull>(Ptr) &&
11916       cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11917     if (!isa<UndefValue>(Val)) {
11918       SI.setOperand(0, Context->getUndef(Val->getType()));
11919       if (Instruction *U = dyn_cast<Instruction>(Val))
11920         AddToWorkList(U);  // Dropped a use.
11921       ++NumCombined;
11922     }
11923     return 0;  // Do not modify these!
11924   }
11925
11926   // store undef, Ptr -> noop
11927   if (isa<UndefValue>(Val)) {
11928     EraseInstFromFunction(SI);
11929     ++NumCombined;
11930     return 0;
11931   }
11932
11933   // If the pointer destination is a cast, see if we can fold the cast into the
11934   // source instead.
11935   if (isa<CastInst>(Ptr))
11936     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11937       return Res;
11938   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11939     if (CE->isCast())
11940       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11941         return Res;
11942
11943   
11944   // If this store is the last instruction in the basic block (possibly
11945   // excepting debug info instructions and the pointer bitcasts that feed
11946   // into them), and if the block ends with an unconditional branch, try
11947   // to move it to the successor block.
11948   BBI = &SI; 
11949   do {
11950     ++BBI;
11951   } while (isa<DbgInfoIntrinsic>(BBI) ||
11952            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11953   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11954     if (BI->isUnconditional())
11955       if (SimplifyStoreAtEndOfBlock(SI))
11956         return 0;  // xform done!
11957   
11958   return 0;
11959 }
11960
11961 /// SimplifyStoreAtEndOfBlock - Turn things like:
11962 ///   if () { *P = v1; } else { *P = v2 }
11963 /// into a phi node with a store in the successor.
11964 ///
11965 /// Simplify things like:
11966 ///   *P = v1; if () { *P = v2; }
11967 /// into a phi node with a store in the successor.
11968 ///
11969 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11970   BasicBlock *StoreBB = SI.getParent();
11971   
11972   // Check to see if the successor block has exactly two incoming edges.  If
11973   // so, see if the other predecessor contains a store to the same location.
11974   // if so, insert a PHI node (if needed) and move the stores down.
11975   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11976   
11977   // Determine whether Dest has exactly two predecessors and, if so, compute
11978   // the other predecessor.
11979   pred_iterator PI = pred_begin(DestBB);
11980   BasicBlock *OtherBB = 0;
11981   if (*PI != StoreBB)
11982     OtherBB = *PI;
11983   ++PI;
11984   if (PI == pred_end(DestBB))
11985     return false;
11986   
11987   if (*PI != StoreBB) {
11988     if (OtherBB)
11989       return false;
11990     OtherBB = *PI;
11991   }
11992   if (++PI != pred_end(DestBB))
11993     return false;
11994
11995   // Bail out if all the relevant blocks aren't distinct (this can happen,
11996   // for example, if SI is in an infinite loop)
11997   if (StoreBB == DestBB || OtherBB == DestBB)
11998     return false;
11999
12000   // Verify that the other block ends in a branch and is not otherwise empty.
12001   BasicBlock::iterator BBI = OtherBB->getTerminator();
12002   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12003   if (!OtherBr || BBI == OtherBB->begin())
12004     return false;
12005   
12006   // If the other block ends in an unconditional branch, check for the 'if then
12007   // else' case.  there is an instruction before the branch.
12008   StoreInst *OtherStore = 0;
12009   if (OtherBr->isUnconditional()) {
12010     --BBI;
12011     // Skip over debugging info.
12012     while (isa<DbgInfoIntrinsic>(BBI) ||
12013            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12014       if (BBI==OtherBB->begin())
12015         return false;
12016       --BBI;
12017     }
12018     // If this isn't a store, or isn't a store to the same location, bail out.
12019     OtherStore = dyn_cast<StoreInst>(BBI);
12020     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12021       return false;
12022   } else {
12023     // Otherwise, the other block ended with a conditional branch. If one of the
12024     // destinations is StoreBB, then we have the if/then case.
12025     if (OtherBr->getSuccessor(0) != StoreBB && 
12026         OtherBr->getSuccessor(1) != StoreBB)
12027       return false;
12028     
12029     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12030     // if/then triangle.  See if there is a store to the same ptr as SI that
12031     // lives in OtherBB.
12032     for (;; --BBI) {
12033       // Check to see if we find the matching store.
12034       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12035         if (OtherStore->getOperand(1) != SI.getOperand(1))
12036           return false;
12037         break;
12038       }
12039       // If we find something that may be using or overwriting the stored
12040       // value, or if we run out of instructions, we can't do the xform.
12041       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12042           BBI == OtherBB->begin())
12043         return false;
12044     }
12045     
12046     // In order to eliminate the store in OtherBr, we have to
12047     // make sure nothing reads or overwrites the stored value in
12048     // StoreBB.
12049     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12050       // FIXME: This should really be AA driven.
12051       if (I->mayReadFromMemory() || I->mayWriteToMemory())
12052         return false;
12053     }
12054   }
12055   
12056   // Insert a PHI node now if we need it.
12057   Value *MergedVal = OtherStore->getOperand(0);
12058   if (MergedVal != SI.getOperand(0)) {
12059     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12060     PN->reserveOperandSpace(2);
12061     PN->addIncoming(SI.getOperand(0), SI.getParent());
12062     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12063     MergedVal = InsertNewInstBefore(PN, DestBB->front());
12064   }
12065   
12066   // Advance to a place where it is safe to insert the new store and
12067   // insert it.
12068   BBI = DestBB->getFirstNonPHI();
12069   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12070                                     OtherStore->isVolatile()), *BBI);
12071   
12072   // Nuke the old stores.
12073   EraseInstFromFunction(SI);
12074   EraseInstFromFunction(*OtherStore);
12075   ++NumCombined;
12076   return true;
12077 }
12078
12079
12080 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12081   // Change br (not X), label True, label False to: br X, label False, True
12082   Value *X = 0;
12083   BasicBlock *TrueDest;
12084   BasicBlock *FalseDest;
12085   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
12086       !isa<Constant>(X)) {
12087     // Swap Destinations and condition...
12088     BI.setCondition(X);
12089     BI.setSuccessor(0, FalseDest);
12090     BI.setSuccessor(1, TrueDest);
12091     return &BI;
12092   }
12093
12094   // Cannonicalize fcmp_one -> fcmp_oeq
12095   FCmpInst::Predicate FPred; Value *Y;
12096   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
12097                              TrueDest, FalseDest), *Context))
12098     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12099          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12100       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12101       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
12102       Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
12103       NewSCC->takeName(I);
12104       // Swap Destinations and condition...
12105       BI.setCondition(NewSCC);
12106       BI.setSuccessor(0, FalseDest);
12107       BI.setSuccessor(1, TrueDest);
12108       RemoveFromWorkList(I);
12109       I->eraseFromParent();
12110       AddToWorkList(NewSCC);
12111       return &BI;
12112     }
12113
12114   // Cannonicalize icmp_ne -> icmp_eq
12115   ICmpInst::Predicate IPred;
12116   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12117                       TrueDest, FalseDest), *Context))
12118     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12119          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12120          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12121       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12122       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
12123       Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
12124       NewSCC->takeName(I);
12125       // Swap Destinations and condition...
12126       BI.setCondition(NewSCC);
12127       BI.setSuccessor(0, FalseDest);
12128       BI.setSuccessor(1, TrueDest);
12129       RemoveFromWorkList(I);
12130       I->eraseFromParent();;
12131       AddToWorkList(NewSCC);
12132       return &BI;
12133     }
12134
12135   return 0;
12136 }
12137
12138 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12139   Value *Cond = SI.getCondition();
12140   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12141     if (I->getOpcode() == Instruction::Add)
12142       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12143         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12144         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12145           SI.setOperand(i,
12146                    Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
12147                                                 AddRHS));
12148         SI.setOperand(0, I->getOperand(0));
12149         AddToWorkList(I);
12150         return &SI;
12151       }
12152   }
12153   return 0;
12154 }
12155
12156 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12157   Value *Agg = EV.getAggregateOperand();
12158
12159   if (!EV.hasIndices())
12160     return ReplaceInstUsesWith(EV, Agg);
12161
12162   if (Constant *C = dyn_cast<Constant>(Agg)) {
12163     if (isa<UndefValue>(C))
12164       return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
12165       
12166     if (isa<ConstantAggregateZero>(C))
12167       return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
12168
12169     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12170       // Extract the element indexed by the first index out of the constant
12171       Value *V = C->getOperand(*EV.idx_begin());
12172       if (EV.getNumIndices() > 1)
12173         // Extract the remaining indices out of the constant indexed by the
12174         // first index
12175         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12176       else
12177         return ReplaceInstUsesWith(EV, V);
12178     }
12179     return 0; // Can't handle other constants
12180   } 
12181   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12182     // We're extracting from an insertvalue instruction, compare the indices
12183     const unsigned *exti, *exte, *insi, *inse;
12184     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12185          exte = EV.idx_end(), inse = IV->idx_end();
12186          exti != exte && insi != inse;
12187          ++exti, ++insi) {
12188       if (*insi != *exti)
12189         // The insert and extract both reference distinctly different elements.
12190         // This means the extract is not influenced by the insert, and we can
12191         // replace the aggregate operand of the extract with the aggregate
12192         // operand of the insert. i.e., replace
12193         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12194         // %E = extractvalue { i32, { i32 } } %I, 0
12195         // with
12196         // %E = extractvalue { i32, { i32 } } %A, 0
12197         return ExtractValueInst::Create(IV->getAggregateOperand(),
12198                                         EV.idx_begin(), EV.idx_end());
12199     }
12200     if (exti == exte && insi == inse)
12201       // Both iterators are at the end: Index lists are identical. Replace
12202       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12203       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12204       // with "i32 42"
12205       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12206     if (exti == exte) {
12207       // The extract list is a prefix of the insert list. i.e. replace
12208       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12209       // %E = extractvalue { i32, { i32 } } %I, 1
12210       // with
12211       // %X = extractvalue { i32, { i32 } } %A, 1
12212       // %E = insertvalue { i32 } %X, i32 42, 0
12213       // by switching the order of the insert and extract (though the
12214       // insertvalue should be left in, since it may have other uses).
12215       Value *NewEV = InsertNewInstBefore(
12216         ExtractValueInst::Create(IV->getAggregateOperand(),
12217                                  EV.idx_begin(), EV.idx_end()),
12218         EV);
12219       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12220                                      insi, inse);
12221     }
12222     if (insi == inse)
12223       // The insert list is a prefix of the extract list
12224       // We can simply remove the common indices from the extract and make it
12225       // operate on the inserted value instead of the insertvalue result.
12226       // i.e., replace
12227       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12228       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12229       // with
12230       // %E extractvalue { i32 } { i32 42 }, 0
12231       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12232                                       exti, exte);
12233   }
12234   // Can't simplify extracts from other values. Note that nested extracts are
12235   // already simplified implicitely by the above (extract ( extract (insert) )
12236   // will be translated into extract ( insert ( extract ) ) first and then just
12237   // the value inserted, if appropriate).
12238   return 0;
12239 }
12240
12241 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12242 /// is to leave as a vector operation.
12243 static bool CheapToScalarize(Value *V, bool isConstant) {
12244   if (isa<ConstantAggregateZero>(V)) 
12245     return true;
12246   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12247     if (isConstant) return true;
12248     // If all elts are the same, we can extract.
12249     Constant *Op0 = C->getOperand(0);
12250     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12251       if (C->getOperand(i) != Op0)
12252         return false;
12253     return true;
12254   }
12255   Instruction *I = dyn_cast<Instruction>(V);
12256   if (!I) return false;
12257   
12258   // Insert element gets simplified to the inserted element or is deleted if
12259   // this is constant idx extract element and its a constant idx insertelt.
12260   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12261       isa<ConstantInt>(I->getOperand(2)))
12262     return true;
12263   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12264     return true;
12265   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12266     if (BO->hasOneUse() &&
12267         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12268          CheapToScalarize(BO->getOperand(1), isConstant)))
12269       return true;
12270   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12271     if (CI->hasOneUse() &&
12272         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12273          CheapToScalarize(CI->getOperand(1), isConstant)))
12274       return true;
12275   
12276   return false;
12277 }
12278
12279 /// Read and decode a shufflevector mask.
12280 ///
12281 /// It turns undef elements into values that are larger than the number of
12282 /// elements in the input.
12283 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12284   unsigned NElts = SVI->getType()->getNumElements();
12285   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12286     return std::vector<unsigned>(NElts, 0);
12287   if (isa<UndefValue>(SVI->getOperand(2)))
12288     return std::vector<unsigned>(NElts, 2*NElts);
12289
12290   std::vector<unsigned> Result;
12291   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12292   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12293     if (isa<UndefValue>(*i))
12294       Result.push_back(NElts*2);  // undef -> 8
12295     else
12296       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12297   return Result;
12298 }
12299
12300 /// FindScalarElement - Given a vector and an element number, see if the scalar
12301 /// value is already around as a register, for example if it were inserted then
12302 /// extracted from the vector.
12303 static Value *FindScalarElement(Value *V, unsigned EltNo,
12304                                 LLVMContext *Context) {
12305   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12306   const VectorType *PTy = cast<VectorType>(V->getType());
12307   unsigned Width = PTy->getNumElements();
12308   if (EltNo >= Width)  // Out of range access.
12309     return Context->getUndef(PTy->getElementType());
12310   
12311   if (isa<UndefValue>(V))
12312     return Context->getUndef(PTy->getElementType());
12313   else if (isa<ConstantAggregateZero>(V))
12314     return Context->getNullValue(PTy->getElementType());
12315   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12316     return CP->getOperand(EltNo);
12317   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12318     // If this is an insert to a variable element, we don't know what it is.
12319     if (!isa<ConstantInt>(III->getOperand(2))) 
12320       return 0;
12321     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12322     
12323     // If this is an insert to the element we are looking for, return the
12324     // inserted value.
12325     if (EltNo == IIElt) 
12326       return III->getOperand(1);
12327     
12328     // Otherwise, the insertelement doesn't modify the value, recurse on its
12329     // vector input.
12330     return FindScalarElement(III->getOperand(0), EltNo, Context);
12331   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12332     unsigned LHSWidth =
12333       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12334     unsigned InEl = getShuffleMask(SVI)[EltNo];
12335     if (InEl < LHSWidth)
12336       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12337     else if (InEl < LHSWidth*2)
12338       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12339     else
12340       return Context->getUndef(PTy->getElementType());
12341   }
12342   
12343   // Otherwise, we don't know.
12344   return 0;
12345 }
12346
12347 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12348   // If vector val is undef, replace extract with scalar undef.
12349   if (isa<UndefValue>(EI.getOperand(0)))
12350     return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12351
12352   // If vector val is constant 0, replace extract with scalar 0.
12353   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12354     return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
12355   
12356   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12357     // If vector val is constant with all elements the same, replace EI with
12358     // that element. When the elements are not identical, we cannot replace yet
12359     // (we do that below, but only when the index is constant).
12360     Constant *op0 = C->getOperand(0);
12361     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12362       if (C->getOperand(i) != op0) {
12363         op0 = 0; 
12364         break;
12365       }
12366     if (op0)
12367       return ReplaceInstUsesWith(EI, op0);
12368   }
12369   
12370   // If extracting a specified index from the vector, see if we can recursively
12371   // find a previously computed scalar that was inserted into the vector.
12372   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12373     unsigned IndexVal = IdxC->getZExtValue();
12374     unsigned VectorWidth = 
12375       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12376       
12377     // If this is extracting an invalid index, turn this into undef, to avoid
12378     // crashing the code below.
12379     if (IndexVal >= VectorWidth)
12380       return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12381     
12382     // This instruction only demands the single element from the input vector.
12383     // If the input vector has a single use, simplify it based on this use
12384     // property.
12385     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12386       APInt UndefElts(VectorWidth, 0);
12387       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12388       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12389                                                 DemandedMask, UndefElts)) {
12390         EI.setOperand(0, V);
12391         return &EI;
12392       }
12393     }
12394     
12395     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12396       return ReplaceInstUsesWith(EI, Elt);
12397     
12398     // If the this extractelement is directly using a bitcast from a vector of
12399     // the same number of elements, see if we can find the source element from
12400     // it.  In this case, we will end up needing to bitcast the scalars.
12401     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12402       if (const VectorType *VT = 
12403               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12404         if (VT->getNumElements() == VectorWidth)
12405           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12406                                              IndexVal, Context))
12407             return new BitCastInst(Elt, EI.getType());
12408     }
12409   }
12410   
12411   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12412     if (I->hasOneUse()) {
12413       // Push extractelement into predecessor operation if legal and
12414       // profitable to do so
12415       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12416         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12417         if (CheapToScalarize(BO, isConstantElt)) {
12418           ExtractElementInst *newEI0 = 
12419             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12420                                    EI.getName()+".lhs");
12421           ExtractElementInst *newEI1 =
12422             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12423                                    EI.getName()+".rhs");
12424           InsertNewInstBefore(newEI0, EI);
12425           InsertNewInstBefore(newEI1, EI);
12426           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12427         }
12428       } else if (isa<LoadInst>(I)) {
12429         unsigned AS = 
12430           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12431         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12432                                   Context->getPointerType(EI.getType(), AS),EI);
12433         GetElementPtrInst *GEP =
12434           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12435         InsertNewInstBefore(GEP, EI);
12436         return new LoadInst(GEP);
12437       }
12438     }
12439     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12440       // Extracting the inserted element?
12441       if (IE->getOperand(2) == EI.getOperand(1))
12442         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12443       // If the inserted and extracted elements are constants, they must not
12444       // be the same value, extract from the pre-inserted value instead.
12445       if (isa<Constant>(IE->getOperand(2)) &&
12446           isa<Constant>(EI.getOperand(1))) {
12447         AddUsesToWorkList(EI);
12448         EI.setOperand(0, IE->getOperand(0));
12449         return &EI;
12450       }
12451     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12452       // If this is extracting an element from a shufflevector, figure out where
12453       // it came from and extract from the appropriate input element instead.
12454       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12455         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12456         Value *Src;
12457         unsigned LHSWidth =
12458           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12459
12460         if (SrcIdx < LHSWidth)
12461           Src = SVI->getOperand(0);
12462         else if (SrcIdx < LHSWidth*2) {
12463           SrcIdx -= LHSWidth;
12464           Src = SVI->getOperand(1);
12465         } else {
12466           return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12467         }
12468         return new ExtractElementInst(Src,
12469                          Context->getConstantInt(Type::Int32Ty, SrcIdx, false));
12470       }
12471     }
12472   }
12473   return 0;
12474 }
12475
12476 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12477 /// elements from either LHS or RHS, return the shuffle mask and true. 
12478 /// Otherwise, return false.
12479 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12480                                          std::vector<Constant*> &Mask,
12481                                          LLVMContext *Context) {
12482   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12483          "Invalid CollectSingleShuffleElements");
12484   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12485
12486   if (isa<UndefValue>(V)) {
12487     Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12488     return true;
12489   } else if (V == LHS) {
12490     for (unsigned i = 0; i != NumElts; ++i)
12491       Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12492     return true;
12493   } else if (V == RHS) {
12494     for (unsigned i = 0; i != NumElts; ++i)
12495       Mask.push_back(Context->getConstantInt(Type::Int32Ty, i+NumElts));
12496     return true;
12497   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12498     // If this is an insert of an extract from some other vector, include it.
12499     Value *VecOp    = IEI->getOperand(0);
12500     Value *ScalarOp = IEI->getOperand(1);
12501     Value *IdxOp    = IEI->getOperand(2);
12502     
12503     if (!isa<ConstantInt>(IdxOp))
12504       return false;
12505     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12506     
12507     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12508       // Okay, we can handle this if the vector we are insertinting into is
12509       // transitively ok.
12510       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12511         // If so, update the mask to reflect the inserted undef.
12512         Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
12513         return true;
12514       }      
12515     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12516       if (isa<ConstantInt>(EI->getOperand(1)) &&
12517           EI->getOperand(0)->getType() == V->getType()) {
12518         unsigned ExtractedIdx =
12519           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12520         
12521         // This must be extracting from either LHS or RHS.
12522         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12523           // Okay, we can handle this if the vector we are insertinting into is
12524           // transitively ok.
12525           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12526             // If so, update the mask to reflect the inserted value.
12527             if (EI->getOperand(0) == LHS) {
12528               Mask[InsertedIdx % NumElts] = 
12529                  Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12530             } else {
12531               assert(EI->getOperand(0) == RHS);
12532               Mask[InsertedIdx % NumElts] = 
12533                 Context->getConstantInt(Type::Int32Ty, ExtractedIdx+NumElts);
12534               
12535             }
12536             return true;
12537           }
12538         }
12539       }
12540     }
12541   }
12542   // TODO: Handle shufflevector here!
12543   
12544   return false;
12545 }
12546
12547 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12548 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12549 /// that computes V and the LHS value of the shuffle.
12550 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12551                                      Value *&RHS, LLVMContext *Context) {
12552   assert(isa<VectorType>(V->getType()) && 
12553          (RHS == 0 || V->getType() == RHS->getType()) &&
12554          "Invalid shuffle!");
12555   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12556
12557   if (isa<UndefValue>(V)) {
12558     Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12559     return V;
12560   } else if (isa<ConstantAggregateZero>(V)) {
12561     Mask.assign(NumElts, Context->getConstantInt(Type::Int32Ty, 0));
12562     return V;
12563   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12564     // If this is an insert of an extract from some other vector, include it.
12565     Value *VecOp    = IEI->getOperand(0);
12566     Value *ScalarOp = IEI->getOperand(1);
12567     Value *IdxOp    = IEI->getOperand(2);
12568     
12569     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12570       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12571           EI->getOperand(0)->getType() == V->getType()) {
12572         unsigned ExtractedIdx =
12573           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12574         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12575         
12576         // Either the extracted from or inserted into vector must be RHSVec,
12577         // otherwise we'd end up with a shuffle of three inputs.
12578         if (EI->getOperand(0) == RHS || RHS == 0) {
12579           RHS = EI->getOperand(0);
12580           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12581           Mask[InsertedIdx % NumElts] = 
12582             Context->getConstantInt(Type::Int32Ty, NumElts+ExtractedIdx);
12583           return V;
12584         }
12585         
12586         if (VecOp == RHS) {
12587           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12588                                             RHS, Context);
12589           // Everything but the extracted element is replaced with the RHS.
12590           for (unsigned i = 0; i != NumElts; ++i) {
12591             if (i != InsertedIdx)
12592               Mask[i] = Context->getConstantInt(Type::Int32Ty, NumElts+i);
12593           }
12594           return V;
12595         }
12596         
12597         // If this insertelement is a chain that comes from exactly these two
12598         // vectors, return the vector and the effective shuffle.
12599         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12600                                          Context))
12601           return EI->getOperand(0);
12602         
12603       }
12604     }
12605   }
12606   // TODO: Handle shufflevector here!
12607   
12608   // Otherwise, can't do anything fancy.  Return an identity vector.
12609   for (unsigned i = 0; i != NumElts; ++i)
12610     Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12611   return V;
12612 }
12613
12614 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12615   Value *VecOp    = IE.getOperand(0);
12616   Value *ScalarOp = IE.getOperand(1);
12617   Value *IdxOp    = IE.getOperand(2);
12618   
12619   // Inserting an undef or into an undefined place, remove this.
12620   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12621     ReplaceInstUsesWith(IE, VecOp);
12622   
12623   // If the inserted element was extracted from some other vector, and if the 
12624   // indexes are constant, try to turn this into a shufflevector operation.
12625   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12626     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12627         EI->getOperand(0)->getType() == IE.getType()) {
12628       unsigned NumVectorElts = IE.getType()->getNumElements();
12629       unsigned ExtractedIdx =
12630         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12631       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12632       
12633       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12634         return ReplaceInstUsesWith(IE, VecOp);
12635       
12636       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12637         return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
12638       
12639       // If we are extracting a value from a vector, then inserting it right
12640       // back into the same place, just use the input vector.
12641       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12642         return ReplaceInstUsesWith(IE, VecOp);      
12643       
12644       // We could theoretically do this for ANY input.  However, doing so could
12645       // turn chains of insertelement instructions into a chain of shufflevector
12646       // instructions, and right now we do not merge shufflevectors.  As such,
12647       // only do this in a situation where it is clear that there is benefit.
12648       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12649         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12650         // the values of VecOp, except then one read from EIOp0.
12651         // Build a new shuffle mask.
12652         std::vector<Constant*> Mask;
12653         if (isa<UndefValue>(VecOp))
12654           Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
12655         else {
12656           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12657           Mask.assign(NumVectorElts, Context->getConstantInt(Type::Int32Ty,
12658                                                        NumVectorElts));
12659         } 
12660         Mask[InsertedIdx] = 
12661                            Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12662         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12663                                      Context->getConstantVector(Mask));
12664       }
12665       
12666       // If this insertelement isn't used by some other insertelement, turn it
12667       // (and any insertelements it points to), into one big shuffle.
12668       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12669         std::vector<Constant*> Mask;
12670         Value *RHS = 0;
12671         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12672         if (RHS == 0) RHS = Context->getUndef(LHS->getType());
12673         // We now have a shuffle of LHS, RHS, Mask.
12674         return new ShuffleVectorInst(LHS, RHS,
12675                                      Context->getConstantVector(Mask));
12676       }
12677     }
12678   }
12679
12680   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12681   APInt UndefElts(VWidth, 0);
12682   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12683   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12684     return &IE;
12685
12686   return 0;
12687 }
12688
12689
12690 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12691   Value *LHS = SVI.getOperand(0);
12692   Value *RHS = SVI.getOperand(1);
12693   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12694
12695   bool MadeChange = false;
12696
12697   // Undefined shuffle mask -> undefined value.
12698   if (isa<UndefValue>(SVI.getOperand(2)))
12699     return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
12700
12701   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12702
12703   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12704     return 0;
12705
12706   APInt UndefElts(VWidth, 0);
12707   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12708   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12709     LHS = SVI.getOperand(0);
12710     RHS = SVI.getOperand(1);
12711     MadeChange = true;
12712   }
12713   
12714   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12715   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12716   if (LHS == RHS || isa<UndefValue>(LHS)) {
12717     if (isa<UndefValue>(LHS) && LHS == RHS) {
12718       // shuffle(undef,undef,mask) -> undef.
12719       return ReplaceInstUsesWith(SVI, LHS);
12720     }
12721     
12722     // Remap any references to RHS to use LHS.
12723     std::vector<Constant*> Elts;
12724     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12725       if (Mask[i] >= 2*e)
12726         Elts.push_back(Context->getUndef(Type::Int32Ty));
12727       else {
12728         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12729             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12730           Mask[i] = 2*e;     // Turn into undef.
12731           Elts.push_back(Context->getUndef(Type::Int32Ty));
12732         } else {
12733           Mask[i] = Mask[i] % e;  // Force to LHS.
12734           Elts.push_back(Context->getConstantInt(Type::Int32Ty, Mask[i]));
12735         }
12736       }
12737     }
12738     SVI.setOperand(0, SVI.getOperand(1));
12739     SVI.setOperand(1, Context->getUndef(RHS->getType()));
12740     SVI.setOperand(2, Context->getConstantVector(Elts));
12741     LHS = SVI.getOperand(0);
12742     RHS = SVI.getOperand(1);
12743     MadeChange = true;
12744   }
12745   
12746   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12747   bool isLHSID = true, isRHSID = true;
12748     
12749   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12750     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12751     // Is this an identity shuffle of the LHS value?
12752     isLHSID &= (Mask[i] == i);
12753       
12754     // Is this an identity shuffle of the RHS value?
12755     isRHSID &= (Mask[i]-e == i);
12756   }
12757
12758   // Eliminate identity shuffles.
12759   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12760   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12761   
12762   // If the LHS is a shufflevector itself, see if we can combine it with this
12763   // one without producing an unusual shuffle.  Here we are really conservative:
12764   // we are absolutely afraid of producing a shuffle mask not in the input
12765   // program, because the code gen may not be smart enough to turn a merged
12766   // shuffle into two specific shuffles: it may produce worse code.  As such,
12767   // we only merge two shuffles if the result is one of the two input shuffle
12768   // masks.  In this case, merging the shuffles just removes one instruction,
12769   // which we know is safe.  This is good for things like turning:
12770   // (splat(splat)) -> splat.
12771   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12772     if (isa<UndefValue>(RHS)) {
12773       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12774
12775       std::vector<unsigned> NewMask;
12776       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12777         if (Mask[i] >= 2*e)
12778           NewMask.push_back(2*e);
12779         else
12780           NewMask.push_back(LHSMask[Mask[i]]);
12781       
12782       // If the result mask is equal to the src shuffle or this shuffle mask, do
12783       // the replacement.
12784       if (NewMask == LHSMask || NewMask == Mask) {
12785         unsigned LHSInNElts =
12786           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12787         std::vector<Constant*> Elts;
12788         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12789           if (NewMask[i] >= LHSInNElts*2) {
12790             Elts.push_back(Context->getUndef(Type::Int32Ty));
12791           } else {
12792             Elts.push_back(Context->getConstantInt(Type::Int32Ty, NewMask[i]));
12793           }
12794         }
12795         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12796                                      LHSSVI->getOperand(1),
12797                                      Context->getConstantVector(Elts));
12798       }
12799     }
12800   }
12801
12802   return MadeChange ? &SVI : 0;
12803 }
12804
12805
12806
12807
12808 /// TryToSinkInstruction - Try to move the specified instruction from its
12809 /// current block into the beginning of DestBlock, which can only happen if it's
12810 /// safe to move the instruction past all of the instructions between it and the
12811 /// end of its block.
12812 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12813   assert(I->hasOneUse() && "Invariants didn't hold!");
12814
12815   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12816   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12817     return false;
12818
12819   // Do not sink alloca instructions out of the entry block.
12820   if (isa<AllocaInst>(I) && I->getParent() ==
12821         &DestBlock->getParent()->getEntryBlock())
12822     return false;
12823
12824   // We can only sink load instructions if there is nothing between the load and
12825   // the end of block that could change the value.
12826   if (I->mayReadFromMemory()) {
12827     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12828          Scan != E; ++Scan)
12829       if (Scan->mayWriteToMemory())
12830         return false;
12831   }
12832
12833   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12834
12835   CopyPrecedingStopPoint(I, InsertPos);
12836   I->moveBefore(InsertPos);
12837   ++NumSunkInst;
12838   return true;
12839 }
12840
12841
12842 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12843 /// all reachable code to the worklist.
12844 ///
12845 /// This has a couple of tricks to make the code faster and more powerful.  In
12846 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12847 /// them to the worklist (this significantly speeds up instcombine on code where
12848 /// many instructions are dead or constant).  Additionally, if we find a branch
12849 /// whose condition is a known constant, we only visit the reachable successors.
12850 ///
12851 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12852                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12853                                        InstCombiner &IC,
12854                                        const TargetData *TD) {
12855   SmallVector<BasicBlock*, 256> Worklist;
12856   Worklist.push_back(BB);
12857
12858   while (!Worklist.empty()) {
12859     BB = Worklist.back();
12860     Worklist.pop_back();
12861     
12862     // We have now visited this block!  If we've already been here, ignore it.
12863     if (!Visited.insert(BB)) continue;
12864
12865     DbgInfoIntrinsic *DBI_Prev = NULL;
12866     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12867       Instruction *Inst = BBI++;
12868       
12869       // DCE instruction if trivially dead.
12870       if (isInstructionTriviallyDead(Inst)) {
12871         ++NumDeadInst;
12872         DOUT << "IC: DCE: " << *Inst;
12873         Inst->eraseFromParent();
12874         continue;
12875       }
12876       
12877       // ConstantProp instruction if trivially constant.
12878       if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12879         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12880         Inst->replaceAllUsesWith(C);
12881         ++NumConstProp;
12882         Inst->eraseFromParent();
12883         continue;
12884       }
12885      
12886       // If there are two consecutive llvm.dbg.stoppoint calls then
12887       // it is likely that the optimizer deleted code in between these
12888       // two intrinsics. 
12889       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12890       if (DBI_Next) {
12891         if (DBI_Prev
12892             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12893             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12894           IC.RemoveFromWorkList(DBI_Prev);
12895           DBI_Prev->eraseFromParent();
12896         }
12897         DBI_Prev = DBI_Next;
12898       } else {
12899         DBI_Prev = 0;
12900       }
12901
12902       IC.AddToWorkList(Inst);
12903     }
12904
12905     // Recursively visit successors.  If this is a branch or switch on a
12906     // constant, only visit the reachable successor.
12907     TerminatorInst *TI = BB->getTerminator();
12908     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12909       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12910         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12911         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12912         Worklist.push_back(ReachableBB);
12913         continue;
12914       }
12915     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12916       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12917         // See if this is an explicit destination.
12918         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12919           if (SI->getCaseValue(i) == Cond) {
12920             BasicBlock *ReachableBB = SI->getSuccessor(i);
12921             Worklist.push_back(ReachableBB);
12922             continue;
12923           }
12924         
12925         // Otherwise it is the default destination.
12926         Worklist.push_back(SI->getSuccessor(0));
12927         continue;
12928       }
12929     }
12930     
12931     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12932       Worklist.push_back(TI->getSuccessor(i));
12933   }
12934 }
12935
12936 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12937   bool Changed = false;
12938   TD = &getAnalysis<TargetData>();
12939   
12940   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12941              << F.getNameStr() << "\n");
12942
12943   {
12944     // Do a depth-first traversal of the function, populate the worklist with
12945     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12946     // track of which blocks we visit.
12947     SmallPtrSet<BasicBlock*, 64> Visited;
12948     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12949
12950     // Do a quick scan over the function.  If we find any blocks that are
12951     // unreachable, remove any instructions inside of them.  This prevents
12952     // the instcombine code from having to deal with some bad special cases.
12953     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12954       if (!Visited.count(BB)) {
12955         Instruction *Term = BB->getTerminator();
12956         while (Term != BB->begin()) {   // Remove instrs bottom-up
12957           BasicBlock::iterator I = Term; --I;
12958
12959           DOUT << "IC: DCE: " << *I;
12960           // A debug intrinsic shouldn't force another iteration if we weren't
12961           // going to do one without it.
12962           if (!isa<DbgInfoIntrinsic>(I)) {
12963             ++NumDeadInst;
12964             Changed = true;
12965           }
12966           if (!I->use_empty())
12967             I->replaceAllUsesWith(Context->getUndef(I->getType()));
12968           I->eraseFromParent();
12969         }
12970       }
12971   }
12972
12973   while (!Worklist.empty()) {
12974     Instruction *I = RemoveOneFromWorkList();
12975     if (I == 0) continue;  // skip null values.
12976
12977     // Check to see if we can DCE the instruction.
12978     if (isInstructionTriviallyDead(I)) {
12979       // Add operands to the worklist.
12980       if (I->getNumOperands() < 4)
12981         AddUsesToWorkList(*I);
12982       ++NumDeadInst;
12983
12984       DOUT << "IC: DCE: " << *I;
12985
12986       I->eraseFromParent();
12987       RemoveFromWorkList(I);
12988       Changed = true;
12989       continue;
12990     }
12991
12992     // Instruction isn't dead, see if we can constant propagate it.
12993     if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12994       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12995
12996       // Add operands to the worklist.
12997       AddUsesToWorkList(*I);
12998       ReplaceInstUsesWith(*I, C);
12999
13000       ++NumConstProp;
13001       I->eraseFromParent();
13002       RemoveFromWorkList(I);
13003       Changed = true;
13004       continue;
13005     }
13006
13007     if (TD) {
13008       // See if we can constant fold its operands.
13009       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13010         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
13011           if (Constant *NewC = ConstantFoldConstantExpression(CE,   
13012                                   F.getContext(), TD))
13013             if (NewC != CE) {
13014               i->set(NewC);
13015               Changed = true;
13016             }
13017     }
13018
13019     // See if we can trivially sink this instruction to a successor basic block.
13020     if (I->hasOneUse()) {
13021       BasicBlock *BB = I->getParent();
13022       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13023       if (UserParent != BB) {
13024         bool UserIsSuccessor = false;
13025         // See if the user is one of our successors.
13026         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13027           if (*SI == UserParent) {
13028             UserIsSuccessor = true;
13029             break;
13030           }
13031
13032         // If the user is one of our immediate successors, and if that successor
13033         // only has us as a predecessors (we'd have to split the critical edge
13034         // otherwise), we can keep going.
13035         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13036             next(pred_begin(UserParent)) == pred_end(UserParent))
13037           // Okay, the CFG is simple enough, try to sink this instruction.
13038           Changed |= TryToSinkInstruction(I, UserParent);
13039       }
13040     }
13041
13042     // Now that we have an instruction, try combining it to simplify it...
13043 #ifndef NDEBUG
13044     std::string OrigI;
13045 #endif
13046     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
13047     if (Instruction *Result = visit(*I)) {
13048       ++NumCombined;
13049       // Should we replace the old instruction with a new one?
13050       if (Result != I) {
13051         DOUT << "IC: Old = " << *I
13052              << "    New = " << *Result;
13053
13054         // Everything uses the new instruction now.
13055         I->replaceAllUsesWith(Result);
13056
13057         // Push the new instruction and any users onto the worklist.
13058         AddToWorkList(Result);
13059         AddUsersToWorkList(*Result);
13060
13061         // Move the name to the new instruction first.
13062         Result->takeName(I);
13063
13064         // Insert the new instruction into the basic block...
13065         BasicBlock *InstParent = I->getParent();
13066         BasicBlock::iterator InsertPos = I;
13067
13068         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
13069           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13070             ++InsertPos;
13071
13072         InstParent->getInstList().insert(InsertPos, Result);
13073
13074         // Make sure that we reprocess all operands now that we reduced their
13075         // use counts.
13076         AddUsesToWorkList(*I);
13077
13078         // Instructions can end up on the worklist more than once.  Make sure
13079         // we do not process an instruction that has been deleted.
13080         RemoveFromWorkList(I);
13081
13082         // Erase the old instruction.
13083         InstParent->getInstList().erase(I);
13084       } else {
13085 #ifndef NDEBUG
13086         DOUT << "IC: Mod = " << OrigI
13087              << "    New = " << *I;
13088 #endif
13089
13090         // If the instruction was modified, it's possible that it is now dead.
13091         // if so, remove it.
13092         if (isInstructionTriviallyDead(I)) {
13093           // Make sure we process all operands now that we are reducing their
13094           // use counts.
13095           AddUsesToWorkList(*I);
13096
13097           // Instructions may end up in the worklist more than once.  Erase all
13098           // occurrences of this instruction.
13099           RemoveFromWorkList(I);
13100           I->eraseFromParent();
13101         } else {
13102           AddToWorkList(I);
13103           AddUsersToWorkList(*I);
13104         }
13105       }
13106       Changed = true;
13107     }
13108   }
13109
13110   assert(WorklistMap.empty() && "Worklist empty, but map not?");
13111     
13112   // Do an explicit clear, this shrinks the map if needed.
13113   WorklistMap.clear();
13114   return Changed;
13115 }
13116
13117
13118 bool InstCombiner::runOnFunction(Function &F) {
13119   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13120   
13121   bool EverMadeChange = false;
13122
13123   // Iterate while there is work to do.
13124   unsigned Iteration = 0;
13125   while (DoOneIteration(F, Iteration++))
13126     EverMadeChange = true;
13127   return EverMadeChange;
13128 }
13129
13130 FunctionPass *llvm::createInstructionCombiningPass() {
13131   return new InstCombiner();
13132 }