Canonicalize bitcasts between types like <1 x i64> and i64 to
[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   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2656     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2657
2658   // Simplify mul instructions with a constant RHS...
2659   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2660     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2661
2662       // ((X << C1)*C2) == (X * (C2 << C1))
2663       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2664         if (SI->getOpcode() == Instruction::Shl)
2665           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2666             return BinaryOperator::CreateMul(SI->getOperand(0),
2667                                         Context->getConstantExprShl(CI, ShOp));
2668
2669       if (CI->isZero())
2670         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2671       if (CI->equalsInt(1))                  // X * 1  == X
2672         return ReplaceInstUsesWith(I, Op0);
2673       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2674         return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2675
2676       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2677       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2678         return BinaryOperator::CreateShl(Op0,
2679                  Context->getConstantInt(Op0->getType(), Val.logBase2()));
2680       }
2681     } else if (isa<VectorType>(Op1->getType())) {
2682       if (Op1->isNullValue())
2683         return ReplaceInstUsesWith(I, Op1);
2684
2685       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2686         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2687           return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2688
2689         // As above, vector X*splat(1.0) -> X in all defined cases.
2690         if (Constant *Splat = Op1V->getSplatValue()) {
2691           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2692             if (CI->equalsInt(1))
2693               return ReplaceInstUsesWith(I, Op0);
2694         }
2695       }
2696     }
2697     
2698     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2699       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2700           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2701         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2702         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2703                                                      Op1, "tmp");
2704         InsertNewInstBefore(Add, I);
2705         Value *C1C2 = Context->getConstantExprMul(Op1, 
2706                                            cast<Constant>(Op0I->getOperand(1)));
2707         return BinaryOperator::CreateAdd(Add, C1C2);
2708         
2709       }
2710
2711     // Try to fold constant mul into select arguments.
2712     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2713       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2714         return R;
2715
2716     if (isa<PHINode>(Op0))
2717       if (Instruction *NV = FoldOpIntoPhi(I))
2718         return NV;
2719   }
2720
2721   if (Value *Op0v = dyn_castNegVal(Op0, Context))     // -X * -Y = X*Y
2722     if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
2723       return BinaryOperator::CreateMul(Op0v, Op1v);
2724
2725   // (X / Y) *  Y = X - (X % Y)
2726   // (X / Y) * -Y = (X % Y) - X
2727   {
2728     Value *Op1 = I.getOperand(1);
2729     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2730     if (!BO ||
2731         (BO->getOpcode() != Instruction::UDiv && 
2732          BO->getOpcode() != Instruction::SDiv)) {
2733       Op1 = Op0;
2734       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2735     }
2736     Value *Neg = dyn_castNegVal(Op1, Context);
2737     if (BO && BO->hasOneUse() &&
2738         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2739         (BO->getOpcode() == Instruction::UDiv ||
2740          BO->getOpcode() == Instruction::SDiv)) {
2741       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2742
2743       Instruction *Rem;
2744       if (BO->getOpcode() == Instruction::UDiv)
2745         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2746       else
2747         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2748
2749       InsertNewInstBefore(Rem, I);
2750       Rem->takeName(BO);
2751
2752       if (Op1BO == Op1)
2753         return BinaryOperator::CreateSub(Op0BO, Rem);
2754       else
2755         return BinaryOperator::CreateSub(Rem, Op0BO);
2756     }
2757   }
2758
2759   if (I.getType() == Type::Int1Ty)
2760     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2761
2762   // If one of the operands of the multiply is a cast from a boolean value, then
2763   // we know the bool is either zero or one, so this is a 'masking' multiply.
2764   // See if we can simplify things based on how the boolean was originally
2765   // formed.
2766   CastInst *BoolCast = 0;
2767   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2768     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2769       BoolCast = CI;
2770   if (!BoolCast)
2771     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2772       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2773         BoolCast = CI;
2774   if (BoolCast) {
2775     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2776       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2777       const Type *SCOpTy = SCIOp0->getType();
2778       bool TIS = false;
2779       
2780       // If the icmp is true iff the sign bit of X is set, then convert this
2781       // multiply into a shift/and combination.
2782       if (isa<ConstantInt>(SCIOp1) &&
2783           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2784           TIS) {
2785         // Shift the X value right to turn it into "all signbits".
2786         Constant *Amt = Context->getConstantInt(SCIOp0->getType(),
2787                                           SCOpTy->getPrimitiveSizeInBits()-1);
2788         Value *V =
2789           InsertNewInstBefore(
2790             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2791                                             BoolCast->getOperand(0)->getName()+
2792                                             ".mask"), I);
2793
2794         // If the multiply type is not the same as the source type, sign extend
2795         // or truncate to the multiply type.
2796         if (I.getType() != V->getType()) {
2797           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2798           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2799           Instruction::CastOps opcode = 
2800             (SrcBits == DstBits ? Instruction::BitCast : 
2801              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2802           V = InsertCastBefore(opcode, V, I.getType(), I);
2803         }
2804
2805         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2806         return BinaryOperator::CreateAnd(V, OtherOp);
2807       }
2808     }
2809   }
2810
2811   return Changed ? &I : 0;
2812 }
2813
2814 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2815   bool Changed = SimplifyCommutative(I);
2816   Value *Op0 = I.getOperand(0);
2817
2818   // Simplify mul instructions with a constant RHS...
2819   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2820     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2821       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2822       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2823       if (Op1F->isExactlyValue(1.0))
2824         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2825     } else if (isa<VectorType>(Op1->getType())) {
2826       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2827         // As above, vector X*splat(1.0) -> X in all defined cases.
2828         if (Constant *Splat = Op1V->getSplatValue()) {
2829           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2830             if (F->isExactlyValue(1.0))
2831               return ReplaceInstUsesWith(I, Op0);
2832         }
2833       }
2834     }
2835
2836     // Try to fold constant mul into select arguments.
2837     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2838       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2839         return R;
2840
2841     if (isa<PHINode>(Op0))
2842       if (Instruction *NV = FoldOpIntoPhi(I))
2843         return NV;
2844   }
2845
2846   if (Value *Op0v = dyn_castFNegVal(Op0, Context))     // -X * -Y = X*Y
2847     if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
2848       return BinaryOperator::CreateFMul(Op0v, Op1v);
2849
2850   return Changed ? &I : 0;
2851 }
2852
2853 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2854 /// instruction.
2855 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2856   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2857   
2858   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2859   int NonNullOperand = -1;
2860   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2861     if (ST->isNullValue())
2862       NonNullOperand = 2;
2863   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2864   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2865     if (ST->isNullValue())
2866       NonNullOperand = 1;
2867   
2868   if (NonNullOperand == -1)
2869     return false;
2870   
2871   Value *SelectCond = SI->getOperand(0);
2872   
2873   // Change the div/rem to use 'Y' instead of the select.
2874   I.setOperand(1, SI->getOperand(NonNullOperand));
2875   
2876   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2877   // problem.  However, the select, or the condition of the select may have
2878   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2879   // propagate the known value for the select into other uses of it, and
2880   // propagate a known value of the condition into its other users.
2881   
2882   // If the select and condition only have a single use, don't bother with this,
2883   // early exit.
2884   if (SI->use_empty() && SelectCond->hasOneUse())
2885     return true;
2886   
2887   // Scan the current block backward, looking for other uses of SI.
2888   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2889   
2890   while (BBI != BBFront) {
2891     --BBI;
2892     // If we found a call to a function, we can't assume it will return, so
2893     // information from below it cannot be propagated above it.
2894     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2895       break;
2896     
2897     // Replace uses of the select or its condition with the known values.
2898     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2899          I != E; ++I) {
2900       if (*I == SI) {
2901         *I = SI->getOperand(NonNullOperand);
2902         AddToWorkList(BBI);
2903       } else if (*I == SelectCond) {
2904         *I = NonNullOperand == 1 ? Context->getConstantIntTrue() :
2905                                    Context->getConstantIntFalse();
2906         AddToWorkList(BBI);
2907       }
2908     }
2909     
2910     // If we past the instruction, quit looking for it.
2911     if (&*BBI == SI)
2912       SI = 0;
2913     if (&*BBI == SelectCond)
2914       SelectCond = 0;
2915     
2916     // If we ran out of things to eliminate, break out of the loop.
2917     if (SelectCond == 0 && SI == 0)
2918       break;
2919     
2920   }
2921   return true;
2922 }
2923
2924
2925 /// This function implements the transforms on div instructions that work
2926 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2927 /// used by the visitors to those instructions.
2928 /// @brief Transforms common to all three div instructions
2929 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2930   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2931
2932   // undef / X -> 0        for integer.
2933   // undef / X -> undef    for FP (the undef could be a snan).
2934   if (isa<UndefValue>(Op0)) {
2935     if (Op0->getType()->isFPOrFPVector())
2936       return ReplaceInstUsesWith(I, Op0);
2937     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2938   }
2939
2940   // X / undef -> undef
2941   if (isa<UndefValue>(Op1))
2942     return ReplaceInstUsesWith(I, Op1);
2943
2944   return 0;
2945 }
2946
2947 /// This function implements the transforms common to both integer division
2948 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2949 /// division instructions.
2950 /// @brief Common integer divide transforms
2951 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2952   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2953
2954   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2955   if (Op0 == Op1) {
2956     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2957       Constant *CI = Context->getConstantInt(Ty->getElementType(), 1);
2958       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2959       return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
2960     }
2961
2962     Constant *CI = Context->getConstantInt(I.getType(), 1);
2963     return ReplaceInstUsesWith(I, CI);
2964   }
2965   
2966   if (Instruction *Common = commonDivTransforms(I))
2967     return Common;
2968   
2969   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2970   // This does not apply for fdiv.
2971   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2972     return &I;
2973
2974   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2975     // div X, 1 == X
2976     if (RHS->equalsInt(1))
2977       return ReplaceInstUsesWith(I, Op0);
2978
2979     // (X / C1) / C2  -> X / (C1*C2)
2980     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2981       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2982         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2983           if (MultiplyOverflows(RHS, LHSRHS,
2984                                 I.getOpcode()==Instruction::SDiv, Context))
2985             return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2986           else 
2987             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2988                                       Context->getConstantExprMul(RHS, LHSRHS));
2989         }
2990
2991     if (!RHS->isZero()) { // avoid X udiv 0
2992       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2993         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2994           return R;
2995       if (isa<PHINode>(Op0))
2996         if (Instruction *NV = FoldOpIntoPhi(I))
2997           return NV;
2998     }
2999   }
3000
3001   // 0 / X == 0, we don't need to preserve faults!
3002   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3003     if (LHS->equalsInt(0))
3004       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3005
3006   // It can't be division by zero, hence it must be division by one.
3007   if (I.getType() == Type::Int1Ty)
3008     return ReplaceInstUsesWith(I, Op0);
3009
3010   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3011     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3012       // div X, 1 == X
3013       if (X->isOne())
3014         return ReplaceInstUsesWith(I, Op0);
3015   }
3016
3017   return 0;
3018 }
3019
3020 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3021   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3022
3023   // Handle the integer div common cases
3024   if (Instruction *Common = commonIDivTransforms(I))
3025     return Common;
3026
3027   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3028     // X udiv C^2 -> X >> C
3029     // Check to see if this is an unsigned division with an exact power of 2,
3030     // if so, convert to a right shift.
3031     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3032       return BinaryOperator::CreateLShr(Op0, 
3033             Context->getConstantInt(Op0->getType(), C->getValue().logBase2()));
3034
3035     // X udiv C, where C >= signbit
3036     if (C->getValue().isNegative()) {
3037       Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3038                                                     ICmpInst::ICMP_ULT, Op0, C),
3039                                       I);
3040       return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3041                                 Context->getConstantInt(I.getType(), 1));
3042     }
3043   }
3044
3045   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3046   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3047     if (RHSI->getOpcode() == Instruction::Shl &&
3048         isa<ConstantInt>(RHSI->getOperand(0))) {
3049       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3050       if (C1.isPowerOf2()) {
3051         Value *N = RHSI->getOperand(1);
3052         const Type *NTy = N->getType();
3053         if (uint32_t C2 = C1.logBase2()) {
3054           Constant *C2V = Context->getConstantInt(NTy, C2);
3055           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3056         }
3057         return BinaryOperator::CreateLShr(Op0, N);
3058       }
3059     }
3060   }
3061   
3062   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3063   // where C1&C2 are powers of two.
3064   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3065     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3066       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3067         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3068         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3069           // Compute the shift amounts
3070           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3071           // Construct the "on true" case of the select
3072           Constant *TC = Context->getConstantInt(Op0->getType(), TSA);
3073           Instruction *TSI = BinaryOperator::CreateLShr(
3074                                                  Op0, TC, SI->getName()+".t");
3075           TSI = InsertNewInstBefore(TSI, I);
3076   
3077           // Construct the "on false" case of the select
3078           Constant *FC = Context->getConstantInt(Op0->getType(), FSA); 
3079           Instruction *FSI = BinaryOperator::CreateLShr(
3080                                                  Op0, FC, SI->getName()+".f");
3081           FSI = InsertNewInstBefore(FSI, I);
3082
3083           // construct the select instruction and return it.
3084           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3085         }
3086       }
3087   return 0;
3088 }
3089
3090 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3091   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3092
3093   // Handle the integer div common cases
3094   if (Instruction *Common = commonIDivTransforms(I))
3095     return Common;
3096
3097   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3098     // sdiv X, -1 == -X
3099     if (RHS->isAllOnesValue())
3100       return BinaryOperator::CreateNeg(*Context, Op0);
3101   }
3102
3103   // If the sign bits of both operands are zero (i.e. we can prove they are
3104   // unsigned inputs), turn this into a udiv.
3105   if (I.getType()->isInteger()) {
3106     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3107     if (MaskedValueIsZero(Op0, Mask)) {
3108       if (MaskedValueIsZero(Op1, Mask)) {
3109         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3110         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3111       }
3112       ConstantInt *ShiftedInt;
3113       if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value()), *Context) &&
3114           ShiftedInt->getValue().isPowerOf2()) {
3115         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3116         // Safe because the only negative value (1 << Y) can take on is
3117         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3118         // the sign bit set.
3119         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3120       }
3121     }
3122   }
3123   
3124   return 0;
3125 }
3126
3127 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3128   return commonDivTransforms(I);
3129 }
3130
3131 /// This function implements the transforms on rem instructions that work
3132 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3133 /// is used by the visitors to those instructions.
3134 /// @brief Transforms common to all three rem instructions
3135 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3136   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3137
3138   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3139     if (I.getType()->isFPOrFPVector())
3140       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3141     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3142   }
3143   if (isa<UndefValue>(Op1))
3144     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3145
3146   // Handle cases involving: rem X, (select Cond, Y, Z)
3147   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3148     return &I;
3149
3150   return 0;
3151 }
3152
3153 /// This function implements the transforms common to both integer remainder
3154 /// instructions (urem and srem). It is called by the visitors to those integer
3155 /// remainder instructions.
3156 /// @brief Common integer remainder transforms
3157 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3158   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3159
3160   if (Instruction *common = commonRemTransforms(I))
3161     return common;
3162
3163   // 0 % X == 0 for integer, we don't need to preserve faults!
3164   if (Constant *LHS = dyn_cast<Constant>(Op0))
3165     if (LHS->isNullValue())
3166       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3167
3168   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3169     // X % 0 == undef, we don't need to preserve faults!
3170     if (RHS->equalsInt(0))
3171       return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
3172     
3173     if (RHS->equalsInt(1))  // X % 1 == 0
3174       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3175
3176     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3177       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3178         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3179           return R;
3180       } else if (isa<PHINode>(Op0I)) {
3181         if (Instruction *NV = FoldOpIntoPhi(I))
3182           return NV;
3183       }
3184
3185       // See if we can fold away this rem instruction.
3186       if (SimplifyDemandedInstructionBits(I))
3187         return &I;
3188     }
3189   }
3190
3191   return 0;
3192 }
3193
3194 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3195   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3196
3197   if (Instruction *common = commonIRemTransforms(I))
3198     return common;
3199   
3200   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3201     // X urem C^2 -> X and C
3202     // Check to see if this is an unsigned remainder with an exact power of 2,
3203     // if so, convert to a bitwise and.
3204     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3205       if (C->getValue().isPowerOf2())
3206         return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
3207   }
3208
3209   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3210     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3211     if (RHSI->getOpcode() == Instruction::Shl &&
3212         isa<ConstantInt>(RHSI->getOperand(0))) {
3213       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3214         Constant *N1 = Context->getAllOnesValue(I.getType());
3215         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3216                                                                    "tmp"), I);
3217         return BinaryOperator::CreateAnd(Op0, Add);
3218       }
3219     }
3220   }
3221
3222   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3223   // where C1&C2 are powers of two.
3224   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3225     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3226       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3227         // STO == 0 and SFO == 0 handled above.
3228         if ((STO->getValue().isPowerOf2()) && 
3229             (SFO->getValue().isPowerOf2())) {
3230           Value *TrueAnd = InsertNewInstBefore(
3231             BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3232                                       SI->getName()+".t"), I);
3233           Value *FalseAnd = InsertNewInstBefore(
3234             BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3235                                       SI->getName()+".f"), I);
3236           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3237         }
3238       }
3239   }
3240   
3241   return 0;
3242 }
3243
3244 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3245   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3246
3247   // Handle the integer rem common cases
3248   if (Instruction *common = commonIRemTransforms(I))
3249     return common;
3250   
3251   if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
3252     if (!isa<Constant>(RHSNeg) ||
3253         (isa<ConstantInt>(RHSNeg) &&
3254          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3255       // X % -Y -> X % Y
3256       AddUsesToWorkList(I);
3257       I.setOperand(1, RHSNeg);
3258       return &I;
3259     }
3260
3261   // If the sign bits of both operands are zero (i.e. we can prove they are
3262   // unsigned inputs), turn this into a urem.
3263   if (I.getType()->isInteger()) {
3264     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3265     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3266       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3267       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3268     }
3269   }
3270
3271   // If it's a constant vector, flip any negative values positive.
3272   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3273     unsigned VWidth = RHSV->getNumOperands();
3274
3275     bool hasNegative = false;
3276     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3277       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3278         if (RHS->getValue().isNegative())
3279           hasNegative = true;
3280
3281     if (hasNegative) {
3282       std::vector<Constant *> Elts(VWidth);
3283       for (unsigned i = 0; i != VWidth; ++i) {
3284         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3285           if (RHS->getValue().isNegative())
3286             Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
3287           else
3288             Elts[i] = RHS;
3289         }
3290       }
3291
3292       Constant *NewRHSV = Context->getConstantVector(Elts);
3293       if (NewRHSV != RHSV) {
3294         AddUsesToWorkList(I);
3295         I.setOperand(1, NewRHSV);
3296         return &I;
3297       }
3298     }
3299   }
3300
3301   return 0;
3302 }
3303
3304 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3305   return commonRemTransforms(I);
3306 }
3307
3308 // isOneBitSet - Return true if there is exactly one bit set in the specified
3309 // constant.
3310 static bool isOneBitSet(const ConstantInt *CI) {
3311   return CI->getValue().isPowerOf2();
3312 }
3313
3314 // isHighOnes - Return true if the constant is of the form 1+0+.
3315 // This is the same as lowones(~X).
3316 static bool isHighOnes(const ConstantInt *CI) {
3317   return (~CI->getValue() + 1).isPowerOf2();
3318 }
3319
3320 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3321 /// are carefully arranged to allow folding of expressions such as:
3322 ///
3323 ///      (A < B) | (A > B) --> (A != B)
3324 ///
3325 /// Note that this is only valid if the first and second predicates have the
3326 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3327 ///
3328 /// Three bits are used to represent the condition, as follows:
3329 ///   0  A > B
3330 ///   1  A == B
3331 ///   2  A < B
3332 ///
3333 /// <=>  Value  Definition
3334 /// 000     0   Always false
3335 /// 001     1   A >  B
3336 /// 010     2   A == B
3337 /// 011     3   A >= B
3338 /// 100     4   A <  B
3339 /// 101     5   A != B
3340 /// 110     6   A <= B
3341 /// 111     7   Always true
3342 ///  
3343 static unsigned getICmpCode(const ICmpInst *ICI) {
3344   switch (ICI->getPredicate()) {
3345     // False -> 0
3346   case ICmpInst::ICMP_UGT: return 1;  // 001
3347   case ICmpInst::ICMP_SGT: return 1;  // 001
3348   case ICmpInst::ICMP_EQ:  return 2;  // 010
3349   case ICmpInst::ICMP_UGE: return 3;  // 011
3350   case ICmpInst::ICMP_SGE: return 3;  // 011
3351   case ICmpInst::ICMP_ULT: return 4;  // 100
3352   case ICmpInst::ICMP_SLT: return 4;  // 100
3353   case ICmpInst::ICMP_NE:  return 5;  // 101
3354   case ICmpInst::ICMP_ULE: return 6;  // 110
3355   case ICmpInst::ICMP_SLE: return 6;  // 110
3356     // True -> 7
3357   default:
3358     llvm_unreachable("Invalid ICmp predicate!");
3359     return 0;
3360   }
3361 }
3362
3363 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3364 /// predicate into a three bit mask. It also returns whether it is an ordered
3365 /// predicate by reference.
3366 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3367   isOrdered = false;
3368   switch (CC) {
3369   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3370   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3371   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3372   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3373   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3374   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3375   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3376   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3377   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3378   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3379   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3380   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3381   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3382   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3383     // True -> 7
3384   default:
3385     // Not expecting FCMP_FALSE and FCMP_TRUE;
3386     llvm_unreachable("Unexpected FCmp predicate!");
3387     return 0;
3388   }
3389 }
3390
3391 /// getICmpValue - This is the complement of getICmpCode, which turns an
3392 /// opcode and two operands into either a constant true or false, or a brand 
3393 /// new ICmp instruction. The sign is passed in to determine which kind
3394 /// of predicate to use in the new icmp instruction.
3395 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3396                            LLVMContext *Context) {
3397   switch (code) {
3398   default: llvm_unreachable("Illegal ICmp code!");
3399   case  0: return Context->getConstantIntFalse();
3400   case  1: 
3401     if (sign)
3402       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
3403     else
3404       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3405   case  2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ,  LHS, RHS);
3406   case  3: 
3407     if (sign)
3408       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
3409     else
3410       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
3411   case  4: 
3412     if (sign)
3413       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
3414     else
3415       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3416   case  5: return new ICmpInst(*Context, ICmpInst::ICMP_NE,  LHS, RHS);
3417   case  6: 
3418     if (sign)
3419       return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
3420     else
3421       return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
3422   case  7: return Context->getConstantIntTrue();
3423   }
3424 }
3425
3426 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3427 /// opcode and two operands into either a FCmp instruction. isordered is passed
3428 /// in to determine which kind of predicate to use in the new fcmp instruction.
3429 static Value *getFCmpValue(bool isordered, unsigned code,
3430                            Value *LHS, Value *RHS, LLVMContext *Context) {
3431   switch (code) {
3432   default: llvm_unreachable("Illegal FCmp code!");
3433   case  0:
3434     if (isordered)
3435       return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
3436     else
3437       return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
3438   case  1: 
3439     if (isordered)
3440       return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
3441     else
3442       return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
3443   case  2: 
3444     if (isordered)
3445       return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
3446     else
3447       return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
3448   case  3: 
3449     if (isordered)
3450       return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
3451     else
3452       return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
3453   case  4: 
3454     if (isordered)
3455       return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
3456     else
3457       return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
3458   case  5: 
3459     if (isordered)
3460       return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
3461     else
3462       return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
3463   case  6: 
3464     if (isordered)
3465       return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
3466     else
3467       return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
3468   case  7: return Context->getConstantIntTrue();
3469   }
3470 }
3471
3472 /// PredicatesFoldable - Return true if both predicates match sign or if at
3473 /// least one of them is an equality comparison (which is signless).
3474 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3475   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3476          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3477          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3478 }
3479
3480 namespace { 
3481 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3482 struct FoldICmpLogical {
3483   InstCombiner &IC;
3484   Value *LHS, *RHS;
3485   ICmpInst::Predicate pred;
3486   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3487     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3488       pred(ICI->getPredicate()) {}
3489   bool shouldApply(Value *V) const {
3490     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3491       if (PredicatesFoldable(pred, ICI->getPredicate()))
3492         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3493                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3494     return false;
3495   }
3496   Instruction *apply(Instruction &Log) const {
3497     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3498     if (ICI->getOperand(0) != LHS) {
3499       assert(ICI->getOperand(1) == LHS);
3500       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3501     }
3502
3503     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3504     unsigned LHSCode = getICmpCode(ICI);
3505     unsigned RHSCode = getICmpCode(RHSICI);
3506     unsigned Code;
3507     switch (Log.getOpcode()) {
3508     case Instruction::And: Code = LHSCode & RHSCode; break;
3509     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3510     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3511     default: llvm_unreachable("Illegal logical opcode!"); return 0;
3512     }
3513
3514     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3515                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3516       
3517     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3518     if (Instruction *I = dyn_cast<Instruction>(RV))
3519       return I;
3520     // Otherwise, it's a constant boolean value...
3521     return IC.ReplaceInstUsesWith(Log, RV);
3522   }
3523 };
3524 } // end anonymous namespace
3525
3526 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3527 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3528 // guaranteed to be a binary operator.
3529 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3530                                     ConstantInt *OpRHS,
3531                                     ConstantInt *AndRHS,
3532                                     BinaryOperator &TheAnd) {
3533   Value *X = Op->getOperand(0);
3534   Constant *Together = 0;
3535   if (!Op->isShift())
3536     Together = Context->getConstantExprAnd(AndRHS, OpRHS);
3537
3538   switch (Op->getOpcode()) {
3539   case Instruction::Xor:
3540     if (Op->hasOneUse()) {
3541       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3542       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3543       InsertNewInstBefore(And, TheAnd);
3544       And->takeName(Op);
3545       return BinaryOperator::CreateXor(And, Together);
3546     }
3547     break;
3548   case Instruction::Or:
3549     if (Together == AndRHS) // (X | C) & C --> C
3550       return ReplaceInstUsesWith(TheAnd, AndRHS);
3551
3552     if (Op->hasOneUse() && Together != OpRHS) {
3553       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3554       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3555       InsertNewInstBefore(Or, TheAnd);
3556       Or->takeName(Op);
3557       return BinaryOperator::CreateAnd(Or, AndRHS);
3558     }
3559     break;
3560   case Instruction::Add:
3561     if (Op->hasOneUse()) {
3562       // Adding a one to a single bit bit-field should be turned into an XOR
3563       // of the bit.  First thing to check is to see if this AND is with a
3564       // single bit constant.
3565       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3566
3567       // If there is only one bit set...
3568       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3569         // Ok, at this point, we know that we are masking the result of the
3570         // ADD down to exactly one bit.  If the constant we are adding has
3571         // no bits set below this bit, then we can eliminate the ADD.
3572         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3573
3574         // Check to see if any bits below the one bit set in AndRHSV are set.
3575         if ((AddRHS & (AndRHSV-1)) == 0) {
3576           // If not, the only thing that can effect the output of the AND is
3577           // the bit specified by AndRHSV.  If that bit is set, the effect of
3578           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3579           // no effect.
3580           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3581             TheAnd.setOperand(0, X);
3582             return &TheAnd;
3583           } else {
3584             // Pull the XOR out of the AND.
3585             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3586             InsertNewInstBefore(NewAnd, TheAnd);
3587             NewAnd->takeName(Op);
3588             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3589           }
3590         }
3591       }
3592     }
3593     break;
3594
3595   case Instruction::Shl: {
3596     // We know that the AND will not produce any of the bits shifted in, so if
3597     // the anded constant includes them, clear them now!
3598     //
3599     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3600     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3601     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3602     ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShlMask);
3603
3604     if (CI->getValue() == ShlMask) { 
3605     // Masking out bits that the shift already masks
3606       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3607     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3608       TheAnd.setOperand(1, CI);
3609       return &TheAnd;
3610     }
3611     break;
3612   }
3613   case Instruction::LShr:
3614   {
3615     // We know that the AND will not produce any of the bits shifted in, so if
3616     // the anded constant includes them, clear them now!  This only applies to
3617     // unsigned shifts, because a signed shr may bring in set bits!
3618     //
3619     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3620     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3621     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3622     ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3623
3624     if (CI->getValue() == ShrMask) {   
3625     // Masking out bits that the shift already masks.
3626       return ReplaceInstUsesWith(TheAnd, Op);
3627     } else if (CI != AndRHS) {
3628       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3629       return &TheAnd;
3630     }
3631     break;
3632   }
3633   case Instruction::AShr:
3634     // Signed shr.
3635     // See if this is shifting in some sign extension, then masking it out
3636     // with an and.
3637     if (Op->hasOneUse()) {
3638       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3639       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3640       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3641       Constant *C = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3642       if (C == AndRHS) {          // Masking out bits shifted in.
3643         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3644         // Make the argument unsigned.
3645         Value *ShVal = Op->getOperand(0);
3646         ShVal = InsertNewInstBefore(
3647             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3648                                    Op->getName()), TheAnd);
3649         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3650       }
3651     }
3652     break;
3653   }
3654   return 0;
3655 }
3656
3657
3658 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3659 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3660 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3661 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3662 /// insert new instructions.
3663 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3664                                            bool isSigned, bool Inside, 
3665                                            Instruction &IB) {
3666   assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ? 
3667             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3668          "Lo is not <= Hi in range emission code!");
3669     
3670   if (Inside) {
3671     if (Lo == Hi)  // Trivially false.
3672       return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
3673
3674     // V >= Min && V < Hi --> V < Hi
3675     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3676       ICmpInst::Predicate pred = (isSigned ? 
3677         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3678       return new ICmpInst(*Context, pred, V, Hi);
3679     }
3680
3681     // Emit V-Lo <u Hi-Lo
3682     Constant *NegLo = Context->getConstantExprNeg(Lo);
3683     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3684     InsertNewInstBefore(Add, IB);
3685     Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
3686     return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
3687   }
3688
3689   if (Lo == Hi)  // Trivially true.
3690     return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
3691
3692   // V < Min || V >= Hi -> V > Hi-1
3693   Hi = SubOne(cast<ConstantInt>(Hi), Context);
3694   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3695     ICmpInst::Predicate pred = (isSigned ? 
3696         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3697     return new ICmpInst(*Context, pred, V, Hi);
3698   }
3699
3700   // Emit V-Lo >u Hi-1-Lo
3701   // Note that Hi has already had one subtracted from it, above.
3702   ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
3703   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3704   InsertNewInstBefore(Add, IB);
3705   Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
3706   return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
3707 }
3708
3709 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3710 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3711 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3712 // not, since all 1s are not contiguous.
3713 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3714   const APInt& V = Val->getValue();
3715   uint32_t BitWidth = Val->getType()->getBitWidth();
3716   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3717
3718   // look for the first zero bit after the run of ones
3719   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3720   // look for the first non-zero bit
3721   ME = V.getActiveBits(); 
3722   return true;
3723 }
3724
3725 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3726 /// where isSub determines whether the operator is a sub.  If we can fold one of
3727 /// the following xforms:
3728 /// 
3729 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3730 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3731 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3732 ///
3733 /// return (A +/- B).
3734 ///
3735 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3736                                         ConstantInt *Mask, bool isSub,
3737                                         Instruction &I) {
3738   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3739   if (!LHSI || LHSI->getNumOperands() != 2 ||
3740       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3741
3742   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3743
3744   switch (LHSI->getOpcode()) {
3745   default: return 0;
3746   case Instruction::And:
3747     if (Context->getConstantExprAnd(N, Mask) == Mask) {
3748       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3749       if ((Mask->getValue().countLeadingZeros() + 
3750            Mask->getValue().countPopulation()) == 
3751           Mask->getValue().getBitWidth())
3752         break;
3753
3754       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3755       // part, we don't need any explicit masks to take them out of A.  If that
3756       // is all N is, ignore it.
3757       uint32_t MB = 0, ME = 0;
3758       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3759         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3760         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3761         if (MaskedValueIsZero(RHS, Mask))
3762           break;
3763       }
3764     }
3765     return 0;
3766   case Instruction::Or:
3767   case Instruction::Xor:
3768     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3769     if ((Mask->getValue().countLeadingZeros() + 
3770          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3771         && Context->getConstantExprAnd(N, Mask)->isNullValue())
3772       break;
3773     return 0;
3774   }
3775   
3776   Instruction *New;
3777   if (isSub)
3778     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3779   else
3780     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3781   return InsertNewInstBefore(New, I);
3782 }
3783
3784 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3785 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3786                                           ICmpInst *LHS, ICmpInst *RHS) {
3787   Value *Val, *Val2;
3788   ConstantInt *LHSCst, *RHSCst;
3789   ICmpInst::Predicate LHSCC, RHSCC;
3790   
3791   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3792   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3793                          m_ConstantInt(LHSCst)), *Context) ||
3794       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3795                          m_ConstantInt(RHSCst)), *Context))
3796     return 0;
3797   
3798   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3799   // where C is a power of 2
3800   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3801       LHSCst->getValue().isPowerOf2()) {
3802     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3803     InsertNewInstBefore(NewOr, I);
3804     return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
3805   }
3806   
3807   // From here on, we only handle:
3808   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3809   if (Val != Val2) return 0;
3810   
3811   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3812   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3813       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3814       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3815       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3816     return 0;
3817   
3818   // We can't fold (ugt x, C) & (sgt x, C2).
3819   if (!PredicatesFoldable(LHSCC, RHSCC))
3820     return 0;
3821     
3822   // Ensure that the larger constant is on the RHS.
3823   bool ShouldSwap;
3824   if (ICmpInst::isSignedPredicate(LHSCC) ||
3825       (ICmpInst::isEquality(LHSCC) && 
3826        ICmpInst::isSignedPredicate(RHSCC)))
3827     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3828   else
3829     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3830     
3831   if (ShouldSwap) {
3832     std::swap(LHS, RHS);
3833     std::swap(LHSCst, RHSCst);
3834     std::swap(LHSCC, RHSCC);
3835   }
3836
3837   // At this point, we know we have have two icmp instructions
3838   // comparing a value against two constants and and'ing the result
3839   // together.  Because of the above check, we know that we only have
3840   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3841   // (from the FoldICmpLogical check above), that the two constants 
3842   // are not equal and that the larger constant is on the RHS
3843   assert(LHSCst != RHSCst && "Compares not folded above?");
3844
3845   switch (LHSCC) {
3846   default: llvm_unreachable("Unknown integer condition code!");
3847   case ICmpInst::ICMP_EQ:
3848     switch (RHSCC) {
3849     default: llvm_unreachable("Unknown integer condition code!");
3850     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3851     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3852     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3853       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3854     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3855     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3856     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3857       return ReplaceInstUsesWith(I, LHS);
3858     }
3859   case ICmpInst::ICMP_NE:
3860     switch (RHSCC) {
3861     default: llvm_unreachable("Unknown integer condition code!");
3862     case ICmpInst::ICMP_ULT:
3863       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
3864         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
3865       break;                        // (X != 13 & X u< 15) -> no change
3866     case ICmpInst::ICMP_SLT:
3867       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
3868         return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
3869       break;                        // (X != 13 & X s< 15) -> no change
3870     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3871     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3872     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3873       return ReplaceInstUsesWith(I, RHS);
3874     case ICmpInst::ICMP_NE:
3875       if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3876         Constant *AddCST = Context->getConstantExprNeg(LHSCst);
3877         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3878                                                      Val->getName()+".off");
3879         InsertNewInstBefore(Add, I);
3880         return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
3881                             Context->getConstantInt(Add->getType(), 1));
3882       }
3883       break;                        // (X != 13 & X != 15) -> no change
3884     }
3885     break;
3886   case ICmpInst::ICMP_ULT:
3887     switch (RHSCC) {
3888     default: llvm_unreachable("Unknown integer condition code!");
3889     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3890     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3891       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3892     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3893       break;
3894     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3895     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3896       return ReplaceInstUsesWith(I, LHS);
3897     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3898       break;
3899     }
3900     break;
3901   case ICmpInst::ICMP_SLT:
3902     switch (RHSCC) {
3903     default: llvm_unreachable("Unknown integer condition code!");
3904     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3905     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3906       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3907     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3908       break;
3909     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3910     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3911       return ReplaceInstUsesWith(I, LHS);
3912     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3913       break;
3914     }
3915     break;
3916   case ICmpInst::ICMP_UGT:
3917     switch (RHSCC) {
3918     default: llvm_unreachable("Unknown integer condition code!");
3919     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3920     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3921       return ReplaceInstUsesWith(I, RHS);
3922     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3923       break;
3924     case ICmpInst::ICMP_NE:
3925       if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
3926         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3927       break;                        // (X u> 13 & X != 15) -> no change
3928     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3929       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3930                              RHSCst, false, true, I);
3931     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3932       break;
3933     }
3934     break;
3935   case ICmpInst::ICMP_SGT:
3936     switch (RHSCC) {
3937     default: llvm_unreachable("Unknown integer condition code!");
3938     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3939     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3940       return ReplaceInstUsesWith(I, RHS);
3941     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3942       break;
3943     case ICmpInst::ICMP_NE:
3944       if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
3945         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3946       break;                        // (X s> 13 & X != 15) -> no change
3947     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3948       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3949                              RHSCst, true, true, I);
3950     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3951       break;
3952     }
3953     break;
3954   }
3955  
3956   return 0;
3957 }
3958
3959
3960 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3961   bool Changed = SimplifyCommutative(I);
3962   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3963
3964   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3965     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3966
3967   // and X, X = X
3968   if (Op0 == Op1)
3969     return ReplaceInstUsesWith(I, Op1);
3970
3971   // See if we can simplify any instructions used by the instruction whose sole 
3972   // purpose is to compute bits we don't care about.
3973   if (SimplifyDemandedInstructionBits(I))
3974     return &I;
3975   if (isa<VectorType>(I.getType())) {
3976     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3977       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3978         return ReplaceInstUsesWith(I, I.getOperand(0));
3979     } else if (isa<ConstantAggregateZero>(Op1)) {
3980       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3981     }
3982   }
3983
3984   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3985     const APInt& AndRHSMask = AndRHS->getValue();
3986     APInt NotAndRHS(~AndRHSMask);
3987
3988     // Optimize a variety of ((val OP C1) & C2) combinations...
3989     if (isa<BinaryOperator>(Op0)) {
3990       Instruction *Op0I = cast<Instruction>(Op0);
3991       Value *Op0LHS = Op0I->getOperand(0);
3992       Value *Op0RHS = Op0I->getOperand(1);
3993       switch (Op0I->getOpcode()) {
3994       case Instruction::Xor:
3995       case Instruction::Or:
3996         // If the mask is only needed on one incoming arm, push it up.
3997         if (Op0I->hasOneUse()) {
3998           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3999             // Not masking anything out for the LHS, move to RHS.
4000             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
4001                                                    Op0RHS->getName()+".masked");
4002             InsertNewInstBefore(NewRHS, I);
4003             return BinaryOperator::Create(
4004                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4005           }
4006           if (!isa<Constant>(Op0RHS) &&
4007               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4008             // Not masking anything out for the RHS, move to LHS.
4009             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
4010                                                    Op0LHS->getName()+".masked");
4011             InsertNewInstBefore(NewLHS, I);
4012             return BinaryOperator::Create(
4013                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4014           }
4015         }
4016
4017         break;
4018       case Instruction::Add:
4019         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4020         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4021         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4022         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4023           return BinaryOperator::CreateAnd(V, AndRHS);
4024         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4025           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4026         break;
4027
4028       case Instruction::Sub:
4029         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4030         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4031         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4032         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4033           return BinaryOperator::CreateAnd(V, AndRHS);
4034
4035         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4036         // has 1's for all bits that the subtraction with A might affect.
4037         if (Op0I->hasOneUse()) {
4038           uint32_t BitWidth = AndRHSMask.getBitWidth();
4039           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4040           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4041
4042           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4043           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4044               MaskedValueIsZero(Op0LHS, Mask)) {
4045             Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
4046             InsertNewInstBefore(NewNeg, I);
4047             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4048           }
4049         }
4050         break;
4051
4052       case Instruction::Shl:
4053       case Instruction::LShr:
4054         // (1 << x) & 1 --> zext(x == 0)
4055         // (1 >> x) & 1 --> zext(x == 0)
4056         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4057           Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4058                                     Op0RHS, Context->getNullValue(I.getType()));
4059           InsertNewInstBefore(NewICmp, I);
4060           return new ZExtInst(NewICmp, I.getType());
4061         }
4062         break;
4063       }
4064
4065       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4066         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4067           return Res;
4068     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4069       // If this is an integer truncation or change from signed-to-unsigned, and
4070       // if the source is an and/or with immediate, transform it.  This
4071       // frequently occurs for bitfield accesses.
4072       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4073         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4074             CastOp->getNumOperands() == 2)
4075           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4076             if (CastOp->getOpcode() == Instruction::And) {
4077               // Change: and (cast (and X, C1) to T), C2
4078               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4079               // This will fold the two constants together, which may allow 
4080               // other simplifications.
4081               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4082                 CastOp->getOperand(0), I.getType(), 
4083                 CastOp->getName()+".shrunk");
4084               NewCast = InsertNewInstBefore(NewCast, I);
4085               // trunc_or_bitcast(C1)&C2
4086               Constant *C3 =
4087                       Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4088               C3 = Context->getConstantExprAnd(C3, AndRHS);
4089               return BinaryOperator::CreateAnd(NewCast, C3);
4090             } else if (CastOp->getOpcode() == Instruction::Or) {
4091               // Change: and (cast (or X, C1) to T), C2
4092               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4093               Constant *C3 =
4094                       Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4095               if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4096                 // trunc(C1)&C2
4097                 return ReplaceInstUsesWith(I, AndRHS);
4098             }
4099           }
4100       }
4101     }
4102
4103     // Try to fold constant and into select arguments.
4104     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4105       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4106         return R;
4107     if (isa<PHINode>(Op0))
4108       if (Instruction *NV = FoldOpIntoPhi(I))
4109         return NV;
4110   }
4111
4112   Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4113   Value *Op1NotVal = dyn_castNotVal(Op1, Context);
4114
4115   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4116     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
4117
4118   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4119   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4120     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4121                                                I.getName()+".demorgan");
4122     InsertNewInstBefore(Or, I);
4123     return BinaryOperator::CreateNot(*Context, Or);
4124   }
4125   
4126   {
4127     Value *A = 0, *B = 0, *C = 0, *D = 0;
4128     if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
4129       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4130         return ReplaceInstUsesWith(I, Op1);
4131     
4132       // (A|B) & ~(A&B) -> A^B
4133       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4134         if ((A == C && B == D) || (A == D && B == C))
4135           return BinaryOperator::CreateXor(A, B);
4136       }
4137     }
4138     
4139     if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
4140       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4141         return ReplaceInstUsesWith(I, Op0);
4142
4143       // ~(A&B) & (A|B) -> A^B
4144       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4145         if ((A == C && B == D) || (A == D && B == C))
4146           return BinaryOperator::CreateXor(A, B);
4147       }
4148     }
4149     
4150     if (Op0->hasOneUse() &&
4151         match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4152       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4153         I.swapOperands();     // Simplify below
4154         std::swap(Op0, Op1);
4155       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4156         cast<BinaryOperator>(Op0)->swapOperands();
4157         I.swapOperands();     // Simplify below
4158         std::swap(Op0, Op1);
4159       }
4160     }
4161
4162     if (Op1->hasOneUse() &&
4163         match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4164       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4165         cast<BinaryOperator>(Op1)->swapOperands();
4166         std::swap(A, B);
4167       }
4168       if (A == Op0) {                                // A&(A^B) -> A & ~B
4169         Instruction *NotB = BinaryOperator::CreateNot(*Context, B, "tmp");
4170         InsertNewInstBefore(NotB, I);
4171         return BinaryOperator::CreateAnd(A, NotB);
4172       }
4173     }
4174
4175     // (A&((~A)|B)) -> A&B
4176     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4177         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
4178       return BinaryOperator::CreateAnd(A, Op1);
4179     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4180         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
4181       return BinaryOperator::CreateAnd(A, Op0);
4182   }
4183   
4184   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4185     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4186     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4187       return R;
4188
4189     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4190       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4191         return Res;
4192   }
4193
4194   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4195   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4196     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4197       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4198         const Type *SrcTy = Op0C->getOperand(0)->getType();
4199         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4200             // Only do this if the casts both really cause code to be generated.
4201             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4202                               I.getType(), TD) &&
4203             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4204                               I.getType(), TD)) {
4205           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4206                                                          Op1C->getOperand(0),
4207                                                          I.getName());
4208           InsertNewInstBefore(NewOp, I);
4209           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4210         }
4211       }
4212     
4213   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4214   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4215     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4216       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4217           SI0->getOperand(1) == SI1->getOperand(1) &&
4218           (SI0->hasOneUse() || SI1->hasOneUse())) {
4219         Instruction *NewOp =
4220           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4221                                                         SI1->getOperand(0),
4222                                                         SI0->getName()), I);
4223         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4224                                       SI1->getOperand(1));
4225       }
4226   }
4227
4228   // If and'ing two fcmp, try combine them into one.
4229   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4230     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4231       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4232           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4233         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4234         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4235           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4236             // If either of the constants are nans, then the whole thing returns
4237             // false.
4238             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4239               return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4240             return new FCmpInst(*Context, FCmpInst::FCMP_ORD, 
4241                                 LHS->getOperand(0), RHS->getOperand(0));
4242           }
4243       } else {
4244         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4245         FCmpInst::Predicate Op0CC, Op1CC;
4246         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4247                   m_Value(Op0RHS)), *Context) &&
4248             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4249                   m_Value(Op1RHS)), *Context)) {
4250           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4251             // Swap RHS operands to match LHS.
4252             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4253             std::swap(Op1LHS, Op1RHS);
4254           }
4255           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4256             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4257             if (Op0CC == Op1CC)
4258               return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4259                                   Op0LHS, Op0RHS);
4260             else if (Op0CC == FCmpInst::FCMP_FALSE ||
4261                      Op1CC == FCmpInst::FCMP_FALSE)
4262               return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4263             else if (Op0CC == FCmpInst::FCMP_TRUE)
4264               return ReplaceInstUsesWith(I, Op1);
4265             else if (Op1CC == FCmpInst::FCMP_TRUE)
4266               return ReplaceInstUsesWith(I, Op0);
4267             bool Op0Ordered;
4268             bool Op1Ordered;
4269             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4270             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4271             if (Op1Pred == 0) {
4272               std::swap(Op0, Op1);
4273               std::swap(Op0Pred, Op1Pred);
4274               std::swap(Op0Ordered, Op1Ordered);
4275             }
4276             if (Op0Pred == 0) {
4277               // uno && ueq -> uno && (uno || eq) -> ueq
4278               // ord && olt -> ord && (ord && lt) -> olt
4279               if (Op0Ordered == Op1Ordered)
4280                 return ReplaceInstUsesWith(I, Op1);
4281               // uno && oeq -> uno && (ord && eq) -> false
4282               // uno && ord -> false
4283               if (!Op0Ordered)
4284                 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4285               // ord && ueq -> ord && (uno || eq) -> oeq
4286               return cast<Instruction>(getFCmpValue(true, Op1Pred,
4287                                                     Op0LHS, Op0RHS, Context));
4288             }
4289           }
4290         }
4291       }
4292     }
4293   }
4294
4295   return Changed ? &I : 0;
4296 }
4297
4298 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4299 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4300 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4301 /// the expression came from the corresponding "byte swapped" byte in some other
4302 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4303 /// we know that the expression deposits the low byte of %X into the high byte
4304 /// of the bswap result and that all other bytes are zero.  This expression is
4305 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4306 /// match.
4307 ///
4308 /// This function returns true if the match was unsuccessful and false if so.
4309 /// On entry to the function the "OverallLeftShift" is a signed integer value
4310 /// indicating the number of bytes that the subexpression is later shifted.  For
4311 /// example, if the expression is later right shifted by 16 bits, the
4312 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4313 /// byte of ByteValues is actually being set.
4314 ///
4315 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4316 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4317 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4318 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4319 /// always in the local (OverallLeftShift) coordinate space.
4320 ///
4321 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4322                               SmallVector<Value*, 8> &ByteValues) {
4323   if (Instruction *I = dyn_cast<Instruction>(V)) {
4324     // If this is an or instruction, it may be an inner node of the bswap.
4325     if (I->getOpcode() == Instruction::Or) {
4326       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4327                                ByteValues) ||
4328              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4329                                ByteValues);
4330     }
4331   
4332     // If this is a logical shift by a constant multiple of 8, recurse with
4333     // OverallLeftShift and ByteMask adjusted.
4334     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4335       unsigned ShAmt = 
4336         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4337       // Ensure the shift amount is defined and of a byte value.
4338       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4339         return true;
4340
4341       unsigned ByteShift = ShAmt >> 3;
4342       if (I->getOpcode() == Instruction::Shl) {
4343         // X << 2 -> collect(X, +2)
4344         OverallLeftShift += ByteShift;
4345         ByteMask >>= ByteShift;
4346       } else {
4347         // X >>u 2 -> collect(X, -2)
4348         OverallLeftShift -= ByteShift;
4349         ByteMask <<= ByteShift;
4350         ByteMask &= (~0U >> (32-ByteValues.size()));
4351       }
4352
4353       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4354       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4355
4356       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4357                                ByteValues);
4358     }
4359
4360     // If this is a logical 'and' with a mask that clears bytes, clear the
4361     // corresponding bytes in ByteMask.
4362     if (I->getOpcode() == Instruction::And &&
4363         isa<ConstantInt>(I->getOperand(1))) {
4364       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4365       unsigned NumBytes = ByteValues.size();
4366       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4367       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4368       
4369       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4370         // If this byte is masked out by a later operation, we don't care what
4371         // the and mask is.
4372         if ((ByteMask & (1 << i)) == 0)
4373           continue;
4374         
4375         // If the AndMask is all zeros for this byte, clear the bit.
4376         APInt MaskB = AndMask & Byte;
4377         if (MaskB == 0) {
4378           ByteMask &= ~(1U << i);
4379           continue;
4380         }
4381         
4382         // If the AndMask is not all ones for this byte, it's not a bytezap.
4383         if (MaskB != Byte)
4384           return true;
4385
4386         // Otherwise, this byte is kept.
4387       }
4388
4389       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4390                                ByteValues);
4391     }
4392   }
4393   
4394   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4395   // the input value to the bswap.  Some observations: 1) if more than one byte
4396   // is demanded from this input, then it could not be successfully assembled
4397   // into a byteswap.  At least one of the two bytes would not be aligned with
4398   // their ultimate destination.
4399   if (!isPowerOf2_32(ByteMask)) return true;
4400   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4401   
4402   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4403   // is demanded, it needs to go into byte 0 of the result.  This means that the
4404   // byte needs to be shifted until it lands in the right byte bucket.  The
4405   // shift amount depends on the position: if the byte is coming from the high
4406   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4407   // low part, it must be shifted left.
4408   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4409   if (InputByteNo < ByteValues.size()/2) {
4410     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4411       return true;
4412   } else {
4413     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4414       return true;
4415   }
4416   
4417   // If the destination byte value is already defined, the values are or'd
4418   // together, which isn't a bswap (unless it's an or of the same bits).
4419   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4420     return true;
4421   ByteValues[DestByteNo] = V;
4422   return false;
4423 }
4424
4425 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4426 /// If so, insert the new bswap intrinsic and return it.
4427 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4428   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4429   if (!ITy || ITy->getBitWidth() % 16 || 
4430       // ByteMask only allows up to 32-byte values.
4431       ITy->getBitWidth() > 32*8) 
4432     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4433   
4434   /// ByteValues - For each byte of the result, we keep track of which value
4435   /// defines each byte.
4436   SmallVector<Value*, 8> ByteValues;
4437   ByteValues.resize(ITy->getBitWidth()/8);
4438     
4439   // Try to find all the pieces corresponding to the bswap.
4440   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4441   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4442     return 0;
4443   
4444   // Check to see if all of the bytes come from the same value.
4445   Value *V = ByteValues[0];
4446   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4447   
4448   // Check to make sure that all of the bytes come from the same value.
4449   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4450     if (ByteValues[i] != V)
4451       return 0;
4452   const Type *Tys[] = { ITy };
4453   Module *M = I.getParent()->getParent()->getParent();
4454   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4455   return CallInst::Create(F, V);
4456 }
4457
4458 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4459 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4460 /// we can simplify this expression to "cond ? C : D or B".
4461 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4462                                          Value *C, Value *D,
4463                                          LLVMContext *Context) {
4464   // If A is not a select of -1/0, this cannot match.
4465   Value *Cond = 0;
4466   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
4467     return 0;
4468
4469   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4470   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4471     return SelectInst::Create(Cond, C, B);
4472   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4473     return SelectInst::Create(Cond, C, B);
4474   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4475   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4476     return SelectInst::Create(Cond, C, D);
4477   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4478     return SelectInst::Create(Cond, C, D);
4479   return 0;
4480 }
4481
4482 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4483 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4484                                          ICmpInst *LHS, ICmpInst *RHS) {
4485   Value *Val, *Val2;
4486   ConstantInt *LHSCst, *RHSCst;
4487   ICmpInst::Predicate LHSCC, RHSCC;
4488   
4489   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4490   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4491              m_ConstantInt(LHSCst)), *Context) ||
4492       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4493              m_ConstantInt(RHSCst)), *Context))
4494     return 0;
4495   
4496   // From here on, we only handle:
4497   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4498   if (Val != Val2) return 0;
4499   
4500   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4501   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4502       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4503       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4504       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4505     return 0;
4506   
4507   // We can't fold (ugt x, C) | (sgt x, C2).
4508   if (!PredicatesFoldable(LHSCC, RHSCC))
4509     return 0;
4510   
4511   // Ensure that the larger constant is on the RHS.
4512   bool ShouldSwap;
4513   if (ICmpInst::isSignedPredicate(LHSCC) ||
4514       (ICmpInst::isEquality(LHSCC) && 
4515        ICmpInst::isSignedPredicate(RHSCC)))
4516     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4517   else
4518     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4519   
4520   if (ShouldSwap) {
4521     std::swap(LHS, RHS);
4522     std::swap(LHSCst, RHSCst);
4523     std::swap(LHSCC, RHSCC);
4524   }
4525   
4526   // At this point, we know we have have two icmp instructions
4527   // comparing a value against two constants and or'ing the result
4528   // together.  Because of the above check, we know that we only have
4529   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4530   // FoldICmpLogical check above), that the two constants are not
4531   // equal.
4532   assert(LHSCst != RHSCst && "Compares not folded above?");
4533
4534   switch (LHSCC) {
4535   default: llvm_unreachable("Unknown integer condition code!");
4536   case ICmpInst::ICMP_EQ:
4537     switch (RHSCC) {
4538     default: llvm_unreachable("Unknown integer condition code!");
4539     case ICmpInst::ICMP_EQ:
4540       if (LHSCst == SubOne(RHSCst, Context)) {
4541         // (X == 13 | X == 14) -> X-13 <u 2
4542         Constant *AddCST = Context->getConstantExprNeg(LHSCst);
4543         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4544                                                      Val->getName()+".off");
4545         InsertNewInstBefore(Add, I);
4546         AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
4547         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
4548       }
4549       break;                         // (X == 13 | X == 15) -> no change
4550     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4551     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4552       break;
4553     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4554     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4555     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4556       return ReplaceInstUsesWith(I, RHS);
4557     }
4558     break;
4559   case ICmpInst::ICMP_NE:
4560     switch (RHSCC) {
4561     default: llvm_unreachable("Unknown integer condition code!");
4562     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4563     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4564     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4565       return ReplaceInstUsesWith(I, LHS);
4566     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4567     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4568     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4569       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4570     }
4571     break;
4572   case ICmpInst::ICMP_ULT:
4573     switch (RHSCC) {
4574     default: llvm_unreachable("Unknown integer condition code!");
4575     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4576       break;
4577     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4578       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4579       // this can cause overflow.
4580       if (RHSCst->isMaxValue(false))
4581         return ReplaceInstUsesWith(I, LHS);
4582       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4583                              false, false, I);
4584     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4585       break;
4586     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4587     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4588       return ReplaceInstUsesWith(I, RHS);
4589     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4590       break;
4591     }
4592     break;
4593   case ICmpInst::ICMP_SLT:
4594     switch (RHSCC) {
4595     default: llvm_unreachable("Unknown integer condition code!");
4596     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4597       break;
4598     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4599       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4600       // this can cause overflow.
4601       if (RHSCst->isMaxValue(true))
4602         return ReplaceInstUsesWith(I, LHS);
4603       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4604                              true, false, I);
4605     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4606       break;
4607     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4608     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4609       return ReplaceInstUsesWith(I, RHS);
4610     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4611       break;
4612     }
4613     break;
4614   case ICmpInst::ICMP_UGT:
4615     switch (RHSCC) {
4616     default: llvm_unreachable("Unknown integer condition code!");
4617     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4618     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4619       return ReplaceInstUsesWith(I, LHS);
4620     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4621       break;
4622     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4623     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4624       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4625     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4626       break;
4627     }
4628     break;
4629   case ICmpInst::ICMP_SGT:
4630     switch (RHSCC) {
4631     default: llvm_unreachable("Unknown integer condition code!");
4632     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4633     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4634       return ReplaceInstUsesWith(I, LHS);
4635     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4636       break;
4637     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4638     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4639       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4640     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4641       break;
4642     }
4643     break;
4644   }
4645   return 0;
4646 }
4647
4648 /// FoldOrWithConstants - This helper function folds:
4649 ///
4650 ///     ((A | B) & C1) | (B & C2)
4651 ///
4652 /// into:
4653 /// 
4654 ///     (A & C1) | B
4655 ///
4656 /// when the XOR of the two constants is "all ones" (-1).
4657 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4658                                                Value *A, Value *B, Value *C) {
4659   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4660   if (!CI1) return 0;
4661
4662   Value *V1 = 0;
4663   ConstantInt *CI2 = 0;
4664   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
4665
4666   APInt Xor = CI1->getValue() ^ CI2->getValue();
4667   if (!Xor.isAllOnesValue()) return 0;
4668
4669   if (V1 == A || V1 == B) {
4670     Instruction *NewOp =
4671       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4672     return BinaryOperator::CreateOr(NewOp, V1);
4673   }
4674
4675   return 0;
4676 }
4677
4678 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4679   bool Changed = SimplifyCommutative(I);
4680   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4681
4682   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4683     return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4684
4685   // or X, X = X
4686   if (Op0 == Op1)
4687     return ReplaceInstUsesWith(I, Op0);
4688
4689   // See if we can simplify any instructions used by the instruction whose sole 
4690   // purpose is to compute bits we don't care about.
4691   if (SimplifyDemandedInstructionBits(I))
4692     return &I;
4693   if (isa<VectorType>(I.getType())) {
4694     if (isa<ConstantAggregateZero>(Op1)) {
4695       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4696     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4697       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4698         return ReplaceInstUsesWith(I, I.getOperand(1));
4699     }
4700   }
4701
4702   // or X, -1 == -1
4703   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4704     ConstantInt *C1 = 0; Value *X = 0;
4705     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4706     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) && 
4707         isOnlyUse(Op0)) {
4708       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4709       InsertNewInstBefore(Or, I);
4710       Or->takeName(Op0);
4711       return BinaryOperator::CreateAnd(Or, 
4712                Context->getConstantInt(RHS->getValue() | C1->getValue()));
4713     }
4714
4715     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4716     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) && 
4717         isOnlyUse(Op0)) {
4718       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4719       InsertNewInstBefore(Or, I);
4720       Or->takeName(Op0);
4721       return BinaryOperator::CreateXor(Or,
4722                  Context->getConstantInt(C1->getValue() & ~RHS->getValue()));
4723     }
4724
4725     // Try to fold constant and into select arguments.
4726     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4727       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4728         return R;
4729     if (isa<PHINode>(Op0))
4730       if (Instruction *NV = FoldOpIntoPhi(I))
4731         return NV;
4732   }
4733
4734   Value *A = 0, *B = 0;
4735   ConstantInt *C1 = 0, *C2 = 0;
4736
4737   if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
4738     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4739       return ReplaceInstUsesWith(I, Op1);
4740   if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
4741     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4742       return ReplaceInstUsesWith(I, Op0);
4743
4744   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4745   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4746   if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4747       match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4748       (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4749        match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
4750     if (Instruction *BSwap = MatchBSwap(I))
4751       return BSwap;
4752   }
4753   
4754   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4755   if (Op0->hasOneUse() &&
4756       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4757       MaskedValueIsZero(Op1, C1->getValue())) {
4758     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4759     InsertNewInstBefore(NOr, I);
4760     NOr->takeName(Op0);
4761     return BinaryOperator::CreateXor(NOr, C1);
4762   }
4763
4764   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4765   if (Op1->hasOneUse() &&
4766       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4767       MaskedValueIsZero(Op0, C1->getValue())) {
4768     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4769     InsertNewInstBefore(NOr, I);
4770     NOr->takeName(Op0);
4771     return BinaryOperator::CreateXor(NOr, C1);
4772   }
4773
4774   // (A & C)|(B & D)
4775   Value *C = 0, *D = 0;
4776   if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4777       match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
4778     Value *V1 = 0, *V2 = 0, *V3 = 0;
4779     C1 = dyn_cast<ConstantInt>(C);
4780     C2 = dyn_cast<ConstantInt>(D);
4781     if (C1 && C2) {  // (A & C1)|(B & C2)
4782       // If we have: ((V + N) & C1) | (V & C2)
4783       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4784       // replace with V+N.
4785       if (C1->getValue() == ~C2->getValue()) {
4786         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4787             match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4788           // Add commutes, try both ways.
4789           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4790             return ReplaceInstUsesWith(I, A);
4791           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4792             return ReplaceInstUsesWith(I, A);
4793         }
4794         // Or commutes, try both ways.
4795         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4796             match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4797           // Add commutes, try both ways.
4798           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4799             return ReplaceInstUsesWith(I, B);
4800           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4801             return ReplaceInstUsesWith(I, B);
4802         }
4803       }
4804       V1 = 0; V2 = 0; V3 = 0;
4805     }
4806     
4807     // Check to see if we have any common things being and'ed.  If so, find the
4808     // terms for V1 & (V2|V3).
4809     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4810       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4811         V1 = A, V2 = C, V3 = D;
4812       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4813         V1 = A, V2 = B, V3 = C;
4814       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4815         V1 = C, V2 = A, V3 = D;
4816       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4817         V1 = C, V2 = A, V3 = B;
4818       
4819       if (V1) {
4820         Value *Or =
4821           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4822         return BinaryOperator::CreateAnd(V1, Or);
4823       }
4824     }
4825
4826     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4827     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4828       return Match;
4829     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4830       return Match;
4831     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4832       return Match;
4833     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4834       return Match;
4835
4836     // ((A&~B)|(~A&B)) -> A^B
4837     if ((match(C, m_Not(m_Specific(D)), *Context) &&
4838          match(B, m_Not(m_Specific(A)), *Context)))
4839       return BinaryOperator::CreateXor(A, D);
4840     // ((~B&A)|(~A&B)) -> A^B
4841     if ((match(A, m_Not(m_Specific(D)), *Context) &&
4842          match(B, m_Not(m_Specific(C)), *Context)))
4843       return BinaryOperator::CreateXor(C, D);
4844     // ((A&~B)|(B&~A)) -> A^B
4845     if ((match(C, m_Not(m_Specific(B)), *Context) &&
4846          match(D, m_Not(m_Specific(A)), *Context)))
4847       return BinaryOperator::CreateXor(A, B);
4848     // ((~B&A)|(B&~A)) -> A^B
4849     if ((match(A, m_Not(m_Specific(B)), *Context) &&
4850          match(D, m_Not(m_Specific(C)), *Context)))
4851       return BinaryOperator::CreateXor(C, B);
4852   }
4853   
4854   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4855   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4856     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4857       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4858           SI0->getOperand(1) == SI1->getOperand(1) &&
4859           (SI0->hasOneUse() || SI1->hasOneUse())) {
4860         Instruction *NewOp =
4861         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4862                                                      SI1->getOperand(0),
4863                                                      SI0->getName()), I);
4864         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4865                                       SI1->getOperand(1));
4866       }
4867   }
4868
4869   // ((A|B)&1)|(B&-2) -> (A&1) | B
4870   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4871       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4872     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4873     if (Ret) return Ret;
4874   }
4875   // (B&-2)|((A|B)&1) -> (A&1) | B
4876   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4877       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4878     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4879     if (Ret) return Ret;
4880   }
4881
4882   if (match(Op0, m_Not(m_Value(A)), *Context)) {   // ~A | Op1
4883     if (A == Op1)   // ~A | A == -1
4884       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4885   } else {
4886     A = 0;
4887   }
4888   // Note, A is still live here!
4889   if (match(Op1, m_Not(m_Value(B)), *Context)) {   // Op0 | ~B
4890     if (Op0 == B)
4891       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4892
4893     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4894     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4895       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4896                                               I.getName()+".demorgan"), I);
4897       return BinaryOperator::CreateNot(*Context, And);
4898     }
4899   }
4900
4901   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4902   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4903     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4904       return R;
4905
4906     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4907       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4908         return Res;
4909   }
4910     
4911   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4912   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4913     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4914       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4915         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4916             !isa<ICmpInst>(Op1C->getOperand(0))) {
4917           const Type *SrcTy = Op0C->getOperand(0)->getType();
4918           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4919               // Only do this if the casts both really cause code to be
4920               // generated.
4921               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4922                                 I.getType(), TD) &&
4923               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4924                                 I.getType(), TD)) {
4925             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4926                                                           Op1C->getOperand(0),
4927                                                           I.getName());
4928             InsertNewInstBefore(NewOp, I);
4929             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4930           }
4931         }
4932       }
4933   }
4934   
4935     
4936   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4937   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4938     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4939       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4940           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4941           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4942         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4943           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4944             // If either of the constants are nans, then the whole thing returns
4945             // true.
4946             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4947               return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4948             
4949             // Otherwise, no need to compare the two constants, compare the
4950             // rest.
4951             return new FCmpInst(*Context, FCmpInst::FCMP_UNO, 
4952                                 LHS->getOperand(0), RHS->getOperand(0));
4953           }
4954       } else {
4955         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4956         FCmpInst::Predicate Op0CC, Op1CC;
4957         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4958                   m_Value(Op0RHS)), *Context) &&
4959             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4960                   m_Value(Op1RHS)), *Context)) {
4961           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4962             // Swap RHS operands to match LHS.
4963             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4964             std::swap(Op1LHS, Op1RHS);
4965           }
4966           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4967             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4968             if (Op0CC == Op1CC)
4969               return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4970                                   Op0LHS, Op0RHS);
4971             else if (Op0CC == FCmpInst::FCMP_TRUE ||
4972                      Op1CC == FCmpInst::FCMP_TRUE)
4973               return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4974             else if (Op0CC == FCmpInst::FCMP_FALSE)
4975               return ReplaceInstUsesWith(I, Op1);
4976             else if (Op1CC == FCmpInst::FCMP_FALSE)
4977               return ReplaceInstUsesWith(I, Op0);
4978             bool Op0Ordered;
4979             bool Op1Ordered;
4980             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4981             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4982             if (Op0Ordered == Op1Ordered) {
4983               // If both are ordered or unordered, return a new fcmp with
4984               // or'ed predicates.
4985               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4986                                        Op0LHS, Op0RHS, Context);
4987               if (Instruction *I = dyn_cast<Instruction>(RV))
4988                 return I;
4989               // Otherwise, it's a constant boolean value...
4990               return ReplaceInstUsesWith(I, RV);
4991             }
4992           }
4993         }
4994       }
4995     }
4996   }
4997
4998   return Changed ? &I : 0;
4999 }
5000
5001 namespace {
5002
5003 // XorSelf - Implements: X ^ X --> 0
5004 struct XorSelf {
5005   Value *RHS;
5006   XorSelf(Value *rhs) : RHS(rhs) {}
5007   bool shouldApply(Value *LHS) const { return LHS == RHS; }
5008   Instruction *apply(BinaryOperator &Xor) const {
5009     return &Xor;
5010   }
5011 };
5012
5013 }
5014
5015 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5016   bool Changed = SimplifyCommutative(I);
5017   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5018
5019   if (isa<UndefValue>(Op1)) {
5020     if (isa<UndefValue>(Op0))
5021       // Handle undef ^ undef -> 0 special case. This is a common
5022       // idiom (misuse).
5023       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5024     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5025   }
5026
5027   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5028   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
5029     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5030     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5031   }
5032   
5033   // See if we can simplify any instructions used by the instruction whose sole 
5034   // purpose is to compute bits we don't care about.
5035   if (SimplifyDemandedInstructionBits(I))
5036     return &I;
5037   if (isa<VectorType>(I.getType()))
5038     if (isa<ConstantAggregateZero>(Op1))
5039       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5040
5041   // Is this a ~ operation?
5042   if (Value *NotOp = dyn_castNotVal(&I, Context)) {
5043     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5044     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5045     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5046       if (Op0I->getOpcode() == Instruction::And || 
5047           Op0I->getOpcode() == Instruction::Or) {
5048         if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5049         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
5050           Instruction *NotY =
5051             BinaryOperator::CreateNot(*Context, Op0I->getOperand(1),
5052                                       Op0I->getOperand(1)->getName()+".not");
5053           InsertNewInstBefore(NotY, I);
5054           if (Op0I->getOpcode() == Instruction::And)
5055             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5056           else
5057             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5058         }
5059       }
5060     }
5061   }
5062   
5063   
5064   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5065     if (RHS == Context->getConstantIntTrue() && Op0->hasOneUse()) {
5066       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5067       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5068         return new ICmpInst(*Context, ICI->getInversePredicate(),
5069                             ICI->getOperand(0), ICI->getOperand(1));
5070
5071       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5072         return new FCmpInst(*Context, FCI->getInversePredicate(),
5073                             FCI->getOperand(0), FCI->getOperand(1));
5074     }
5075
5076     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5077     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5078       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5079         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5080           Instruction::CastOps Opcode = Op0C->getOpcode();
5081           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5082             if (RHS == Context->getConstantExprCast(Opcode, 
5083                                              Context->getConstantIntTrue(),
5084                                              Op0C->getDestTy())) {
5085               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5086                                      *Context,
5087                                      CI->getOpcode(), CI->getInversePredicate(),
5088                                      CI->getOperand(0), CI->getOperand(1)), I);
5089               NewCI->takeName(CI);
5090               return CastInst::Create(Opcode, NewCI, Op0C->getType());
5091             }
5092           }
5093         }
5094       }
5095     }
5096
5097     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5098       // ~(c-X) == X-c-1 == X+(-c-1)
5099       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5100         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5101           Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5102           Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
5103                                       Context->getConstantInt(I.getType(), 1));
5104           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5105         }
5106           
5107       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5108         if (Op0I->getOpcode() == Instruction::Add) {
5109           // ~(X-c) --> (-c-1)-X
5110           if (RHS->isAllOnesValue()) {
5111             Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
5112             return BinaryOperator::CreateSub(
5113                            Context->getConstantExprSub(NegOp0CI,
5114                                       Context->getConstantInt(I.getType(), 1)),
5115                                       Op0I->getOperand(0));
5116           } else if (RHS->getValue().isSignBit()) {
5117             // (X + C) ^ signbit -> (X + C + signbit)
5118             Constant *C =
5119                    Context->getConstantInt(RHS->getValue() + Op0CI->getValue());
5120             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5121
5122           }
5123         } else if (Op0I->getOpcode() == Instruction::Or) {
5124           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5125           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5126             Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
5127             // Anything in both C1 and C2 is known to be zero, remove it from
5128             // NewRHS.
5129             Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5130             NewRHS = Context->getConstantExprAnd(NewRHS, 
5131                                        Context->getConstantExprNot(CommonBits));
5132             AddToWorkList(Op0I);
5133             I.setOperand(0, Op0I->getOperand(0));
5134             I.setOperand(1, NewRHS);
5135             return &I;
5136           }
5137         }
5138       }
5139     }
5140
5141     // Try to fold constant and into select arguments.
5142     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5143       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5144         return R;
5145     if (isa<PHINode>(Op0))
5146       if (Instruction *NV = FoldOpIntoPhi(I))
5147         return NV;
5148   }
5149
5150   if (Value *X = dyn_castNotVal(Op0, Context))   // ~A ^ A == -1
5151     if (X == Op1)
5152       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5153
5154   if (Value *X = dyn_castNotVal(Op1, Context))   // A ^ ~A == -1
5155     if (X == Op0)
5156       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5157
5158   
5159   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5160   if (Op1I) {
5161     Value *A, *B;
5162     if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
5163       if (A == Op0) {              // B^(B|A) == (A|B)^B
5164         Op1I->swapOperands();
5165         I.swapOperands();
5166         std::swap(Op0, Op1);
5167       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5168         I.swapOperands();     // Simplified below.
5169         std::swap(Op0, Op1);
5170       }
5171     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
5172       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5173     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
5174       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5175     } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) && 
5176                Op1I->hasOneUse()){
5177       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5178         Op1I->swapOperands();
5179         std::swap(A, B);
5180       }
5181       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5182         I.swapOperands();     // Simplified below.
5183         std::swap(Op0, Op1);
5184       }
5185     }
5186   }
5187   
5188   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5189   if (Op0I) {
5190     Value *A, *B;
5191     if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5192         Op0I->hasOneUse()) {
5193       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5194         std::swap(A, B);
5195       if (B == Op1) {                                // (A|B)^B == A & ~B
5196         Instruction *NotB =
5197           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, 
5198                                                         Op1, "tmp"), I);
5199         return BinaryOperator::CreateAnd(A, NotB);
5200       }
5201     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
5202       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5203     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
5204       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5205     } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) && 
5206                Op0I->hasOneUse()){
5207       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5208         std::swap(A, B);
5209       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5210           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5211         Instruction *N =
5212           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, A, "tmp"), I);
5213         return BinaryOperator::CreateAnd(N, Op1);
5214       }
5215     }
5216   }
5217   
5218   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5219   if (Op0I && Op1I && Op0I->isShift() && 
5220       Op0I->getOpcode() == Op1I->getOpcode() && 
5221       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5222       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5223     Instruction *NewOp =
5224       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5225                                                     Op1I->getOperand(0),
5226                                                     Op0I->getName()), I);
5227     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5228                                   Op1I->getOperand(1));
5229   }
5230     
5231   if (Op0I && Op1I) {
5232     Value *A, *B, *C, *D;
5233     // (A & B)^(A | B) -> A ^ B
5234     if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5235         match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
5236       if ((A == C && B == D) || (A == D && B == C)) 
5237         return BinaryOperator::CreateXor(A, B);
5238     }
5239     // (A | B)^(A & B) -> A ^ B
5240     if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5241         match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5242       if ((A == C && B == D) || (A == D && B == C)) 
5243         return BinaryOperator::CreateXor(A, B);
5244     }
5245     
5246     // (A & B)^(C & D)
5247     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5248         match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5249         match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5250       // (X & Y)^(X & Y) -> (Y^Z) & X
5251       Value *X = 0, *Y = 0, *Z = 0;
5252       if (A == C)
5253         X = A, Y = B, Z = D;
5254       else if (A == D)
5255         X = A, Y = B, Z = C;
5256       else if (B == C)
5257         X = B, Y = A, Z = D;
5258       else if (B == D)
5259         X = B, Y = A, Z = C;
5260       
5261       if (X) {
5262         Instruction *NewOp =
5263         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5264         return BinaryOperator::CreateAnd(NewOp, X);
5265       }
5266     }
5267   }
5268     
5269   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5270   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5271     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
5272       return R;
5273
5274   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5275   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5276     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5277       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5278         const Type *SrcTy = Op0C->getOperand(0)->getType();
5279         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5280             // Only do this if the casts both really cause code to be generated.
5281             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5282                               I.getType(), TD) &&
5283             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5284                               I.getType(), TD)) {
5285           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5286                                                          Op1C->getOperand(0),
5287                                                          I.getName());
5288           InsertNewInstBefore(NewOp, I);
5289           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5290         }
5291       }
5292   }
5293
5294   return Changed ? &I : 0;
5295 }
5296
5297 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5298                                    LLVMContext *Context) {
5299   return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
5300 }
5301
5302 static bool HasAddOverflow(ConstantInt *Result,
5303                            ConstantInt *In1, ConstantInt *In2,
5304                            bool IsSigned) {
5305   if (IsSigned)
5306     if (In2->getValue().isNegative())
5307       return Result->getValue().sgt(In1->getValue());
5308     else
5309       return Result->getValue().slt(In1->getValue());
5310   else
5311     return Result->getValue().ult(In1->getValue());
5312 }
5313
5314 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5315 /// overflowed for this type.
5316 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5317                             Constant *In2, LLVMContext *Context,
5318                             bool IsSigned = false) {
5319   Result = Context->getConstantExprAdd(In1, In2);
5320
5321   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5322     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5323       Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5324       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5325                          ExtractElement(In1, Idx, Context),
5326                          ExtractElement(In2, Idx, Context),
5327                          IsSigned))
5328         return true;
5329     }
5330     return false;
5331   }
5332
5333   return HasAddOverflow(cast<ConstantInt>(Result),
5334                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5335                         IsSigned);
5336 }
5337
5338 static bool HasSubOverflow(ConstantInt *Result,
5339                            ConstantInt *In1, ConstantInt *In2,
5340                            bool IsSigned) {
5341   if (IsSigned)
5342     if (In2->getValue().isNegative())
5343       return Result->getValue().slt(In1->getValue());
5344     else
5345       return Result->getValue().sgt(In1->getValue());
5346   else
5347     return Result->getValue().ugt(In1->getValue());
5348 }
5349
5350 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5351 /// overflowed for this type.
5352 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5353                             Constant *In2, LLVMContext *Context,
5354                             bool IsSigned = false) {
5355   Result = Context->getConstantExprSub(In1, In2);
5356
5357   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5358     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5359       Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5360       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5361                          ExtractElement(In1, Idx, Context),
5362                          ExtractElement(In2, Idx, Context),
5363                          IsSigned))
5364         return true;
5365     }
5366     return false;
5367   }
5368
5369   return HasSubOverflow(cast<ConstantInt>(Result),
5370                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5371                         IsSigned);
5372 }
5373
5374 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5375 /// code necessary to compute the offset from the base pointer (without adding
5376 /// in the base pointer).  Return the result as a signed integer of intptr size.
5377 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5378   TargetData &TD = IC.getTargetData();
5379   gep_type_iterator GTI = gep_type_begin(GEP);
5380   const Type *IntPtrTy = TD.getIntPtrType();
5381   LLVMContext *Context = IC.getContext();
5382   Value *Result = Context->getNullValue(IntPtrTy);
5383
5384   // Build a mask for high order bits.
5385   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5386   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5387
5388   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5389        ++i, ++GTI) {
5390     Value *Op = *i;
5391     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5392     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5393       if (OpC->isZero()) continue;
5394       
5395       // Handle a struct index, which adds its field offset to the pointer.
5396       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5397         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5398         
5399         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5400           Result = 
5401              Context->getConstantInt(RC->getValue() + APInt(IntPtrWidth, Size));
5402         else
5403           Result = IC.InsertNewInstBefore(
5404                    BinaryOperator::CreateAdd(Result,
5405                                         Context->getConstantInt(IntPtrTy, Size),
5406                                              GEP->getName()+".offs"), I);
5407         continue;
5408       }
5409       
5410       Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5411       Constant *OC =
5412               Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5413       Scale = Context->getConstantExprMul(OC, Scale);
5414       if (Constant *RC = dyn_cast<Constant>(Result))
5415         Result = Context->getConstantExprAdd(RC, Scale);
5416       else {
5417         // Emit an add instruction.
5418         Result = IC.InsertNewInstBefore(
5419            BinaryOperator::CreateAdd(Result, Scale,
5420                                      GEP->getName()+".offs"), I);
5421       }
5422       continue;
5423     }
5424     // Convert to correct type.
5425     if (Op->getType() != IntPtrTy) {
5426       if (Constant *OpC = dyn_cast<Constant>(Op))
5427         Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
5428       else
5429         Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5430                                                                 true,
5431                                                       Op->getName()+".c"), I);
5432     }
5433     if (Size != 1) {
5434       Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5435       if (Constant *OpC = dyn_cast<Constant>(Op))
5436         Op = Context->getConstantExprMul(OpC, Scale);
5437       else    // We'll let instcombine(mul) convert this to a shl if possible.
5438         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5439                                                   GEP->getName()+".idx"), I);
5440     }
5441
5442     // Emit an add instruction.
5443     if (isa<Constant>(Op) && isa<Constant>(Result))
5444       Result = Context->getConstantExprAdd(cast<Constant>(Op),
5445                                     cast<Constant>(Result));
5446     else
5447       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5448                                                   GEP->getName()+".offs"), I);
5449   }
5450   return Result;
5451 }
5452
5453
5454 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5455 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
5456 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
5457 /// be complex, and scales are involved.  The above expression would also be
5458 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5459 /// This later form is less amenable to optimization though, and we are allowed
5460 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5461 ///
5462 /// If we can't emit an optimized form for this expression, this returns null.
5463 /// 
5464 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5465                                           InstCombiner &IC) {
5466   TargetData &TD = IC.getTargetData();
5467   gep_type_iterator GTI = gep_type_begin(GEP);
5468
5469   // Check to see if this gep only has a single variable index.  If so, and if
5470   // any constant indices are a multiple of its scale, then we can compute this
5471   // in terms of the scale of the variable index.  For example, if the GEP
5472   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5473   // because the expression will cross zero at the same point.
5474   unsigned i, e = GEP->getNumOperands();
5475   int64_t Offset = 0;
5476   for (i = 1; i != e; ++i, ++GTI) {
5477     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5478       // Compute the aggregate offset of constant indices.
5479       if (CI->isZero()) continue;
5480
5481       // Handle a struct index, which adds its field offset to the pointer.
5482       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5483         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5484       } else {
5485         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5486         Offset += Size*CI->getSExtValue();
5487       }
5488     } else {
5489       // Found our variable index.
5490       break;
5491     }
5492   }
5493   
5494   // If there are no variable indices, we must have a constant offset, just
5495   // evaluate it the general way.
5496   if (i == e) return 0;
5497   
5498   Value *VariableIdx = GEP->getOperand(i);
5499   // Determine the scale factor of the variable element.  For example, this is
5500   // 4 if the variable index is into an array of i32.
5501   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5502   
5503   // Verify that there are no other variable indices.  If so, emit the hard way.
5504   for (++i, ++GTI; i != e; ++i, ++GTI) {
5505     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5506     if (!CI) return 0;
5507    
5508     // Compute the aggregate offset of constant indices.
5509     if (CI->isZero()) continue;
5510     
5511     // Handle a struct index, which adds its field offset to the pointer.
5512     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5513       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5514     } else {
5515       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5516       Offset += Size*CI->getSExtValue();
5517     }
5518   }
5519   
5520   // Okay, we know we have a single variable index, which must be a
5521   // pointer/array/vector index.  If there is no offset, life is simple, return
5522   // the index.
5523   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5524   if (Offset == 0) {
5525     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5526     // we don't need to bother extending: the extension won't affect where the
5527     // computation crosses zero.
5528     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5529       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5530                                   VariableIdx->getNameStart(), &I);
5531     return VariableIdx;
5532   }
5533   
5534   // Otherwise, there is an index.  The computation we will do will be modulo
5535   // the pointer size, so get it.
5536   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5537   
5538   Offset &= PtrSizeMask;
5539   VariableScale &= PtrSizeMask;
5540
5541   // To do this transformation, any constant index must be a multiple of the
5542   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5543   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5544   // multiple of the variable scale.
5545   int64_t NewOffs = Offset / (int64_t)VariableScale;
5546   if (Offset != NewOffs*(int64_t)VariableScale)
5547     return 0;
5548
5549   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5550   const Type *IntPtrTy = TD.getIntPtrType();
5551   if (VariableIdx->getType() != IntPtrTy)
5552     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5553                                               true /*SExt*/, 
5554                                               VariableIdx->getNameStart(), &I);
5555   Constant *OffsetVal = IC.getContext()->getConstantInt(IntPtrTy, NewOffs);
5556   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5557 }
5558
5559
5560 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5561 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5562 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5563                                        ICmpInst::Predicate Cond,
5564                                        Instruction &I) {
5565   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5566
5567   // Look through bitcasts.
5568   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5569     RHS = BCI->getOperand(0);
5570
5571   Value *PtrBase = GEPLHS->getOperand(0);
5572   if (PtrBase == RHS) {
5573     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5574     // This transformation (ignoring the base and scales) is valid because we
5575     // know pointers can't overflow.  See if we can output an optimized form.
5576     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5577     
5578     // If not, synthesize the offset the hard way.
5579     if (Offset == 0)
5580       Offset = EmitGEPOffset(GEPLHS, I, *this);
5581     return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
5582                         Context->getNullValue(Offset->getType()));
5583   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5584     // If the base pointers are different, but the indices are the same, just
5585     // compare the base pointer.
5586     if (PtrBase != GEPRHS->getOperand(0)) {
5587       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5588       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5589                         GEPRHS->getOperand(0)->getType();
5590       if (IndicesTheSame)
5591         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5592           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5593             IndicesTheSame = false;
5594             break;
5595           }
5596
5597       // If all indices are the same, just compare the base pointers.
5598       if (IndicesTheSame)
5599         return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), 
5600                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5601
5602       // Otherwise, the base pointers are different and the indices are
5603       // different, bail out.
5604       return 0;
5605     }
5606
5607     // If one of the GEPs has all zero indices, recurse.
5608     bool AllZeros = true;
5609     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5610       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5611           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5612         AllZeros = false;
5613         break;
5614       }
5615     if (AllZeros)
5616       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5617                           ICmpInst::getSwappedPredicate(Cond), I);
5618
5619     // If the other GEP has all zero indices, recurse.
5620     AllZeros = true;
5621     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5622       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5623           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5624         AllZeros = false;
5625         break;
5626       }
5627     if (AllZeros)
5628       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5629
5630     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5631       // If the GEPs only differ by one index, compare it.
5632       unsigned NumDifferences = 0;  // Keep track of # differences.
5633       unsigned DiffOperand = 0;     // The operand that differs.
5634       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5635         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5636           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5637                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5638             // Irreconcilable differences.
5639             NumDifferences = 2;
5640             break;
5641           } else {
5642             if (NumDifferences++) break;
5643             DiffOperand = i;
5644           }
5645         }
5646
5647       if (NumDifferences == 0)   // SAME GEP?
5648         return ReplaceInstUsesWith(I, // No comparison is needed here.
5649                                    Context->getConstantInt(Type::Int1Ty,
5650                                              ICmpInst::isTrueWhenEqual(Cond)));
5651
5652       else if (NumDifferences == 1) {
5653         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5654         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5655         // Make sure we do a signed comparison here.
5656         return new ICmpInst(*Context,
5657                             ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5658       }
5659     }
5660
5661     // Only lower this if the icmp is the only user of the GEP or if we expect
5662     // the result to fold to a constant!
5663     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5664         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5665       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5666       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5667       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5668       return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
5669     }
5670   }
5671   return 0;
5672 }
5673
5674 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5675 ///
5676 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5677                                                 Instruction *LHSI,
5678                                                 Constant *RHSC) {
5679   if (!isa<ConstantFP>(RHSC)) return 0;
5680   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5681   
5682   // Get the width of the mantissa.  We don't want to hack on conversions that
5683   // might lose information from the integer, e.g. "i64 -> float"
5684   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5685   if (MantissaWidth == -1) return 0;  // Unknown.
5686   
5687   // Check to see that the input is converted from an integer type that is small
5688   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5689   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5690   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5691   
5692   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5693   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5694   if (LHSUnsigned)
5695     ++InputSize;
5696   
5697   // If the conversion would lose info, don't hack on this.
5698   if ((int)InputSize > MantissaWidth)
5699     return 0;
5700   
5701   // Otherwise, we can potentially simplify the comparison.  We know that it
5702   // will always come through as an integer value and we know the constant is
5703   // not a NAN (it would have been previously simplified).
5704   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5705   
5706   ICmpInst::Predicate Pred;
5707   switch (I.getPredicate()) {
5708   default: llvm_unreachable("Unexpected predicate!");
5709   case FCmpInst::FCMP_UEQ:
5710   case FCmpInst::FCMP_OEQ:
5711     Pred = ICmpInst::ICMP_EQ;
5712     break;
5713   case FCmpInst::FCMP_UGT:
5714   case FCmpInst::FCMP_OGT:
5715     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5716     break;
5717   case FCmpInst::FCMP_UGE:
5718   case FCmpInst::FCMP_OGE:
5719     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5720     break;
5721   case FCmpInst::FCMP_ULT:
5722   case FCmpInst::FCMP_OLT:
5723     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5724     break;
5725   case FCmpInst::FCMP_ULE:
5726   case FCmpInst::FCMP_OLE:
5727     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5728     break;
5729   case FCmpInst::FCMP_UNE:
5730   case FCmpInst::FCMP_ONE:
5731     Pred = ICmpInst::ICMP_NE;
5732     break;
5733   case FCmpInst::FCMP_ORD:
5734     return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5735   case FCmpInst::FCMP_UNO:
5736     return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5737   }
5738   
5739   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5740   
5741   // Now we know that the APFloat is a normal number, zero or inf.
5742   
5743   // See if the FP constant is too large for the integer.  For example,
5744   // comparing an i8 to 300.0.
5745   unsigned IntWidth = IntTy->getScalarSizeInBits();
5746   
5747   if (!LHSUnsigned) {
5748     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5749     // and large values.
5750     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5751     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5752                           APFloat::rmNearestTiesToEven);
5753     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5754       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5755           Pred == ICmpInst::ICMP_SLE)
5756         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5757       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5758     }
5759   } else {
5760     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5761     // +INF and large values.
5762     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5763     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5764                           APFloat::rmNearestTiesToEven);
5765     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5766       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5767           Pred == ICmpInst::ICMP_ULE)
5768         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5769       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5770     }
5771   }
5772   
5773   if (!LHSUnsigned) {
5774     // See if the RHS value is < SignedMin.
5775     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5776     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5777                           APFloat::rmNearestTiesToEven);
5778     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5779       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5780           Pred == ICmpInst::ICMP_SGE)
5781         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5782       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5783     }
5784   }
5785
5786   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5787   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5788   // casting the FP value to the integer value and back, checking for equality.
5789   // Don't do this for zero, because -0.0 is not fractional.
5790   Constant *RHSInt = LHSUnsigned
5791     ? Context->getConstantExprFPToUI(RHSC, IntTy)
5792     : Context->getConstantExprFPToSI(RHSC, IntTy);
5793   if (!RHS.isZero()) {
5794     bool Equal = LHSUnsigned
5795       ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5796       : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
5797     if (!Equal) {
5798       // If we had a comparison against a fractional value, we have to adjust
5799       // the compare predicate and sometimes the value.  RHSC is rounded towards
5800       // zero at this point.
5801       switch (Pred) {
5802       default: llvm_unreachable("Unexpected integer comparison!");
5803       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5804         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5805       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5806         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5807       case ICmpInst::ICMP_ULE:
5808         // (float)int <= 4.4   --> int <= 4
5809         // (float)int <= -4.4  --> false
5810         if (RHS.isNegative())
5811           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5812         break;
5813       case ICmpInst::ICMP_SLE:
5814         // (float)int <= 4.4   --> int <= 4
5815         // (float)int <= -4.4  --> int < -4
5816         if (RHS.isNegative())
5817           Pred = ICmpInst::ICMP_SLT;
5818         break;
5819       case ICmpInst::ICMP_ULT:
5820         // (float)int < -4.4   --> false
5821         // (float)int < 4.4    --> int <= 4
5822         if (RHS.isNegative())
5823           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5824         Pred = ICmpInst::ICMP_ULE;
5825         break;
5826       case ICmpInst::ICMP_SLT:
5827         // (float)int < -4.4   --> int < -4
5828         // (float)int < 4.4    --> int <= 4
5829         if (!RHS.isNegative())
5830           Pred = ICmpInst::ICMP_SLE;
5831         break;
5832       case ICmpInst::ICMP_UGT:
5833         // (float)int > 4.4    --> int > 4
5834         // (float)int > -4.4   --> true
5835         if (RHS.isNegative())
5836           return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5837         break;
5838       case ICmpInst::ICMP_SGT:
5839         // (float)int > 4.4    --> int > 4
5840         // (float)int > -4.4   --> int >= -4
5841         if (RHS.isNegative())
5842           Pred = ICmpInst::ICMP_SGE;
5843         break;
5844       case ICmpInst::ICMP_UGE:
5845         // (float)int >= -4.4   --> true
5846         // (float)int >= 4.4    --> int > 4
5847         if (!RHS.isNegative())
5848           return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5849         Pred = ICmpInst::ICMP_UGT;
5850         break;
5851       case ICmpInst::ICMP_SGE:
5852         // (float)int >= -4.4   --> int >= -4
5853         // (float)int >= 4.4    --> int > 4
5854         if (!RHS.isNegative())
5855           Pred = ICmpInst::ICMP_SGT;
5856         break;
5857       }
5858     }
5859   }
5860
5861   // Lower this FP comparison into an appropriate integer version of the
5862   // comparison.
5863   return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
5864 }
5865
5866 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5867   bool Changed = SimplifyCompare(I);
5868   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5869
5870   // Fold trivial predicates.
5871   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5872     return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5873   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5874     return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5875   
5876   // Simplify 'fcmp pred X, X'
5877   if (Op0 == Op1) {
5878     switch (I.getPredicate()) {
5879     default: llvm_unreachable("Unknown predicate!");
5880     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5881     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5882     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5883       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5884     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5885     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5886     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5887       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5888       
5889     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5890     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5891     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5892     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5893       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5894       I.setPredicate(FCmpInst::FCMP_UNO);
5895       I.setOperand(1, Context->getNullValue(Op0->getType()));
5896       return &I;
5897       
5898     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5899     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5900     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5901     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5902       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5903       I.setPredicate(FCmpInst::FCMP_ORD);
5904       I.setOperand(1, Context->getNullValue(Op0->getType()));
5905       return &I;
5906     }
5907   }
5908     
5909   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5910     return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5911
5912   // Handle fcmp with constant RHS
5913   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5914     // If the constant is a nan, see if we can fold the comparison based on it.
5915     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5916       if (CFP->getValueAPF().isNaN()) {
5917         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5918           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5919         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5920                "Comparison must be either ordered or unordered!");
5921         // True if unordered.
5922         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5923       }
5924     }
5925     
5926     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5927       switch (LHSI->getOpcode()) {
5928       case Instruction::PHI:
5929         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5930         // block.  If in the same block, we're encouraging jump threading.  If
5931         // not, we are just pessimizing the code by making an i1 phi.
5932         if (LHSI->getParent() == I.getParent())
5933           if (Instruction *NV = FoldOpIntoPhi(I))
5934             return NV;
5935         break;
5936       case Instruction::SIToFP:
5937       case Instruction::UIToFP:
5938         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5939           return NV;
5940         break;
5941       case Instruction::Select:
5942         // If either operand of the select is a constant, we can fold the
5943         // comparison into the select arms, which will cause one to be
5944         // constant folded and the select turned into a bitwise or.
5945         Value *Op1 = 0, *Op2 = 0;
5946         if (LHSI->hasOneUse()) {
5947           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5948             // Fold the known value into the constant operand.
5949             Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5950             // Insert a new FCmp of the other select operand.
5951             Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5952                                                       LHSI->getOperand(2), RHSC,
5953                                                       I.getName()), I);
5954           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5955             // Fold the known value into the constant operand.
5956             Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5957             // Insert a new FCmp of the other select operand.
5958             Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5959                                                       LHSI->getOperand(1), RHSC,
5960                                                       I.getName()), I);
5961           }
5962         }
5963
5964         if (Op1)
5965           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5966         break;
5967       }
5968   }
5969
5970   return Changed ? &I : 0;
5971 }
5972
5973 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5974   bool Changed = SimplifyCompare(I);
5975   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5976   const Type *Ty = Op0->getType();
5977
5978   // icmp X, X
5979   if (Op0 == Op1)
5980     return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty, 
5981                                                    I.isTrueWhenEqual()));
5982
5983   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5984     return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5985   
5986   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5987   // addresses never equal each other!  We already know that Op0 != Op1.
5988   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5989        isa<ConstantPointerNull>(Op0)) &&
5990       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5991        isa<ConstantPointerNull>(Op1)))
5992     return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty, 
5993                                                    !I.isTrueWhenEqual()));
5994
5995   // icmp's with boolean values can always be turned into bitwise operations
5996   if (Ty == Type::Int1Ty) {
5997     switch (I.getPredicate()) {
5998     default: llvm_unreachable("Invalid icmp instruction!");
5999     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
6000       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
6001       InsertNewInstBefore(Xor, I);
6002       return BinaryOperator::CreateNot(*Context, Xor);
6003     }
6004     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
6005       return BinaryOperator::CreateXor(Op0, Op1);
6006
6007     case ICmpInst::ICMP_UGT:
6008       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
6009       // FALL THROUGH
6010     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
6011       Instruction *Not = BinaryOperator::CreateNot(*Context,
6012                                                    Op0, I.getName()+"tmp");
6013       InsertNewInstBefore(Not, I);
6014       return BinaryOperator::CreateAnd(Not, Op1);
6015     }
6016     case ICmpInst::ICMP_SGT:
6017       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
6018       // FALL THROUGH
6019     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
6020       Instruction *Not = BinaryOperator::CreateNot(*Context, 
6021                                                    Op1, I.getName()+"tmp");
6022       InsertNewInstBefore(Not, I);
6023       return BinaryOperator::CreateAnd(Not, Op0);
6024     }
6025     case ICmpInst::ICMP_UGE:
6026       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6027       // FALL THROUGH
6028     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6029       Instruction *Not = BinaryOperator::CreateNot(*Context,
6030                                                    Op0, I.getName()+"tmp");
6031       InsertNewInstBefore(Not, I);
6032       return BinaryOperator::CreateOr(Not, Op1);
6033     }
6034     case ICmpInst::ICMP_SGE:
6035       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6036       // FALL THROUGH
6037     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6038       Instruction *Not = BinaryOperator::CreateNot(*Context,
6039                                                    Op1, I.getName()+"tmp");
6040       InsertNewInstBefore(Not, I);
6041       return BinaryOperator::CreateOr(Not, Op0);
6042     }
6043     }
6044   }
6045
6046   unsigned BitWidth = 0;
6047   if (TD)
6048     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6049   else if (Ty->isIntOrIntVector())
6050     BitWidth = Ty->getScalarSizeInBits();
6051
6052   bool isSignBit = false;
6053
6054   // See if we are doing a comparison with a constant.
6055   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6056     Value *A = 0, *B = 0;
6057     
6058     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6059     if (I.isEquality() && CI->isNullValue() &&
6060         match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
6061       // (icmp cond A B) if cond is equality
6062       return new ICmpInst(*Context, I.getPredicate(), A, B);
6063     }
6064     
6065     // If we have an icmp le or icmp ge instruction, turn it into the
6066     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6067     // them being folded in the code below.
6068     switch (I.getPredicate()) {
6069     default: break;
6070     case ICmpInst::ICMP_ULE:
6071       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
6072         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6073       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6074                           AddOne(CI, Context));
6075     case ICmpInst::ICMP_SLE:
6076       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
6077         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6078       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6079                           AddOne(CI, Context));
6080     case ICmpInst::ICMP_UGE:
6081       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
6082         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6083       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6084                           SubOne(CI, Context));
6085     case ICmpInst::ICMP_SGE:
6086       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
6087         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6088       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6089                           SubOne(CI, Context));
6090     }
6091     
6092     // If this comparison is a normal comparison, it demands all
6093     // bits, if it is a sign bit comparison, it only demands the sign bit.
6094     bool UnusedBit;
6095     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6096   }
6097
6098   // See if we can fold the comparison based on range information we can get
6099   // by checking whether bits are known to be zero or one in the input.
6100   if (BitWidth != 0) {
6101     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6102     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6103
6104     if (SimplifyDemandedBits(I.getOperandUse(0),
6105                              isSignBit ? APInt::getSignBit(BitWidth)
6106                                        : APInt::getAllOnesValue(BitWidth),
6107                              Op0KnownZero, Op0KnownOne, 0))
6108       return &I;
6109     if (SimplifyDemandedBits(I.getOperandUse(1),
6110                              APInt::getAllOnesValue(BitWidth),
6111                              Op1KnownZero, Op1KnownOne, 0))
6112       return &I;
6113
6114     // Given the known and unknown bits, compute a range that the LHS could be
6115     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6116     // EQ and NE we use unsigned values.
6117     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6118     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6119     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6120       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6121                                              Op0Min, Op0Max);
6122       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6123                                              Op1Min, Op1Max);
6124     } else {
6125       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6126                                                Op0Min, Op0Max);
6127       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6128                                                Op1Min, Op1Max);
6129     }
6130
6131     // If Min and Max are known to be the same, then SimplifyDemandedBits
6132     // figured out that the LHS is a constant.  Just constant fold this now so
6133     // that code below can assume that Min != Max.
6134     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6135       return new ICmpInst(*Context, I.getPredicate(),
6136                           Context->getConstantInt(Op0Min), Op1);
6137     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6138       return new ICmpInst(*Context, I.getPredicate(), Op0, 
6139                           Context->getConstantInt(Op1Min));
6140
6141     // Based on the range information we know about the LHS, see if we can
6142     // simplify this comparison.  For example, (x&4) < 8  is always true.
6143     switch (I.getPredicate()) {
6144     default: llvm_unreachable("Unknown icmp opcode!");
6145     case ICmpInst::ICMP_EQ:
6146       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6147         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6148       break;
6149     case ICmpInst::ICMP_NE:
6150       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6151         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6152       break;
6153     case ICmpInst::ICMP_ULT:
6154       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6155         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6156       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6157         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6158       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6159         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6160       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6161         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6162           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6163                               SubOne(CI, Context));
6164
6165         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6166         if (CI->isMinValue(true))
6167           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6168                            Context->getAllOnesValue(Op0->getType()));
6169       }
6170       break;
6171     case ICmpInst::ICMP_UGT:
6172       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6173         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6174       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6175         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6176
6177       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6178         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6179       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6180         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6181           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6182                               AddOne(CI, Context));
6183
6184         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6185         if (CI->isMaxValue(true))
6186           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6187                               Context->getNullValue(Op0->getType()));
6188       }
6189       break;
6190     case ICmpInst::ICMP_SLT:
6191       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6192         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6193       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6194         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6195       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6196         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6197       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6198         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6199           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6200                               SubOne(CI, Context));
6201       }
6202       break;
6203     case ICmpInst::ICMP_SGT:
6204       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6205         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6206       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6207         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6208
6209       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6210         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6211       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6212         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6213           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6214                               AddOne(CI, Context));
6215       }
6216       break;
6217     case ICmpInst::ICMP_SGE:
6218       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6219       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6220         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6221       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6222         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6223       break;
6224     case ICmpInst::ICMP_SLE:
6225       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6226       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6227         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6228       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6229         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6230       break;
6231     case ICmpInst::ICMP_UGE:
6232       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6233       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6234         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6235       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6236         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6237       break;
6238     case ICmpInst::ICMP_ULE:
6239       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6240       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6241         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6242       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6243         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6244       break;
6245     }
6246
6247     // Turn a signed comparison into an unsigned one if both operands
6248     // are known to have the same sign.
6249     if (I.isSignedPredicate() &&
6250         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6251          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6252       return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
6253   }
6254
6255   // Test if the ICmpInst instruction is used exclusively by a select as
6256   // part of a minimum or maximum operation. If so, refrain from doing
6257   // any other folding. This helps out other analyses which understand
6258   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6259   // and CodeGen. And in this case, at least one of the comparison
6260   // operands has at least one user besides the compare (the select),
6261   // which would often largely negate the benefit of folding anyway.
6262   if (I.hasOneUse())
6263     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6264       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6265           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6266         return 0;
6267
6268   // See if we are doing a comparison between a constant and an instruction that
6269   // can be folded into the comparison.
6270   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6271     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6272     // instruction, see if that instruction also has constants so that the 
6273     // instruction can be folded into the icmp 
6274     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6275       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6276         return Res;
6277   }
6278
6279   // Handle icmp with constant (but not simple integer constant) RHS
6280   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6281     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6282       switch (LHSI->getOpcode()) {
6283       case Instruction::GetElementPtr:
6284         if (RHSC->isNullValue()) {
6285           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6286           bool isAllZeros = true;
6287           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6288             if (!isa<Constant>(LHSI->getOperand(i)) ||
6289                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6290               isAllZeros = false;
6291               break;
6292             }
6293           if (isAllZeros)
6294             return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
6295                     Context->getNullValue(LHSI->getOperand(0)->getType()));
6296         }
6297         break;
6298
6299       case Instruction::PHI:
6300         // Only fold icmp into the PHI if the phi and fcmp are in the same
6301         // block.  If in the same block, we're encouraging jump threading.  If
6302         // not, we are just pessimizing the code by making an i1 phi.
6303         if (LHSI->getParent() == I.getParent())
6304           if (Instruction *NV = FoldOpIntoPhi(I))
6305             return NV;
6306         break;
6307       case Instruction::Select: {
6308         // If either operand of the select is a constant, we can fold the
6309         // comparison into the select arms, which will cause one to be
6310         // constant folded and the select turned into a bitwise or.
6311         Value *Op1 = 0, *Op2 = 0;
6312         if (LHSI->hasOneUse()) {
6313           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6314             // Fold the known value into the constant operand.
6315             Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6316             // Insert a new ICmp of the other select operand.
6317             Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6318                                                    LHSI->getOperand(2), RHSC,
6319                                                    I.getName()), I);
6320           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6321             // Fold the known value into the constant operand.
6322             Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6323             // Insert a new ICmp of the other select operand.
6324             Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6325                                                    LHSI->getOperand(1), RHSC,
6326                                                    I.getName()), I);
6327           }
6328         }
6329
6330         if (Op1)
6331           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6332         break;
6333       }
6334       case Instruction::Malloc:
6335         // If we have (malloc != null), and if the malloc has a single use, we
6336         // can assume it is successful and remove the malloc.
6337         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6338           AddToWorkList(LHSI);
6339           return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
6340                                                          !I.isTrueWhenEqual()));
6341         }
6342         break;
6343       }
6344   }
6345
6346   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6347   if (User *GEP = dyn_castGetElementPtr(Op0))
6348     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6349       return NI;
6350   if (User *GEP = dyn_castGetElementPtr(Op1))
6351     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6352                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6353       return NI;
6354
6355   // Test to see if the operands of the icmp are casted versions of other
6356   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6357   // now.
6358   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6359     if (isa<PointerType>(Op0->getType()) && 
6360         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6361       // We keep moving the cast from the left operand over to the right
6362       // operand, where it can often be eliminated completely.
6363       Op0 = CI->getOperand(0);
6364
6365       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6366       // so eliminate it as well.
6367       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6368         Op1 = CI2->getOperand(0);
6369
6370       // If Op1 is a constant, we can fold the cast into the constant.
6371       if (Op0->getType() != Op1->getType()) {
6372         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6373           Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
6374         } else {
6375           // Otherwise, cast the RHS right before the icmp
6376           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6377         }
6378       }
6379       return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
6380     }
6381   }
6382   
6383   if (isa<CastInst>(Op0)) {
6384     // Handle the special case of: icmp (cast bool to X), <cst>
6385     // This comes up when you have code like
6386     //   int X = A < B;
6387     //   if (X) ...
6388     // For generality, we handle any zero-extension of any operand comparison
6389     // with a constant or another cast from the same type.
6390     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6391       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6392         return R;
6393   }
6394   
6395   // See if it's the same type of instruction on the left and right.
6396   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6397     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6398       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6399           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6400         switch (Op0I->getOpcode()) {
6401         default: break;
6402         case Instruction::Add:
6403         case Instruction::Sub:
6404         case Instruction::Xor:
6405           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6406             return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
6407                                 Op1I->getOperand(0));
6408           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6409           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6410             if (CI->getValue().isSignBit()) {
6411               ICmpInst::Predicate Pred = I.isSignedPredicate()
6412                                              ? I.getUnsignedPredicate()
6413                                              : I.getSignedPredicate();
6414               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6415                                   Op1I->getOperand(0));
6416             }
6417             
6418             if (CI->getValue().isMaxSignedValue()) {
6419               ICmpInst::Predicate Pred = I.isSignedPredicate()
6420                                              ? I.getUnsignedPredicate()
6421                                              : I.getSignedPredicate();
6422               Pred = I.getSwappedPredicate(Pred);
6423               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6424                                   Op1I->getOperand(0));
6425             }
6426           }
6427           break;
6428         case Instruction::Mul:
6429           if (!I.isEquality())
6430             break;
6431
6432           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6433             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6434             // Mask = -1 >> count-trailing-zeros(Cst).
6435             if (!CI->isZero() && !CI->isOne()) {
6436               const APInt &AP = CI->getValue();
6437               ConstantInt *Mask = Context->getConstantInt(
6438                                       APInt::getLowBitsSet(AP.getBitWidth(),
6439                                                            AP.getBitWidth() -
6440                                                       AP.countTrailingZeros()));
6441               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6442                                                             Mask);
6443               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6444                                                             Mask);
6445               InsertNewInstBefore(And1, I);
6446               InsertNewInstBefore(And2, I);
6447               return new ICmpInst(*Context, I.getPredicate(), And1, And2);
6448             }
6449           }
6450           break;
6451         }
6452       }
6453     }
6454   }
6455   
6456   // ~x < ~y --> y < x
6457   { Value *A, *B;
6458     if (match(Op0, m_Not(m_Value(A)), *Context) &&
6459         match(Op1, m_Not(m_Value(B)), *Context))
6460       return new ICmpInst(*Context, I.getPredicate(), B, A);
6461   }
6462   
6463   if (I.isEquality()) {
6464     Value *A, *B, *C, *D;
6465     
6466     // -x == -y --> x == y
6467     if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6468         match(Op1, m_Neg(m_Value(B)), *Context))
6469       return new ICmpInst(*Context, I.getPredicate(), A, B);
6470     
6471     if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
6472       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6473         Value *OtherVal = A == Op1 ? B : A;
6474         return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6475                             Context->getNullValue(A->getType()));
6476       }
6477
6478       if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
6479         // A^c1 == C^c2 --> A == C^(c1^c2)
6480         ConstantInt *C1, *C2;
6481         if (match(B, m_ConstantInt(C1), *Context) &&
6482             match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
6483           Constant *NC = 
6484                        Context->getConstantInt(C1->getValue() ^ C2->getValue());
6485           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6486           return new ICmpInst(*Context, I.getPredicate(), A,
6487                               InsertNewInstBefore(Xor, I));
6488         }
6489         
6490         // A^B == A^D -> B == D
6491         if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6492         if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6493         if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6494         if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
6495       }
6496     }
6497     
6498     if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
6499         (A == Op0 || B == Op0)) {
6500       // A == (A^B)  ->  B == 0
6501       Value *OtherVal = A == Op0 ? B : A;
6502       return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6503                           Context->getNullValue(A->getType()));
6504     }
6505
6506     // (A-B) == A  ->  B == 0
6507     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
6508       return new ICmpInst(*Context, I.getPredicate(), B, 
6509                           Context->getNullValue(B->getType()));
6510
6511     // A == (A-B)  ->  B == 0
6512     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
6513       return new ICmpInst(*Context, I.getPredicate(), B,
6514                           Context->getNullValue(B->getType()));
6515     
6516     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6517     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6518         match(Op0, m_And(m_Value(A), m_Value(B)), *Context) && 
6519         match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
6520       Value *X = 0, *Y = 0, *Z = 0;
6521       
6522       if (A == C) {
6523         X = B; Y = D; Z = A;
6524       } else if (A == D) {
6525         X = B; Y = C; Z = A;
6526       } else if (B == C) {
6527         X = A; Y = D; Z = B;
6528       } else if (B == D) {
6529         X = A; Y = C; Z = B;
6530       }
6531       
6532       if (X) {   // Build (X^Y) & Z
6533         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6534         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6535         I.setOperand(0, Op1);
6536         I.setOperand(1, Context->getNullValue(Op1->getType()));
6537         return &I;
6538       }
6539     }
6540   }
6541   return Changed ? &I : 0;
6542 }
6543
6544
6545 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6546 /// and CmpRHS are both known to be integer constants.
6547 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6548                                           ConstantInt *DivRHS) {
6549   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6550   const APInt &CmpRHSV = CmpRHS->getValue();
6551   
6552   // FIXME: If the operand types don't match the type of the divide 
6553   // then don't attempt this transform. The code below doesn't have the
6554   // logic to deal with a signed divide and an unsigned compare (and
6555   // vice versa). This is because (x /s C1) <s C2  produces different 
6556   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6557   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6558   // work. :(  The if statement below tests that condition and bails 
6559   // if it finds it. 
6560   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6561   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6562     return 0;
6563   if (DivRHS->isZero())
6564     return 0; // The ProdOV computation fails on divide by zero.
6565   if (DivIsSigned && DivRHS->isAllOnesValue())
6566     return 0; // The overflow computation also screws up here
6567   if (DivRHS->isOne())
6568     return 0; // Not worth bothering, and eliminates some funny cases
6569               // with INT_MIN.
6570
6571   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6572   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6573   // C2 (CI). By solving for X we can turn this into a range check 
6574   // instead of computing a divide. 
6575   Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
6576
6577   // Determine if the product overflows by seeing if the product is
6578   // not equal to the divide. Make sure we do the same kind of divide
6579   // as in the LHS instruction that we're folding. 
6580   bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6581                  Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
6582
6583   // Get the ICmp opcode
6584   ICmpInst::Predicate Pred = ICI.getPredicate();
6585
6586   // Figure out the interval that is being checked.  For example, a comparison
6587   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6588   // Compute this interval based on the constants involved and the signedness of
6589   // the compare/divide.  This computes a half-open interval, keeping track of
6590   // whether either value in the interval overflows.  After analysis each
6591   // overflow variable is set to 0 if it's corresponding bound variable is valid
6592   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6593   int LoOverflow = 0, HiOverflow = 0;
6594   Constant *LoBound = 0, *HiBound = 0;
6595   
6596   if (!DivIsSigned) {  // udiv
6597     // e.g. X/5 op 3  --> [15, 20)
6598     LoBound = Prod;
6599     HiOverflow = LoOverflow = ProdOV;
6600     if (!HiOverflow)
6601       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6602   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6603     if (CmpRHSV == 0) {       // (X / pos) op 0
6604       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6605       LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS, 
6606                                                                     Context)));
6607       HiBound = DivRHS;
6608     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6609       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6610       HiOverflow = LoOverflow = ProdOV;
6611       if (!HiOverflow)
6612         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6613     } else {                       // (X / pos) op neg
6614       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6615       HiBound = AddOne(Prod, Context);
6616       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6617       if (!LoOverflow) {
6618         ConstantInt* DivNeg =
6619                          cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6620         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6621                                      true) ? -1 : 0;
6622        }
6623     }
6624   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6625     if (CmpRHSV == 0) {       // (X / neg) op 0
6626       // e.g. X/-5 op 0  --> [-4, 5)
6627       LoBound = AddOne(DivRHS, Context);
6628       HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6629       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6630         HiOverflow = 1;            // [INTMIN+1, overflow)
6631         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6632       }
6633     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6634       // e.g. X/-5 op 3  --> [-19, -14)
6635       HiBound = AddOne(Prod, Context);
6636       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6637       if (!LoOverflow)
6638         LoOverflow = AddWithOverflow(LoBound, HiBound,
6639                                      DivRHS, Context, true) ? -1 : 0;
6640     } else {                       // (X / neg) op neg
6641       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6642       LoOverflow = HiOverflow = ProdOV;
6643       if (!HiOverflow)
6644         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6645     }
6646     
6647     // Dividing by a negative swaps the condition.  LT <-> GT
6648     Pred = ICmpInst::getSwappedPredicate(Pred);
6649   }
6650
6651   Value *X = DivI->getOperand(0);
6652   switch (Pred) {
6653   default: llvm_unreachable("Unhandled icmp opcode!");
6654   case ICmpInst::ICMP_EQ:
6655     if (LoOverflow && HiOverflow)
6656       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6657     else if (HiOverflow)
6658       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6659                           ICmpInst::ICMP_UGE, X, LoBound);
6660     else if (LoOverflow)
6661       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6662                           ICmpInst::ICMP_ULT, X, HiBound);
6663     else
6664       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6665   case ICmpInst::ICMP_NE:
6666     if (LoOverflow && HiOverflow)
6667       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6668     else if (HiOverflow)
6669       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6670                           ICmpInst::ICMP_ULT, X, LoBound);
6671     else if (LoOverflow)
6672       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6673                           ICmpInst::ICMP_UGE, X, HiBound);
6674     else
6675       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6676   case ICmpInst::ICMP_ULT:
6677   case ICmpInst::ICMP_SLT:
6678     if (LoOverflow == +1)   // Low bound is greater than input range.
6679       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6680     if (LoOverflow == -1)   // Low bound is less than input range.
6681       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6682     return new ICmpInst(*Context, Pred, X, LoBound);
6683   case ICmpInst::ICMP_UGT:
6684   case ICmpInst::ICMP_SGT:
6685     if (HiOverflow == +1)       // High bound greater than input range.
6686       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6687     else if (HiOverflow == -1)  // High bound less than input range.
6688       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6689     if (Pred == ICmpInst::ICMP_UGT)
6690       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
6691     else
6692       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
6693   }
6694 }
6695
6696
6697 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6698 ///
6699 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6700                                                           Instruction *LHSI,
6701                                                           ConstantInt *RHS) {
6702   const APInt &RHSV = RHS->getValue();
6703   
6704   switch (LHSI->getOpcode()) {
6705   case Instruction::Trunc:
6706     if (ICI.isEquality() && LHSI->hasOneUse()) {
6707       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6708       // of the high bits truncated out of x are known.
6709       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6710              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6711       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6712       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6713       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6714       
6715       // If all the high bits are known, we can do this xform.
6716       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6717         // Pull in the high bits from known-ones set.
6718         APInt NewRHS(RHS->getValue());
6719         NewRHS.zext(SrcBits);
6720         NewRHS |= KnownOne;
6721         return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
6722                             Context->getConstantInt(NewRHS));
6723       }
6724     }
6725     break;
6726       
6727   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6728     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6729       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6730       // fold the xor.
6731       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6732           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6733         Value *CompareVal = LHSI->getOperand(0);
6734         
6735         // If the sign bit of the XorCST is not set, there is no change to
6736         // the operation, just stop using the Xor.
6737         if (!XorCST->getValue().isNegative()) {
6738           ICI.setOperand(0, CompareVal);
6739           AddToWorkList(LHSI);
6740           return &ICI;
6741         }
6742         
6743         // Was the old condition true if the operand is positive?
6744         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6745         
6746         // If so, the new one isn't.
6747         isTrueIfPositive ^= true;
6748         
6749         if (isTrueIfPositive)
6750           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
6751                               SubOne(RHS, Context));
6752         else
6753           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
6754                               AddOne(RHS, Context));
6755       }
6756
6757       if (LHSI->hasOneUse()) {
6758         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6759         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6760           const APInt &SignBit = XorCST->getValue();
6761           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6762                                          ? ICI.getUnsignedPredicate()
6763                                          : ICI.getSignedPredicate();
6764           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6765                               Context->getConstantInt(RHSV ^ SignBit));
6766         }
6767
6768         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6769         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6770           const APInt &NotSignBit = XorCST->getValue();
6771           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6772                                          ? ICI.getUnsignedPredicate()
6773                                          : ICI.getSignedPredicate();
6774           Pred = ICI.getSwappedPredicate(Pred);
6775           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6776                               Context->getConstantInt(RHSV ^ NotSignBit));
6777         }
6778       }
6779     }
6780     break;
6781   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6782     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6783         LHSI->getOperand(0)->hasOneUse()) {
6784       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6785       
6786       // If the LHS is an AND of a truncating cast, we can widen the
6787       // and/compare to be the input width without changing the value
6788       // produced, eliminating a cast.
6789       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6790         // We can do this transformation if either the AND constant does not
6791         // have its sign bit set or if it is an equality comparison. 
6792         // Extending a relational comparison when we're checking the sign
6793         // bit would not work.
6794         if (Cast->hasOneUse() &&
6795             (ICI.isEquality() ||
6796              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6797           uint32_t BitWidth = 
6798             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6799           APInt NewCST = AndCST->getValue();
6800           NewCST.zext(BitWidth);
6801           APInt NewCI = RHSV;
6802           NewCI.zext(BitWidth);
6803           Instruction *NewAnd = 
6804             BinaryOperator::CreateAnd(Cast->getOperand(0),
6805                                Context->getConstantInt(NewCST),LHSI->getName());
6806           InsertNewInstBefore(NewAnd, ICI);
6807           return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
6808                               Context->getConstantInt(NewCI));
6809         }
6810       }
6811       
6812       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6813       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6814       // happens a LOT in code produced by the C front-end, for bitfield
6815       // access.
6816       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6817       if (Shift && !Shift->isShift())
6818         Shift = 0;
6819       
6820       ConstantInt *ShAmt;
6821       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6822       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6823       const Type *AndTy = AndCST->getType();          // Type of the and.
6824       
6825       // We can fold this as long as we can't shift unknown bits
6826       // into the mask.  This can only happen with signed shift
6827       // rights, as they sign-extend.
6828       if (ShAmt) {
6829         bool CanFold = Shift->isLogicalShift();
6830         if (!CanFold) {
6831           // To test for the bad case of the signed shr, see if any
6832           // of the bits shifted in could be tested after the mask.
6833           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6834           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6835           
6836           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6837           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6838                AndCST->getValue()) == 0)
6839             CanFold = true;
6840         }
6841         
6842         if (CanFold) {
6843           Constant *NewCst;
6844           if (Shift->getOpcode() == Instruction::Shl)
6845             NewCst = Context->getConstantExprLShr(RHS, ShAmt);
6846           else
6847             NewCst = Context->getConstantExprShl(RHS, ShAmt);
6848           
6849           // Check to see if we are shifting out any of the bits being
6850           // compared.
6851           if (Context->getConstantExpr(Shift->getOpcode(),
6852                                        NewCst, ShAmt) != RHS) {
6853             // If we shifted bits out, the fold is not going to work out.
6854             // As a special case, check to see if this means that the
6855             // result is always true or false now.
6856             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6857               return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6858             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6859               return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6860           } else {
6861             ICI.setOperand(1, NewCst);
6862             Constant *NewAndCST;
6863             if (Shift->getOpcode() == Instruction::Shl)
6864               NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
6865             else
6866               NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
6867             LHSI->setOperand(1, NewAndCST);
6868             LHSI->setOperand(0, Shift->getOperand(0));
6869             AddToWorkList(Shift); // Shift is dead.
6870             AddUsesToWorkList(ICI);
6871             return &ICI;
6872           }
6873         }
6874       }
6875       
6876       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6877       // preferable because it allows the C<<Y expression to be hoisted out
6878       // of a loop if Y is invariant and X is not.
6879       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6880           ICI.isEquality() && !Shift->isArithmeticShift() &&
6881           !isa<Constant>(Shift->getOperand(0))) {
6882         // Compute C << Y.
6883         Value *NS;
6884         if (Shift->getOpcode() == Instruction::LShr) {
6885           NS = BinaryOperator::CreateShl(AndCST, 
6886                                          Shift->getOperand(1), "tmp");
6887         } else {
6888           // Insert a logical shift.
6889           NS = BinaryOperator::CreateLShr(AndCST,
6890                                           Shift->getOperand(1), "tmp");
6891         }
6892         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6893         
6894         // Compute X & (C << Y).
6895         Instruction *NewAnd = 
6896           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6897         InsertNewInstBefore(NewAnd, ICI);
6898         
6899         ICI.setOperand(0, NewAnd);
6900         return &ICI;
6901       }
6902     }
6903     break;
6904     
6905   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6906     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6907     if (!ShAmt) break;
6908     
6909     uint32_t TypeBits = RHSV.getBitWidth();
6910     
6911     // Check that the shift amount is in range.  If not, don't perform
6912     // undefined shifts.  When the shift is visited it will be
6913     // simplified.
6914     if (ShAmt->uge(TypeBits))
6915       break;
6916     
6917     if (ICI.isEquality()) {
6918       // If we are comparing against bits always shifted out, the
6919       // comparison cannot succeed.
6920       Constant *Comp =
6921         Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6922                                                                  ShAmt);
6923       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6924         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6925         Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
6926         return ReplaceInstUsesWith(ICI, Cst);
6927       }
6928       
6929       if (LHSI->hasOneUse()) {
6930         // Otherwise strength reduce the shift into an and.
6931         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6932         Constant *Mask =
6933           Context->getConstantInt(APInt::getLowBitsSet(TypeBits, 
6934                                                        TypeBits-ShAmtVal));
6935         
6936         Instruction *AndI =
6937           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6938                                     Mask, LHSI->getName()+".mask");
6939         Value *And = InsertNewInstBefore(AndI, ICI);
6940         return new ICmpInst(*Context, ICI.getPredicate(), And,
6941                             Context->getConstantInt(RHSV.lshr(ShAmtVal)));
6942       }
6943     }
6944     
6945     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6946     bool TrueIfSigned = false;
6947     if (LHSI->hasOneUse() &&
6948         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6949       // (X << 31) <s 0  --> (X&1) != 0
6950       Constant *Mask = Context->getConstantInt(APInt(TypeBits, 1) <<
6951                                            (TypeBits-ShAmt->getZExtValue()-1));
6952       Instruction *AndI =
6953         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6954                                   Mask, LHSI->getName()+".mask");
6955       Value *And = InsertNewInstBefore(AndI, ICI);
6956       
6957       return new ICmpInst(*Context,
6958                           TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6959                           And, Context->getNullValue(And->getType()));
6960     }
6961     break;
6962   }
6963     
6964   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6965   case Instruction::AShr: {
6966     // Only handle equality comparisons of shift-by-constant.
6967     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6968     if (!ShAmt || !ICI.isEquality()) break;
6969
6970     // Check that the shift amount is in range.  If not, don't perform
6971     // undefined shifts.  When the shift is visited it will be
6972     // simplified.
6973     uint32_t TypeBits = RHSV.getBitWidth();
6974     if (ShAmt->uge(TypeBits))
6975       break;
6976     
6977     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6978       
6979     // If we are comparing against bits always shifted out, the
6980     // comparison cannot succeed.
6981     APInt Comp = RHSV << ShAmtVal;
6982     if (LHSI->getOpcode() == Instruction::LShr)
6983       Comp = Comp.lshr(ShAmtVal);
6984     else
6985       Comp = Comp.ashr(ShAmtVal);
6986     
6987     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6988       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6989       Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
6990       return ReplaceInstUsesWith(ICI, Cst);
6991     }
6992     
6993     // Otherwise, check to see if the bits shifted out are known to be zero.
6994     // If so, we can compare against the unshifted value:
6995     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6996     if (LHSI->hasOneUse() &&
6997         MaskedValueIsZero(LHSI->getOperand(0), 
6998                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6999       return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
7000                           Context->getConstantExprShl(RHS, ShAmt));
7001     }
7002       
7003     if (LHSI->hasOneUse()) {
7004       // Otherwise strength reduce the shift into an and.
7005       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
7006       Constant *Mask = Context->getConstantInt(Val);
7007       
7008       Instruction *AndI =
7009         BinaryOperator::CreateAnd(LHSI->getOperand(0),
7010                                   Mask, LHSI->getName()+".mask");
7011       Value *And = InsertNewInstBefore(AndI, ICI);
7012       return new ICmpInst(*Context, ICI.getPredicate(), And,
7013                           Context->getConstantExprShl(RHS, ShAmt));
7014     }
7015     break;
7016   }
7017     
7018   case Instruction::SDiv:
7019   case Instruction::UDiv:
7020     // Fold: icmp pred ([us]div X, C1), C2 -> range test
7021     // Fold this div into the comparison, producing a range check. 
7022     // Determine, based on the divide type, what the range is being 
7023     // checked.  If there is an overflow on the low or high side, remember 
7024     // it, otherwise compute the range [low, hi) bounding the new value.
7025     // See: InsertRangeTest above for the kinds of replacements possible.
7026     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7027       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7028                                           DivRHS))
7029         return R;
7030     break;
7031
7032   case Instruction::Add:
7033     // Fold: icmp pred (add, X, C1), C2
7034
7035     if (!ICI.isEquality()) {
7036       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7037       if (!LHSC) break;
7038       const APInt &LHSV = LHSC->getValue();
7039
7040       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7041                             .subtract(LHSV);
7042
7043       if (ICI.isSignedPredicate()) {
7044         if (CR.getLower().isSignBit()) {
7045           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7046                               Context->getConstantInt(CR.getUpper()));
7047         } else if (CR.getUpper().isSignBit()) {
7048           return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7049                               Context->getConstantInt(CR.getLower()));
7050         }
7051       } else {
7052         if (CR.getLower().isMinValue()) {
7053           return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7054                               Context->getConstantInt(CR.getUpper()));
7055         } else if (CR.getUpper().isMinValue()) {
7056           return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7057                               Context->getConstantInt(CR.getLower()));
7058         }
7059       }
7060     }
7061     break;
7062   }
7063   
7064   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7065   if (ICI.isEquality()) {
7066     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7067     
7068     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7069     // the second operand is a constant, simplify a bit.
7070     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7071       switch (BO->getOpcode()) {
7072       case Instruction::SRem:
7073         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7074         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7075           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7076           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7077             Instruction *NewRem =
7078               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
7079                                          BO->getName());
7080             InsertNewInstBefore(NewRem, ICI);
7081             return new ICmpInst(*Context, ICI.getPredicate(), NewRem, 
7082                                 Context->getNullValue(BO->getType()));
7083           }
7084         }
7085         break;
7086       case Instruction::Add:
7087         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7088         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7089           if (BO->hasOneUse())
7090             return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7091                                 Context->getConstantExprSub(RHS, BOp1C));
7092         } else if (RHSV == 0) {
7093           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7094           // efficiently invertible, or if the add has just this one use.
7095           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7096           
7097           if (Value *NegVal = dyn_castNegVal(BOp1, Context))
7098             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
7099           else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
7100             return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
7101           else if (BO->hasOneUse()) {
7102             Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
7103             InsertNewInstBefore(Neg, ICI);
7104             Neg->takeName(BO);
7105             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
7106           }
7107         }
7108         break;
7109       case Instruction::Xor:
7110         // For the xor case, we can xor two constants together, eliminating
7111         // the explicit xor.
7112         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7113           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0), 
7114                               Context->getConstantExprXor(RHS, BOC));
7115         
7116         // FALLTHROUGH
7117       case Instruction::Sub:
7118         // Replace (([sub|xor] A, B) != 0) with (A != B)
7119         if (RHSV == 0)
7120           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7121                               BO->getOperand(1));
7122         break;
7123         
7124       case Instruction::Or:
7125         // If bits are being or'd in that are not present in the constant we
7126         // are comparing against, then the comparison could never succeed!
7127         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7128           Constant *NotCI = Context->getConstantExprNot(RHS);
7129           if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7130             return ReplaceInstUsesWith(ICI,
7131                                        Context->getConstantInt(Type::Int1Ty, 
7132                                        isICMP_NE));
7133         }
7134         break;
7135         
7136       case Instruction::And:
7137         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7138           // If bits are being compared against that are and'd out, then the
7139           // comparison can never succeed!
7140           if ((RHSV & ~BOC->getValue()) != 0)
7141             return ReplaceInstUsesWith(ICI,
7142                                        Context->getConstantInt(Type::Int1Ty,
7143                                        isICMP_NE));
7144           
7145           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7146           if (RHS == BOC && RHSV.isPowerOf2())
7147             return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
7148                                 ICmpInst::ICMP_NE, LHSI,
7149                                 Context->getNullValue(RHS->getType()));
7150           
7151           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7152           if (BOC->getValue().isSignBit()) {
7153             Value *X = BO->getOperand(0);
7154             Constant *Zero = Context->getNullValue(X->getType());
7155             ICmpInst::Predicate pred = isICMP_NE ? 
7156               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7157             return new ICmpInst(*Context, pred, X, Zero);
7158           }
7159           
7160           // ((X & ~7) == 0) --> X < 8
7161           if (RHSV == 0 && isHighOnes(BOC)) {
7162             Value *X = BO->getOperand(0);
7163             Constant *NegX = Context->getConstantExprNeg(BOC);
7164             ICmpInst::Predicate pred = isICMP_NE ? 
7165               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7166             return new ICmpInst(*Context, pred, X, NegX);
7167           }
7168         }
7169       default: break;
7170       }
7171     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7172       // Handle icmp {eq|ne} <intrinsic>, intcst.
7173       if (II->getIntrinsicID() == Intrinsic::bswap) {
7174         AddToWorkList(II);
7175         ICI.setOperand(0, II->getOperand(1));
7176         ICI.setOperand(1, Context->getConstantInt(RHSV.byteSwap()));
7177         return &ICI;
7178       }
7179     }
7180   }
7181   return 0;
7182 }
7183
7184 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7185 /// We only handle extending casts so far.
7186 ///
7187 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7188   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7189   Value *LHSCIOp        = LHSCI->getOperand(0);
7190   const Type *SrcTy     = LHSCIOp->getType();
7191   const Type *DestTy    = LHSCI->getType();
7192   Value *RHSCIOp;
7193
7194   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7195   // integer type is the same size as the pointer type.
7196   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7197       getTargetData().getPointerSizeInBits() == 
7198          cast<IntegerType>(DestTy)->getBitWidth()) {
7199     Value *RHSOp = 0;
7200     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7201       RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
7202     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7203       RHSOp = RHSC->getOperand(0);
7204       // If the pointer types don't match, insert a bitcast.
7205       if (LHSCIOp->getType() != RHSOp->getType())
7206         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
7207     }
7208
7209     if (RHSOp)
7210       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
7211   }
7212   
7213   // The code below only handles extension cast instructions, so far.
7214   // Enforce this.
7215   if (LHSCI->getOpcode() != Instruction::ZExt &&
7216       LHSCI->getOpcode() != Instruction::SExt)
7217     return 0;
7218
7219   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7220   bool isSignedCmp = ICI.isSignedPredicate();
7221
7222   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7223     // Not an extension from the same type?
7224     RHSCIOp = CI->getOperand(0);
7225     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7226       return 0;
7227     
7228     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7229     // and the other is a zext), then we can't handle this.
7230     if (CI->getOpcode() != LHSCI->getOpcode())
7231       return 0;
7232
7233     // Deal with equality cases early.
7234     if (ICI.isEquality())
7235       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7236
7237     // A signed comparison of sign extended values simplifies into a
7238     // signed comparison.
7239     if (isSignedCmp && isSignedExt)
7240       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7241
7242     // The other three cases all fold into an unsigned comparison.
7243     return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7244   }
7245
7246   // If we aren't dealing with a constant on the RHS, exit early
7247   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7248   if (!CI)
7249     return 0;
7250
7251   // Compute the constant that would happen if we truncated to SrcTy then
7252   // reextended to DestTy.
7253   Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7254   Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7255                                                 Res1, DestTy);
7256
7257   // If the re-extended constant didn't change...
7258   if (Res2 == CI) {
7259     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7260     // For example, we might have:
7261     //    %A = sext i16 %X to i32
7262     //    %B = icmp ugt i32 %A, 1330
7263     // It is incorrect to transform this into 
7264     //    %B = icmp ugt i16 %X, 1330
7265     // because %A may have negative value. 
7266     //
7267     // However, we allow this when the compare is EQ/NE, because they are
7268     // signless.
7269     if (isSignedExt == isSignedCmp || ICI.isEquality())
7270       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
7271     return 0;
7272   }
7273
7274   // The re-extended constant changed so the constant cannot be represented 
7275   // in the shorter type. Consequently, we cannot emit a simple comparison.
7276
7277   // First, handle some easy cases. We know the result cannot be equal at this
7278   // point so handle the ICI.isEquality() cases
7279   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7280     return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
7281   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7282     return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
7283
7284   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7285   // should have been folded away previously and not enter in here.
7286   Value *Result;
7287   if (isSignedCmp) {
7288     // We're performing a signed comparison.
7289     if (cast<ConstantInt>(CI)->getValue().isNegative())
7290       Result = Context->getConstantIntFalse();          // X < (small) --> false
7291     else
7292       Result = Context->getConstantIntTrue();           // X < (large) --> true
7293   } else {
7294     // We're performing an unsigned comparison.
7295     if (isSignedExt) {
7296       // We're performing an unsigned comp with a sign extended value.
7297       // This is true if the input is >= 0. [aka >s -1]
7298       Constant *NegOne = Context->getAllOnesValue(SrcTy);
7299       Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT, 
7300                                    LHSCIOp, NegOne, ICI.getName()), ICI);
7301     } else {
7302       // Unsigned extend & unsigned compare -> always true.
7303       Result = Context->getConstantIntTrue();
7304     }
7305   }
7306
7307   // Finally, return the value computed.
7308   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7309       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7310     return ReplaceInstUsesWith(ICI, Result);
7311
7312   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7313           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7314          "ICmp should be folded!");
7315   if (Constant *CI = dyn_cast<Constant>(Result))
7316     return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
7317   return BinaryOperator::CreateNot(*Context, Result);
7318 }
7319
7320 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7321   return commonShiftTransforms(I);
7322 }
7323
7324 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7325   return commonShiftTransforms(I);
7326 }
7327
7328 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7329   if (Instruction *R = commonShiftTransforms(I))
7330     return R;
7331   
7332   Value *Op0 = I.getOperand(0);
7333   
7334   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7335   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7336     if (CSI->isAllOnesValue())
7337       return ReplaceInstUsesWith(I, CSI);
7338
7339   // See if we can turn a signed shr into an unsigned shr.
7340   if (MaskedValueIsZero(Op0,
7341                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7342     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7343
7344   // Arithmetic shifting an all-sign-bit value is a no-op.
7345   unsigned NumSignBits = ComputeNumSignBits(Op0);
7346   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7347     return ReplaceInstUsesWith(I, Op0);
7348
7349   return 0;
7350 }
7351
7352 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7353   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7354   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7355
7356   // shl X, 0 == X and shr X, 0 == X
7357   // shl 0, X == 0 and shr 0, X == 0
7358   if (Op1 == Context->getNullValue(Op1->getType()) ||
7359       Op0 == Context->getNullValue(Op0->getType()))
7360     return ReplaceInstUsesWith(I, Op0);
7361   
7362   if (isa<UndefValue>(Op0)) {            
7363     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7364       return ReplaceInstUsesWith(I, Op0);
7365     else                                    // undef << X -> 0, undef >>u X -> 0
7366       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7367   }
7368   if (isa<UndefValue>(Op1)) {
7369     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7370       return ReplaceInstUsesWith(I, Op0);          
7371     else                                     // X << undef, X >>u undef -> 0
7372       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7373   }
7374
7375   // See if we can fold away this shift.
7376   if (SimplifyDemandedInstructionBits(I))
7377     return &I;
7378
7379   // Try to fold constant and into select arguments.
7380   if (isa<Constant>(Op0))
7381     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7382       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7383         return R;
7384
7385   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7386     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7387       return Res;
7388   return 0;
7389 }
7390
7391 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7392                                                BinaryOperator &I) {
7393   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7394
7395   // See if we can simplify any instructions used by the instruction whose sole 
7396   // purpose is to compute bits we don't care about.
7397   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7398   
7399   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7400   // a signed shift.
7401   //
7402   if (Op1->uge(TypeBits)) {
7403     if (I.getOpcode() != Instruction::AShr)
7404       return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
7405     else {
7406       I.setOperand(1, Context->getConstantInt(I.getType(), TypeBits-1));
7407       return &I;
7408     }
7409   }
7410   
7411   // ((X*C1) << C2) == (X * (C1 << C2))
7412   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7413     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7414       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7415         return BinaryOperator::CreateMul(BO->getOperand(0),
7416                                         Context->getConstantExprShl(BOOp, Op1));
7417   
7418   // Try to fold constant and into select arguments.
7419   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7420     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7421       return R;
7422   if (isa<PHINode>(Op0))
7423     if (Instruction *NV = FoldOpIntoPhi(I))
7424       return NV;
7425   
7426   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7427   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7428     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7429     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7430     // place.  Don't try to do this transformation in this case.  Also, we
7431     // require that the input operand is a shift-by-constant so that we have
7432     // confidence that the shifts will get folded together.  We could do this
7433     // xform in more cases, but it is unlikely to be profitable.
7434     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7435         isa<ConstantInt>(TrOp->getOperand(1))) {
7436       // Okay, we'll do this xform.  Make the shift of shift.
7437       Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
7438       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7439                                                 I.getName());
7440       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7441
7442       // For logical shifts, the truncation has the effect of making the high
7443       // part of the register be zeros.  Emulate this by inserting an AND to
7444       // clear the top bits as needed.  This 'and' will usually be zapped by
7445       // other xforms later if dead.
7446       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7447       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7448       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7449       
7450       // The mask we constructed says what the trunc would do if occurring
7451       // between the shifts.  We want to know the effect *after* the second
7452       // shift.  We know that it is a logical shift by a constant, so adjust the
7453       // mask as appropriate.
7454       if (I.getOpcode() == Instruction::Shl)
7455         MaskV <<= Op1->getZExtValue();
7456       else {
7457         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7458         MaskV = MaskV.lshr(Op1->getZExtValue());
7459       }
7460
7461       Instruction *And =
7462         BinaryOperator::CreateAnd(NSh, Context->getConstantInt(MaskV), 
7463                                   TI->getName());
7464       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7465
7466       // Return the value truncated to the interesting size.
7467       return new TruncInst(And, I.getType());
7468     }
7469   }
7470   
7471   if (Op0->hasOneUse()) {
7472     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7473       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7474       Value *V1, *V2;
7475       ConstantInt *CC;
7476       switch (Op0BO->getOpcode()) {
7477         default: break;
7478         case Instruction::Add:
7479         case Instruction::And:
7480         case Instruction::Or:
7481         case Instruction::Xor: {
7482           // These operators commute.
7483           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7484           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7485               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7486                     m_Specific(Op1)), *Context)){
7487             Instruction *YS = BinaryOperator::CreateShl(
7488                                             Op0BO->getOperand(0), Op1,
7489                                             Op0BO->getName());
7490             InsertNewInstBefore(YS, I); // (Y << C)
7491             Instruction *X = 
7492               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7493                                      Op0BO->getOperand(1)->getName());
7494             InsertNewInstBefore(X, I);  // (X + (Y << C))
7495             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7496             return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7497                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7498           }
7499           
7500           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7501           Value *Op0BOOp1 = Op0BO->getOperand(1);
7502           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7503               match(Op0BOOp1, 
7504                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7505                           m_ConstantInt(CC)), *Context) &&
7506               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7507             Instruction *YS = BinaryOperator::CreateShl(
7508                                                      Op0BO->getOperand(0), Op1,
7509                                                      Op0BO->getName());
7510             InsertNewInstBefore(YS, I); // (Y << C)
7511             Instruction *XM =
7512               BinaryOperator::CreateAnd(V1,
7513                                         Context->getConstantExprShl(CC, Op1),
7514                                         V1->getName()+".mask");
7515             InsertNewInstBefore(XM, I); // X & (CC << C)
7516             
7517             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7518           }
7519         }
7520           
7521         // FALL THROUGH.
7522         case Instruction::Sub: {
7523           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7524           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7525               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7526                     m_Specific(Op1)), *Context)){
7527             Instruction *YS = BinaryOperator::CreateShl(
7528                                                      Op0BO->getOperand(1), Op1,
7529                                                      Op0BO->getName());
7530             InsertNewInstBefore(YS, I); // (Y << C)
7531             Instruction *X =
7532               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7533                                      Op0BO->getOperand(0)->getName());
7534             InsertNewInstBefore(X, I);  // (X + (Y << C))
7535             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7536             return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7537                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7538           }
7539           
7540           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7541           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7542               match(Op0BO->getOperand(0),
7543                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7544                           m_ConstantInt(CC)), *Context) && V2 == Op1 &&
7545               cast<BinaryOperator>(Op0BO->getOperand(0))
7546                   ->getOperand(0)->hasOneUse()) {
7547             Instruction *YS = BinaryOperator::CreateShl(
7548                                                      Op0BO->getOperand(1), Op1,
7549                                                      Op0BO->getName());
7550             InsertNewInstBefore(YS, I); // (Y << C)
7551             Instruction *XM =
7552               BinaryOperator::CreateAnd(V1, 
7553                                         Context->getConstantExprShl(CC, Op1),
7554                                         V1->getName()+".mask");
7555             InsertNewInstBefore(XM, I); // X & (CC << C)
7556             
7557             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7558           }
7559           
7560           break;
7561         }
7562       }
7563       
7564       
7565       // If the operand is an bitwise operator with a constant RHS, and the
7566       // shift is the only use, we can pull it out of the shift.
7567       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7568         bool isValid = true;     // Valid only for And, Or, Xor
7569         bool highBitSet = false; // Transform if high bit of constant set?
7570         
7571         switch (Op0BO->getOpcode()) {
7572           default: isValid = false; break;   // Do not perform transform!
7573           case Instruction::Add:
7574             isValid = isLeftShift;
7575             break;
7576           case Instruction::Or:
7577           case Instruction::Xor:
7578             highBitSet = false;
7579             break;
7580           case Instruction::And:
7581             highBitSet = true;
7582             break;
7583         }
7584         
7585         // If this is a signed shift right, and the high bit is modified
7586         // by the logical operation, do not perform the transformation.
7587         // The highBitSet boolean indicates the value of the high bit of
7588         // the constant which would cause it to be modified for this
7589         // operation.
7590         //
7591         if (isValid && I.getOpcode() == Instruction::AShr)
7592           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7593         
7594         if (isValid) {
7595           Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
7596           
7597           Instruction *NewShift =
7598             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7599           InsertNewInstBefore(NewShift, I);
7600           NewShift->takeName(Op0BO);
7601           
7602           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7603                                         NewRHS);
7604         }
7605       }
7606     }
7607   }
7608   
7609   // Find out if this is a shift of a shift by a constant.
7610   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7611   if (ShiftOp && !ShiftOp->isShift())
7612     ShiftOp = 0;
7613   
7614   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7615     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7616     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7617     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7618     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7619     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7620     Value *X = ShiftOp->getOperand(0);
7621     
7622     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7623     
7624     const IntegerType *Ty = cast<IntegerType>(I.getType());
7625     
7626     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7627     if (I.getOpcode() == ShiftOp->getOpcode()) {
7628       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7629       // saturates.
7630       if (AmtSum >= TypeBits) {
7631         if (I.getOpcode() != Instruction::AShr)
7632           return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7633         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7634       }
7635       
7636       return BinaryOperator::Create(I.getOpcode(), X,
7637                                     Context->getConstantInt(Ty, AmtSum));
7638     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7639                I.getOpcode() == Instruction::AShr) {
7640       if (AmtSum >= TypeBits)
7641         return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7642       
7643       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7644       return BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, AmtSum));
7645     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7646                I.getOpcode() == Instruction::LShr) {
7647       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7648       if (AmtSum >= TypeBits)
7649         AmtSum = TypeBits-1;
7650       
7651       Instruction *Shift =
7652         BinaryOperator::CreateAShr(X, Context->getConstantInt(Ty, AmtSum));
7653       InsertNewInstBefore(Shift, I);
7654
7655       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7656       return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7657     }
7658     
7659     // Okay, if we get here, one shift must be left, and the other shift must be
7660     // right.  See if the amounts are equal.
7661     if (ShiftAmt1 == ShiftAmt2) {
7662       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7663       if (I.getOpcode() == Instruction::Shl) {
7664         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7665         return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7666       }
7667       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7668       if (I.getOpcode() == Instruction::LShr) {
7669         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7670         return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7671       }
7672       // We can simplify ((X << C) >>s C) into a trunc + sext.
7673       // NOTE: we could do this for any C, but that would make 'unusual' integer
7674       // types.  For now, just stick to ones well-supported by the code
7675       // generators.
7676       const Type *SExtType = 0;
7677       switch (Ty->getBitWidth() - ShiftAmt1) {
7678       case 1  :
7679       case 8  :
7680       case 16 :
7681       case 32 :
7682       case 64 :
7683       case 128:
7684         SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
7685         break;
7686       default: break;
7687       }
7688       if (SExtType) {
7689         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7690         InsertNewInstBefore(NewTrunc, I);
7691         return new SExtInst(NewTrunc, Ty);
7692       }
7693       // Otherwise, we can't handle it yet.
7694     } else if (ShiftAmt1 < ShiftAmt2) {
7695       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7696       
7697       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7698       if (I.getOpcode() == Instruction::Shl) {
7699         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7700                ShiftOp->getOpcode() == Instruction::AShr);
7701         Instruction *Shift =
7702           BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7703         InsertNewInstBefore(Shift, I);
7704         
7705         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7706         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7707       }
7708       
7709       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7710       if (I.getOpcode() == Instruction::LShr) {
7711         assert(ShiftOp->getOpcode() == Instruction::Shl);
7712         Instruction *Shift =
7713           BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, ShiftDiff));
7714         InsertNewInstBefore(Shift, I);
7715         
7716         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7717         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7718       }
7719       
7720       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7721     } else {
7722       assert(ShiftAmt2 < ShiftAmt1);
7723       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7724
7725       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7726       if (I.getOpcode() == Instruction::Shl) {
7727         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7728                ShiftOp->getOpcode() == Instruction::AShr);
7729         Instruction *Shift =
7730           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7731                                  Context->getConstantInt(Ty, ShiftDiff));
7732         InsertNewInstBefore(Shift, I);
7733         
7734         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7735         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7736       }
7737       
7738       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7739       if (I.getOpcode() == Instruction::LShr) {
7740         assert(ShiftOp->getOpcode() == Instruction::Shl);
7741         Instruction *Shift =
7742           BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7743         InsertNewInstBefore(Shift, I);
7744         
7745         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7746         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7747       }
7748       
7749       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7750     }
7751   }
7752   return 0;
7753 }
7754
7755
7756 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7757 /// expression.  If so, decompose it, returning some value X, such that Val is
7758 /// X*Scale+Offset.
7759 ///
7760 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7761                                         int &Offset, LLVMContext *Context) {
7762   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7763   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7764     Offset = CI->getZExtValue();
7765     Scale  = 0;
7766     return Context->getConstantInt(Type::Int32Ty, 0);
7767   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7768     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7769       if (I->getOpcode() == Instruction::Shl) {
7770         // This is a value scaled by '1 << the shift amt'.
7771         Scale = 1U << RHS->getZExtValue();
7772         Offset = 0;
7773         return I->getOperand(0);
7774       } else if (I->getOpcode() == Instruction::Mul) {
7775         // This value is scaled by 'RHS'.
7776         Scale = RHS->getZExtValue();
7777         Offset = 0;
7778         return I->getOperand(0);
7779       } else if (I->getOpcode() == Instruction::Add) {
7780         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7781         // where C1 is divisible by C2.
7782         unsigned SubScale;
7783         Value *SubVal = 
7784           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7785                                     Offset, Context);
7786         Offset += RHS->getZExtValue();
7787         Scale = SubScale;
7788         return SubVal;
7789       }
7790     }
7791   }
7792
7793   // Otherwise, we can't look past this.
7794   Scale = 1;
7795   Offset = 0;
7796   return Val;
7797 }
7798
7799
7800 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7801 /// try to eliminate the cast by moving the type information into the alloc.
7802 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7803                                                    AllocationInst &AI) {
7804   const PointerType *PTy = cast<PointerType>(CI.getType());
7805   
7806   // Remove any uses of AI that are dead.
7807   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7808   
7809   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7810     Instruction *User = cast<Instruction>(*UI++);
7811     if (isInstructionTriviallyDead(User)) {
7812       while (UI != E && *UI == User)
7813         ++UI; // If this instruction uses AI more than once, don't break UI.
7814       
7815       ++NumDeadInst;
7816       DOUT << "IC: DCE: " << *User;
7817       EraseInstFromFunction(*User);
7818     }
7819   }
7820   
7821   // Get the type really allocated and the type casted to.
7822   const Type *AllocElTy = AI.getAllocatedType();
7823   const Type *CastElTy = PTy->getElementType();
7824   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7825
7826   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7827   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7828   if (CastElTyAlign < AllocElTyAlign) return 0;
7829
7830   // If the allocation has multiple uses, only promote it if we are strictly
7831   // increasing the alignment of the resultant allocation.  If we keep it the
7832   // same, we open the door to infinite loops of various kinds.  (A reference
7833   // from a dbg.declare doesn't count as a use for this purpose.)
7834   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7835       CastElTyAlign == AllocElTyAlign) return 0;
7836
7837   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7838   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7839   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7840
7841   // See if we can satisfy the modulus by pulling a scale out of the array
7842   // size argument.
7843   unsigned ArraySizeScale;
7844   int ArrayOffset;
7845   Value *NumElements = // See if the array size is a decomposable linear expr.
7846     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7847                               ArrayOffset, Context);
7848  
7849   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7850   // do the xform.
7851   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7852       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7853
7854   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7855   Value *Amt = 0;
7856   if (Scale == 1) {
7857     Amt = NumElements;
7858   } else {
7859     // If the allocation size is constant, form a constant mul expression
7860     Amt = Context->getConstantInt(Type::Int32Ty, Scale);
7861     if (isa<ConstantInt>(NumElements))
7862       Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
7863                                  cast<ConstantInt>(Amt));
7864     // otherwise multiply the amount and the number of elements
7865     else {
7866       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7867       Amt = InsertNewInstBefore(Tmp, AI);
7868     }
7869   }
7870   
7871   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7872     Value *Off = Context->getConstantInt(Type::Int32Ty, Offset, true);
7873     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7874     Amt = InsertNewInstBefore(Tmp, AI);
7875   }
7876   
7877   AllocationInst *New;
7878   if (isa<MallocInst>(AI))
7879     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7880   else
7881     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7882   InsertNewInstBefore(New, AI);
7883   New->takeName(&AI);
7884   
7885   // If the allocation has one real use plus a dbg.declare, just remove the
7886   // declare.
7887   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7888     EraseInstFromFunction(*DI);
7889   }
7890   // If the allocation has multiple real uses, insert a cast and change all
7891   // things that used it to use the new cast.  This will also hack on CI, but it
7892   // will die soon.
7893   else if (!AI.hasOneUse()) {
7894     AddUsesToWorkList(AI);
7895     // New is the allocation instruction, pointer typed. AI is the original
7896     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7897     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7898     InsertNewInstBefore(NewCast, AI);
7899     AI.replaceAllUsesWith(NewCast);
7900   }
7901   return ReplaceInstUsesWith(CI, New);
7902 }
7903
7904 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7905 /// and return it as type Ty without inserting any new casts and without
7906 /// changing the computed value.  This is used by code that tries to decide
7907 /// whether promoting or shrinking integer operations to wider or smaller types
7908 /// will allow us to eliminate a truncate or extend.
7909 ///
7910 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7911 /// extension operation if Ty is larger.
7912 ///
7913 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7914 /// should return true if trunc(V) can be computed by computing V in the smaller
7915 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7916 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7917 /// efficiently truncated.
7918 ///
7919 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7920 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7921 /// the final result.
7922 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7923                                               unsigned CastOpc,
7924                                               int &NumCastsRemoved){
7925   // We can always evaluate constants in another type.
7926   if (isa<Constant>(V))
7927     return true;
7928   
7929   Instruction *I = dyn_cast<Instruction>(V);
7930   if (!I) return false;
7931   
7932   const Type *OrigTy = V->getType();
7933   
7934   // If this is an extension or truncate, we can often eliminate it.
7935   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7936     // If this is a cast from the destination type, we can trivially eliminate
7937     // it, and this will remove a cast overall.
7938     if (I->getOperand(0)->getType() == Ty) {
7939       // If the first operand is itself a cast, and is eliminable, do not count
7940       // this as an eliminable cast.  We would prefer to eliminate those two
7941       // casts first.
7942       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7943         ++NumCastsRemoved;
7944       return true;
7945     }
7946   }
7947
7948   // We can't extend or shrink something that has multiple uses: doing so would
7949   // require duplicating the instruction in general, which isn't profitable.
7950   if (!I->hasOneUse()) return false;
7951
7952   unsigned Opc = I->getOpcode();
7953   switch (Opc) {
7954   case Instruction::Add:
7955   case Instruction::Sub:
7956   case Instruction::Mul:
7957   case Instruction::And:
7958   case Instruction::Or:
7959   case Instruction::Xor:
7960     // These operators can all arbitrarily be extended or truncated.
7961     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7962                                       NumCastsRemoved) &&
7963            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7964                                       NumCastsRemoved);
7965
7966   case Instruction::UDiv:
7967   case Instruction::URem: {
7968     // UDiv and URem can be truncated if all the truncated bits are zero.
7969     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7970     uint32_t BitWidth = Ty->getScalarSizeInBits();
7971     if (BitWidth < OrigBitWidth) {
7972       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7973       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7974           MaskedValueIsZero(I->getOperand(1), Mask)) {
7975         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7976                                           NumCastsRemoved) &&
7977                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7978                                           NumCastsRemoved);
7979       }
7980     }
7981     break;
7982   }
7983   case Instruction::Shl:
7984     // If we are truncating the result of this SHL, and if it's a shift of a
7985     // constant amount, we can always perform a SHL in a smaller type.
7986     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7987       uint32_t BitWidth = Ty->getScalarSizeInBits();
7988       if (BitWidth < OrigTy->getScalarSizeInBits() &&
7989           CI->getLimitedValue(BitWidth) < BitWidth)
7990         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7991                                           NumCastsRemoved);
7992     }
7993     break;
7994   case Instruction::LShr:
7995     // If this is a truncate of a logical shr, we can truncate it to a smaller
7996     // lshr iff we know that the bits we would otherwise be shifting in are
7997     // already zeros.
7998     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7999       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8000       uint32_t BitWidth = Ty->getScalarSizeInBits();
8001       if (BitWidth < OrigBitWidth &&
8002           MaskedValueIsZero(I->getOperand(0),
8003             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8004           CI->getLimitedValue(BitWidth) < BitWidth) {
8005         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8006                                           NumCastsRemoved);
8007       }
8008     }
8009     break;
8010   case Instruction::ZExt:
8011   case Instruction::SExt:
8012   case Instruction::Trunc:
8013     // If this is the same kind of case as our original (e.g. zext+zext), we
8014     // can safely replace it.  Note that replacing it does not reduce the number
8015     // of casts in the input.
8016     if (Opc == CastOpc)
8017       return true;
8018
8019     // sext (zext ty1), ty2 -> zext ty2
8020     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
8021       return true;
8022     break;
8023   case Instruction::Select: {
8024     SelectInst *SI = cast<SelectInst>(I);
8025     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8026                                       NumCastsRemoved) &&
8027            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8028                                       NumCastsRemoved);
8029   }
8030   case Instruction::PHI: {
8031     // We can change a phi if we can change all operands.
8032     PHINode *PN = cast<PHINode>(I);
8033     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8034       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8035                                       NumCastsRemoved))
8036         return false;
8037     return true;
8038   }
8039   default:
8040     // TODO: Can handle more cases here.
8041     break;
8042   }
8043   
8044   return false;
8045 }
8046
8047 /// EvaluateInDifferentType - Given an expression that 
8048 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8049 /// evaluate the expression.
8050 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
8051                                              bool isSigned) {
8052   if (Constant *C = dyn_cast<Constant>(V))
8053     return Context->getConstantExprIntegerCast(C, Ty,
8054                                                isSigned /*Sext or ZExt*/);
8055
8056   // Otherwise, it must be an instruction.
8057   Instruction *I = cast<Instruction>(V);
8058   Instruction *Res = 0;
8059   unsigned Opc = I->getOpcode();
8060   switch (Opc) {
8061   case Instruction::Add:
8062   case Instruction::Sub:
8063   case Instruction::Mul:
8064   case Instruction::And:
8065   case Instruction::Or:
8066   case Instruction::Xor:
8067   case Instruction::AShr:
8068   case Instruction::LShr:
8069   case Instruction::Shl:
8070   case Instruction::UDiv:
8071   case Instruction::URem: {
8072     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8073     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8074     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8075     break;
8076   }    
8077   case Instruction::Trunc:
8078   case Instruction::ZExt:
8079   case Instruction::SExt:
8080     // If the source type of the cast is the type we're trying for then we can
8081     // just return the source.  There's no need to insert it because it is not
8082     // new.
8083     if (I->getOperand(0)->getType() == Ty)
8084       return I->getOperand(0);
8085     
8086     // Otherwise, must be the same type of cast, so just reinsert a new one.
8087     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8088                            Ty);
8089     break;
8090   case Instruction::Select: {
8091     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8092     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8093     Res = SelectInst::Create(I->getOperand(0), True, False);
8094     break;
8095   }
8096   case Instruction::PHI: {
8097     PHINode *OPN = cast<PHINode>(I);
8098     PHINode *NPN = PHINode::Create(Ty);
8099     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8100       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8101       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8102     }
8103     Res = NPN;
8104     break;
8105   }
8106   default: 
8107     // TODO: Can handle more cases here.
8108     llvm_unreachable("Unreachable!");
8109     break;
8110   }
8111   
8112   Res->takeName(I);
8113   return InsertNewInstBefore(Res, *I);
8114 }
8115
8116 /// @brief Implement the transforms common to all CastInst visitors.
8117 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8118   Value *Src = CI.getOperand(0);
8119
8120   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8121   // eliminate it now.
8122   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8123     if (Instruction::CastOps opc = 
8124         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8125       // The first cast (CSrc) is eliminable so we need to fix up or replace
8126       // the second cast (CI). CSrc will then have a good chance of being dead.
8127       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8128     }
8129   }
8130
8131   // If we are casting a select then fold the cast into the select
8132   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8133     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8134       return NV;
8135
8136   // If we are casting a PHI then fold the cast into the PHI
8137   if (isa<PHINode>(Src))
8138     if (Instruction *NV = FoldOpIntoPhi(CI))
8139       return NV;
8140   
8141   return 0;
8142 }
8143
8144 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8145 /// or not there is a sequence of GEP indices into the type that will land us at
8146 /// the specified offset.  If so, fill them into NewIndices and return the
8147 /// resultant element type, otherwise return null.
8148 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8149                                        SmallVectorImpl<Value*> &NewIndices,
8150                                        const TargetData *TD,
8151                                        LLVMContext *Context) {
8152   if (!Ty->isSized()) return 0;
8153   
8154   // Start with the index over the outer type.  Note that the type size
8155   // might be zero (even if the offset isn't zero) if the indexed type
8156   // is something like [0 x {int, int}]
8157   const Type *IntPtrTy = TD->getIntPtrType();
8158   int64_t FirstIdx = 0;
8159   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8160     FirstIdx = Offset/TySize;
8161     Offset -= FirstIdx*TySize;
8162     
8163     // Handle hosts where % returns negative instead of values [0..TySize).
8164     if (Offset < 0) {
8165       --FirstIdx;
8166       Offset += TySize;
8167       assert(Offset >= 0);
8168     }
8169     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8170   }
8171   
8172   NewIndices.push_back(Context->getConstantInt(IntPtrTy, FirstIdx));
8173     
8174   // Index into the types.  If we fail, set OrigBase to null.
8175   while (Offset) {
8176     // Indexing into tail padding between struct/array elements.
8177     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8178       return 0;
8179     
8180     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8181       const StructLayout *SL = TD->getStructLayout(STy);
8182       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8183              "Offset must stay within the indexed type");
8184       
8185       unsigned Elt = SL->getElementContainingOffset(Offset);
8186       NewIndices.push_back(Context->getConstantInt(Type::Int32Ty, Elt));
8187       
8188       Offset -= SL->getElementOffset(Elt);
8189       Ty = STy->getElementType(Elt);
8190     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8191       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8192       assert(EltSize && "Cannot index into a zero-sized array");
8193       NewIndices.push_back(Context->getConstantInt(IntPtrTy,Offset/EltSize));
8194       Offset %= EltSize;
8195       Ty = AT->getElementType();
8196     } else {
8197       // Otherwise, we can't index into the middle of this atomic type, bail.
8198       return 0;
8199     }
8200   }
8201   
8202   return Ty;
8203 }
8204
8205 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8206 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8207   Value *Src = CI.getOperand(0);
8208   
8209   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8210     // If casting the result of a getelementptr instruction with no offset, turn
8211     // this into a cast of the original pointer!
8212     if (GEP->hasAllZeroIndices()) {
8213       // Changing the cast operand is usually not a good idea but it is safe
8214       // here because the pointer operand is being replaced with another 
8215       // pointer operand so the opcode doesn't need to change.
8216       AddToWorkList(GEP);
8217       CI.setOperand(0, GEP->getOperand(0));
8218       return &CI;
8219     }
8220     
8221     // If the GEP has a single use, and the base pointer is a bitcast, and the
8222     // GEP computes a constant offset, see if we can convert these three
8223     // instructions into fewer.  This typically happens with unions and other
8224     // non-type-safe code.
8225     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8226       if (GEP->hasAllConstantIndices()) {
8227         // We are guaranteed to get a constant from EmitGEPOffset.
8228         ConstantInt *OffsetV =
8229                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8230         int64_t Offset = OffsetV->getSExtValue();
8231         
8232         // Get the base pointer input of the bitcast, and the type it points to.
8233         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8234         const Type *GEPIdxTy =
8235           cast<PointerType>(OrigBase->getType())->getElementType();
8236         SmallVector<Value*, 8> NewIndices;
8237         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8238           // If we were able to index down into an element, create the GEP
8239           // and bitcast the result.  This eliminates one bitcast, potentially
8240           // two.
8241           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
8242                                                         NewIndices.begin(),
8243                                                         NewIndices.end(), "");
8244           InsertNewInstBefore(NGEP, CI);
8245           NGEP->takeName(GEP);
8246           
8247           if (isa<BitCastInst>(CI))
8248             return new BitCastInst(NGEP, CI.getType());
8249           assert(isa<PtrToIntInst>(CI));
8250           return new PtrToIntInst(NGEP, CI.getType());
8251         }
8252       }      
8253     }
8254   }
8255     
8256   return commonCastTransforms(CI);
8257 }
8258
8259 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8260 /// type like i42.  We don't want to introduce operations on random non-legal
8261 /// integer types where they don't already exist in the code.  In the future,
8262 /// we should consider making this based off target-data, so that 32-bit targets
8263 /// won't get i64 operations etc.
8264 static bool isSafeIntegerType(const Type *Ty) {
8265   switch (Ty->getPrimitiveSizeInBits()) {
8266   case 8:
8267   case 16:
8268   case 32:
8269   case 64:
8270     return true;
8271   default: 
8272     return false;
8273   }
8274 }
8275
8276 /// commonIntCastTransforms - This function implements the common transforms
8277 /// for trunc, zext, and sext.
8278 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8279   if (Instruction *Result = commonCastTransforms(CI))
8280     return Result;
8281
8282   Value *Src = CI.getOperand(0);
8283   const Type *SrcTy = Src->getType();
8284   const Type *DestTy = CI.getType();
8285   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8286   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8287
8288   // See if we can simplify any instructions used by the LHS whose sole 
8289   // purpose is to compute bits we don't care about.
8290   if (SimplifyDemandedInstructionBits(CI))
8291     return &CI;
8292
8293   // If the source isn't an instruction or has more than one use then we
8294   // can't do anything more. 
8295   Instruction *SrcI = dyn_cast<Instruction>(Src);
8296   if (!SrcI || !Src->hasOneUse())
8297     return 0;
8298
8299   // Attempt to propagate the cast into the instruction for int->int casts.
8300   int NumCastsRemoved = 0;
8301   // Only do this if the dest type is a simple type, don't convert the
8302   // expression tree to something weird like i93 unless the source is also
8303   // strange.
8304   if ((isSafeIntegerType(DestTy->getScalarType()) ||
8305        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8306       CanEvaluateInDifferentType(SrcI, DestTy,
8307                                  CI.getOpcode(), NumCastsRemoved)) {
8308     // If this cast is a truncate, evaluting in a different type always
8309     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8310     // we need to do an AND to maintain the clear top-part of the computation,
8311     // so we require that the input have eliminated at least one cast.  If this
8312     // is a sign extension, we insert two new casts (to do the extension) so we
8313     // require that two casts have been eliminated.
8314     bool DoXForm = false;
8315     bool JustReplace = false;
8316     switch (CI.getOpcode()) {
8317     default:
8318       // All the others use floating point so we shouldn't actually 
8319       // get here because of the check above.
8320       llvm_unreachable("Unknown cast type");
8321     case Instruction::Trunc:
8322       DoXForm = true;
8323       break;
8324     case Instruction::ZExt: {
8325       DoXForm = NumCastsRemoved >= 1;
8326       if (!DoXForm && 0) {
8327         // If it's unnecessary to issue an AND to clear the high bits, it's
8328         // always profitable to do this xform.
8329         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8330         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8331         if (MaskedValueIsZero(TryRes, Mask))
8332           return ReplaceInstUsesWith(CI, TryRes);
8333         
8334         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8335           if (TryI->use_empty())
8336             EraseInstFromFunction(*TryI);
8337       }
8338       break;
8339     }
8340     case Instruction::SExt: {
8341       DoXForm = NumCastsRemoved >= 2;
8342       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8343         // If we do not have to emit the truncate + sext pair, then it's always
8344         // profitable to do this xform.
8345         //
8346         // It's not safe to eliminate the trunc + sext pair if one of the
8347         // eliminated cast is a truncate. e.g.
8348         // t2 = trunc i32 t1 to i16
8349         // t3 = sext i16 t2 to i32
8350         // !=
8351         // i32 t1
8352         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8353         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8354         if (NumSignBits > (DestBitSize - SrcBitSize))
8355           return ReplaceInstUsesWith(CI, TryRes);
8356         
8357         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8358           if (TryI->use_empty())
8359             EraseInstFromFunction(*TryI);
8360       }
8361       break;
8362     }
8363     }
8364     
8365     if (DoXForm) {
8366       DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8367            << " cast: " << CI;
8368       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8369                                            CI.getOpcode() == Instruction::SExt);
8370       if (JustReplace)
8371         // Just replace this cast with the result.
8372         return ReplaceInstUsesWith(CI, Res);
8373
8374       assert(Res->getType() == DestTy);
8375       switch (CI.getOpcode()) {
8376       default: llvm_unreachable("Unknown cast type!");
8377       case Instruction::Trunc:
8378         // Just replace this cast with the result.
8379         return ReplaceInstUsesWith(CI, Res);
8380       case Instruction::ZExt: {
8381         assert(SrcBitSize < DestBitSize && "Not a zext?");
8382
8383         // If the high bits are already zero, just replace this cast with the
8384         // result.
8385         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8386         if (MaskedValueIsZero(Res, Mask))
8387           return ReplaceInstUsesWith(CI, Res);
8388
8389         // We need to emit an AND to clear the high bits.
8390         Constant *C = Context->getConstantInt(APInt::getLowBitsSet(DestBitSize,
8391                                                             SrcBitSize));
8392         return BinaryOperator::CreateAnd(Res, C);
8393       }
8394       case Instruction::SExt: {
8395         // If the high bits are already filled with sign bit, just replace this
8396         // cast with the result.
8397         unsigned NumSignBits = ComputeNumSignBits(Res);
8398         if (NumSignBits > (DestBitSize - SrcBitSize))
8399           return ReplaceInstUsesWith(CI, Res);
8400
8401         // We need to emit a cast to truncate, then a cast to sext.
8402         return CastInst::Create(Instruction::SExt,
8403             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8404                              CI), DestTy);
8405       }
8406       }
8407     }
8408   }
8409   
8410   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8411   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8412
8413   switch (SrcI->getOpcode()) {
8414   case Instruction::Add:
8415   case Instruction::Mul:
8416   case Instruction::And:
8417   case Instruction::Or:
8418   case Instruction::Xor:
8419     // If we are discarding information, rewrite.
8420     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8421       // Don't insert two casts unless at least one can be eliminated.
8422       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8423           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8424         Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8425         Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8426         return BinaryOperator::Create(
8427             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8428       }
8429     }
8430
8431     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8432     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8433         SrcI->getOpcode() == Instruction::Xor &&
8434         Op1 == Context->getConstantIntTrue() &&
8435         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8436       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8437       return BinaryOperator::CreateXor(New,
8438                                       Context->getConstantInt(CI.getType(), 1));
8439     }
8440     break;
8441
8442   case Instruction::Shl: {
8443     // Canonicalize trunc inside shl, if we can.
8444     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8445     if (CI && DestBitSize < SrcBitSize &&
8446         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8447       Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8448       Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8449       return BinaryOperator::CreateShl(Op0c, Op1c);
8450     }
8451     break;
8452   }
8453   }
8454   return 0;
8455 }
8456
8457 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8458   if (Instruction *Result = commonIntCastTransforms(CI))
8459     return Result;
8460   
8461   Value *Src = CI.getOperand(0);
8462   const Type *Ty = CI.getType();
8463   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8464   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8465
8466   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8467   if (DestBitWidth == 1) {
8468     Constant *One = Context->getConstantInt(Src->getType(), 1);
8469     Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8470     Value *Zero = Context->getNullValue(Src->getType());
8471     return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
8472   }
8473
8474   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8475   ConstantInt *ShAmtV = 0;
8476   Value *ShiftOp = 0;
8477   if (Src->hasOneUse() &&
8478       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
8479     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8480     
8481     // Get a mask for the bits shifting in.
8482     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8483     if (MaskedValueIsZero(ShiftOp, Mask)) {
8484       if (ShAmt >= DestBitWidth)        // All zeros.
8485         return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
8486       
8487       // Okay, we can shrink this.  Truncate the input, then return a new
8488       // shift.
8489       Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8490       Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
8491       return BinaryOperator::CreateLShr(V1, V2);
8492     }
8493   }
8494   
8495   return 0;
8496 }
8497
8498 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8499 /// in order to eliminate the icmp.
8500 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8501                                              bool DoXform) {
8502   // If we are just checking for a icmp eq of a single bit and zext'ing it
8503   // to an integer, then shift the bit to the appropriate place and then
8504   // cast to integer to avoid the comparison.
8505   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8506     const APInt &Op1CV = Op1C->getValue();
8507       
8508     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8509     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8510     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8511         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8512       if (!DoXform) return ICI;
8513
8514       Value *In = ICI->getOperand(0);
8515       Value *Sh = Context->getConstantInt(In->getType(),
8516                                    In->getType()->getScalarSizeInBits()-1);
8517       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8518                                                         In->getName()+".lobit"),
8519                                CI);
8520       if (In->getType() != CI.getType())
8521         In = CastInst::CreateIntegerCast(In, CI.getType(),
8522                                          false/*ZExt*/, "tmp", &CI);
8523
8524       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8525         Constant *One = Context->getConstantInt(In->getType(), 1);
8526         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8527                                                          In->getName()+".not"),
8528                                  CI);
8529       }
8530
8531       return ReplaceInstUsesWith(CI, In);
8532     }
8533       
8534       
8535       
8536     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8537     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8538     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8539     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8540     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8541     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8542     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8543     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8544     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8545         // This only works for EQ and NE
8546         ICI->isEquality()) {
8547       // If Op1C some other power of two, convert:
8548       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8549       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8550       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8551       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8552         
8553       APInt KnownZeroMask(~KnownZero);
8554       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8555         if (!DoXform) return ICI;
8556
8557         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8558         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8559           // (X&4) == 2 --> false
8560           // (X&4) != 2 --> true
8561           Constant *Res = Context->getConstantInt(Type::Int1Ty, isNE);
8562           Res = Context->getConstantExprZExt(Res, CI.getType());
8563           return ReplaceInstUsesWith(CI, Res);
8564         }
8565           
8566         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8567         Value *In = ICI->getOperand(0);
8568         if (ShiftAmt) {
8569           // Perform a logical shr by shiftamt.
8570           // Insert the shift to put the result in the low bit.
8571           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8572                               Context->getConstantInt(In->getType(), ShiftAmt),
8573                                                    In->getName()+".lobit"), CI);
8574         }
8575           
8576         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8577           Constant *One = Context->getConstantInt(In->getType(), 1);
8578           In = BinaryOperator::CreateXor(In, One, "tmp");
8579           InsertNewInstBefore(cast<Instruction>(In), CI);
8580         }
8581           
8582         if (CI.getType() == In->getType())
8583           return ReplaceInstUsesWith(CI, In);
8584         else
8585           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8586       }
8587     }
8588   }
8589
8590   return 0;
8591 }
8592
8593 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8594   // If one of the common conversion will work ..
8595   if (Instruction *Result = commonIntCastTransforms(CI))
8596     return Result;
8597
8598   Value *Src = CI.getOperand(0);
8599
8600   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8601   // types and if the sizes are just right we can convert this into a logical
8602   // 'and' which will be much cheaper than the pair of casts.
8603   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8604     // Get the sizes of the types involved.  We know that the intermediate type
8605     // will be smaller than A or C, but don't know the relation between A and C.
8606     Value *A = CSrc->getOperand(0);
8607     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8608     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8609     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8610     // If we're actually extending zero bits, then if
8611     // SrcSize <  DstSize: zext(a & mask)
8612     // SrcSize == DstSize: a & mask
8613     // SrcSize  > DstSize: trunc(a) & mask
8614     if (SrcSize < DstSize) {
8615       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8616       Constant *AndConst = Context->getConstantInt(A->getType(), AndValue);
8617       Instruction *And =
8618         BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8619       InsertNewInstBefore(And, CI);
8620       return new ZExtInst(And, CI.getType());
8621     } else if (SrcSize == DstSize) {
8622       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8623       return BinaryOperator::CreateAnd(A, Context->getConstantInt(A->getType(),
8624                                                            AndValue));
8625     } else if (SrcSize > DstSize) {
8626       Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8627       InsertNewInstBefore(Trunc, CI);
8628       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8629       return BinaryOperator::CreateAnd(Trunc, 
8630                                        Context->getConstantInt(Trunc->getType(),
8631                                                                AndValue));
8632     }
8633   }
8634
8635   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8636     return transformZExtICmp(ICI, CI);
8637
8638   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8639   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8640     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8641     // of the (zext icmp) will be transformed.
8642     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8643     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8644     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8645         (transformZExtICmp(LHS, CI, false) ||
8646          transformZExtICmp(RHS, CI, false))) {
8647       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8648       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8649       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8650     }
8651   }
8652
8653   // zext(trunc(t) & C) -> (t & zext(C)).
8654   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8655     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8656       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8657         Value *TI0 = TI->getOperand(0);
8658         if (TI0->getType() == CI.getType())
8659           return
8660             BinaryOperator::CreateAnd(TI0,
8661                                 Context->getConstantExprZExt(C, CI.getType()));
8662       }
8663
8664   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8665   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8666     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8667       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8668         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8669             And->getOperand(1) == C)
8670           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8671             Value *TI0 = TI->getOperand(0);
8672             if (TI0->getType() == CI.getType()) {
8673               Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
8674               Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8675               InsertNewInstBefore(NewAnd, *And);
8676               return BinaryOperator::CreateXor(NewAnd, ZC);
8677             }
8678           }
8679
8680   return 0;
8681 }
8682
8683 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8684   if (Instruction *I = commonIntCastTransforms(CI))
8685     return I;
8686   
8687   Value *Src = CI.getOperand(0);
8688   
8689   // Canonicalize sign-extend from i1 to a select.
8690   if (Src->getType() == Type::Int1Ty)
8691     return SelectInst::Create(Src,
8692                               Context->getAllOnesValue(CI.getType()),
8693                               Context->getNullValue(CI.getType()));
8694
8695   // See if the value being truncated is already sign extended.  If so, just
8696   // eliminate the trunc/sext pair.
8697   if (Operator::getOpcode(Src) == Instruction::Trunc) {
8698     Value *Op = cast<User>(Src)->getOperand(0);
8699     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8700     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8701     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8702     unsigned NumSignBits = ComputeNumSignBits(Op);
8703
8704     if (OpBits == DestBits) {
8705       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8706       // bits, it is already ready.
8707       if (NumSignBits > DestBits-MidBits)
8708         return ReplaceInstUsesWith(CI, Op);
8709     } else if (OpBits < DestBits) {
8710       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8711       // bits, just sext from i32.
8712       if (NumSignBits > OpBits-MidBits)
8713         return new SExtInst(Op, CI.getType(), "tmp");
8714     } else {
8715       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8716       // bits, just truncate to i32.
8717       if (NumSignBits > OpBits-MidBits)
8718         return new TruncInst(Op, CI.getType(), "tmp");
8719     }
8720   }
8721
8722   // If the input is a shl/ashr pair of a same constant, then this is a sign
8723   // extension from a smaller value.  If we could trust arbitrary bitwidth
8724   // integers, we could turn this into a truncate to the smaller bit and then
8725   // use a sext for the whole extension.  Since we don't, look deeper and check
8726   // for a truncate.  If the source and dest are the same type, eliminate the
8727   // trunc and extend and just do shifts.  For example, turn:
8728   //   %a = trunc i32 %i to i8
8729   //   %b = shl i8 %a, 6
8730   //   %c = ashr i8 %b, 6
8731   //   %d = sext i8 %c to i32
8732   // into:
8733   //   %a = shl i32 %i, 30
8734   //   %d = ashr i32 %a, 30
8735   Value *A = 0;
8736   ConstantInt *BA = 0, *CA = 0;
8737   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8738                         m_ConstantInt(CA)), *Context) &&
8739       BA == CA && isa<TruncInst>(A)) {
8740     Value *I = cast<TruncInst>(A)->getOperand(0);
8741     if (I->getType() == CI.getType()) {
8742       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8743       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8744       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8745       Constant *ShAmtV = Context->getConstantInt(CI.getType(), ShAmt);
8746       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8747                                                         CI.getName()), CI);
8748       return BinaryOperator::CreateAShr(I, ShAmtV);
8749     }
8750   }
8751   
8752   return 0;
8753 }
8754
8755 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8756 /// in the specified FP type without changing its value.
8757 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8758                               LLVMContext *Context) {
8759   bool losesInfo;
8760   APFloat F = CFP->getValueAPF();
8761   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8762   if (!losesInfo)
8763     return Context->getConstantFP(F);
8764   return 0;
8765 }
8766
8767 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8768 /// through it until we get the source value.
8769 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8770   if (Instruction *I = dyn_cast<Instruction>(V))
8771     if (I->getOpcode() == Instruction::FPExt)
8772       return LookThroughFPExtensions(I->getOperand(0), Context);
8773   
8774   // If this value is a constant, return the constant in the smallest FP type
8775   // that can accurately represent it.  This allows us to turn
8776   // (float)((double)X+2.0) into x+2.0f.
8777   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8778     if (CFP->getType() == Type::PPC_FP128Ty)
8779       return V;  // No constant folding of this.
8780     // See if the value can be truncated to float and then reextended.
8781     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8782       return V;
8783     if (CFP->getType() == Type::DoubleTy)
8784       return V;  // Won't shrink.
8785     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8786       return V;
8787     // Don't try to shrink to various long double types.
8788   }
8789   
8790   return V;
8791 }
8792
8793 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8794   if (Instruction *I = commonCastTransforms(CI))
8795     return I;
8796   
8797   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8798   // smaller than the destination type, we can eliminate the truncate by doing
8799   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8800   // many builtins (sqrt, etc).
8801   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8802   if (OpI && OpI->hasOneUse()) {
8803     switch (OpI->getOpcode()) {
8804     default: break;
8805     case Instruction::FAdd:
8806     case Instruction::FSub:
8807     case Instruction::FMul:
8808     case Instruction::FDiv:
8809     case Instruction::FRem:
8810       const Type *SrcTy = OpI->getType();
8811       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8812       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8813       if (LHSTrunc->getType() != SrcTy && 
8814           RHSTrunc->getType() != SrcTy) {
8815         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8816         // If the source types were both smaller than the destination type of
8817         // the cast, do this xform.
8818         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8819             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8820           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8821                                       CI.getType(), CI);
8822           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8823                                       CI.getType(), CI);
8824           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8825         }
8826       }
8827       break;  
8828     }
8829   }
8830   return 0;
8831 }
8832
8833 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8834   return commonCastTransforms(CI);
8835 }
8836
8837 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8838   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8839   if (OpI == 0)
8840     return commonCastTransforms(FI);
8841
8842   // fptoui(uitofp(X)) --> X
8843   // fptoui(sitofp(X)) --> X
8844   // This is safe if the intermediate type has enough bits in its mantissa to
8845   // accurately represent all values of X.  For example, do not do this with
8846   // i64->float->i64.  This is also safe for sitofp case, because any negative
8847   // 'X' value would cause an undefined result for the fptoui. 
8848   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8849       OpI->getOperand(0)->getType() == FI.getType() &&
8850       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8851                     OpI->getType()->getFPMantissaWidth())
8852     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8853
8854   return commonCastTransforms(FI);
8855 }
8856
8857 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8858   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8859   if (OpI == 0)
8860     return commonCastTransforms(FI);
8861   
8862   // fptosi(sitofp(X)) --> X
8863   // fptosi(uitofp(X)) --> X
8864   // This is safe if the intermediate type has enough bits in its mantissa to
8865   // accurately represent all values of X.  For example, do not do this with
8866   // i64->float->i64.  This is also safe for sitofp case, because any negative
8867   // 'X' value would cause an undefined result for the fptoui. 
8868   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8869       OpI->getOperand(0)->getType() == FI.getType() &&
8870       (int)FI.getType()->getScalarSizeInBits() <=
8871                     OpI->getType()->getFPMantissaWidth())
8872     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8873   
8874   return commonCastTransforms(FI);
8875 }
8876
8877 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8878   return commonCastTransforms(CI);
8879 }
8880
8881 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8882   return commonCastTransforms(CI);
8883 }
8884
8885 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8886   // If the destination integer type is smaller than the intptr_t type for
8887   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8888   // trunc to be exposed to other transforms.  Don't do this for extending
8889   // ptrtoint's, because we don't know if the target sign or zero extends its
8890   // pointers.
8891   if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8892     Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8893                                                     TD->getIntPtrType(),
8894                                                     "tmp"), CI);
8895     return new TruncInst(P, CI.getType());
8896   }
8897   
8898   return commonPointerCastTransforms(CI);
8899 }
8900
8901 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8902   // If the source integer type is larger than the intptr_t type for
8903   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8904   // allows the trunc to be exposed to other transforms.  Don't do this for
8905   // extending inttoptr's, because we don't know if the target sign or zero
8906   // extends to pointers.
8907   if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
8908       TD->getPointerSizeInBits()) {
8909     Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8910                                                  TD->getIntPtrType(),
8911                                                  "tmp"), CI);
8912     return new IntToPtrInst(P, CI.getType());
8913   }
8914   
8915   if (Instruction *I = commonCastTransforms(CI))
8916     return I;
8917   
8918   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8919   if (!DestPointee->isSized()) return 0;
8920
8921   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8922   ConstantInt *Cst;
8923   Value *X;
8924   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8925                                     m_ConstantInt(Cst)), *Context)) {
8926     // If the source and destination operands have the same type, see if this
8927     // is a single-index GEP.
8928     if (X->getType() == CI.getType()) {
8929       // Get the size of the pointee type.
8930       uint64_t Size = TD->getTypeAllocSize(DestPointee);
8931
8932       // Convert the constant to intptr type.
8933       APInt Offset = Cst->getValue();
8934       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8935
8936       // If Offset is evenly divisible by Size, we can do this xform.
8937       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8938         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8939         GetElementPtrInst *GEP =
8940           GetElementPtrInst::Create(X, Context->getConstantInt(Offset));
8941         // A gep synthesized from inttoptr+add+ptrtoint must be assumed to
8942         // potentially overflow, in the absense of further analysis.
8943         cast<GEPOperator>(GEP)->setHasNoPointerOverflow(false);
8944         return GEP;
8945       }
8946     }
8947     // TODO: Could handle other cases, e.g. where add is indexing into field of
8948     // struct etc.
8949   } else if (CI.getOperand(0)->hasOneUse() &&
8950              match(CI.getOperand(0), m_Add(m_Value(X),
8951                    m_ConstantInt(Cst)), *Context)) {
8952     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8953     // "inttoptr+GEP" instead of "add+intptr".
8954     
8955     // Get the size of the pointee type.
8956     uint64_t Size = TD->getTypeAllocSize(DestPointee);
8957     
8958     // Convert the constant to intptr type.
8959     APInt Offset = Cst->getValue();
8960     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8961     
8962     // If Offset is evenly divisible by Size, we can do this xform.
8963     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8964       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8965       
8966       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8967                                                             "tmp"), CI);
8968       GetElementPtrInst *GEP =
8969         GetElementPtrInst::Create(P, Context->getConstantInt(Offset), "tmp");
8970       // A gep synthesized from inttoptr+add+ptrtoint must be assumed to
8971       // potentially overflow, in the absense of further analysis.
8972       cast<GEPOperator>(GEP)->setHasNoPointerOverflow(false);
8973       return GEP;
8974     }
8975   }
8976   return 0;
8977 }
8978
8979 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8980   // If the operands are integer typed then apply the integer transforms,
8981   // otherwise just apply the common ones.
8982   Value *Src = CI.getOperand(0);
8983   const Type *SrcTy = Src->getType();
8984   const Type *DestTy = CI.getType();
8985
8986   if (isa<PointerType>(SrcTy)) {
8987     if (Instruction *I = commonPointerCastTransforms(CI))
8988       return I;
8989   } else {
8990     if (Instruction *Result = commonCastTransforms(CI))
8991       return Result;
8992   }
8993
8994
8995   // Get rid of casts from one type to the same type. These are useless and can
8996   // be replaced by the operand.
8997   if (DestTy == Src->getType())
8998     return ReplaceInstUsesWith(CI, Src);
8999
9000   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
9001     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
9002     const Type *DstElTy = DstPTy->getElementType();
9003     const Type *SrcElTy = SrcPTy->getElementType();
9004     
9005     // If the address spaces don't match, don't eliminate the bitcast, which is
9006     // required for changing types.
9007     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9008       return 0;
9009     
9010     // If we are casting a malloc or alloca to a pointer to a type of the same
9011     // size, rewrite the allocation instruction to allocate the "right" type.
9012     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
9013       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9014         return V;
9015     
9016     // If the source and destination are pointers, and this cast is equivalent
9017     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
9018     // This can enhance SROA and other transforms that want type-safe pointers.
9019     Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
9020     unsigned NumZeros = 0;
9021     while (SrcElTy != DstElTy && 
9022            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9023            SrcElTy->getNumContainedTypes() /* not "{}" */) {
9024       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9025       ++NumZeros;
9026     }
9027
9028     // If we found a path from the src to dest, create the getelementptr now.
9029     if (SrcElTy == DstElTy) {
9030       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
9031       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
9032                                        ((Instruction*) NULL));
9033     }
9034   }
9035
9036   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9037     if (DestVTy->getNumElements() == 1) {
9038       if (!isa<VectorType>(SrcTy)) {
9039         Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
9040                                        DestVTy->getElementType(), CI);
9041         return InsertElementInst::Create(Context->getUndef(DestTy), Elem,
9042                                          Context->getNullValue(Type::Int32Ty));
9043       }
9044       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9045     }
9046   }
9047
9048   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9049     if (SrcVTy->getNumElements() == 1) {
9050       if (!isa<VectorType>(DestTy)) {
9051         Instruction *Elem =
9052             new ExtractElementInst(Src, Context->getNullValue(Type::Int32Ty));
9053         InsertNewInstBefore(Elem, CI);
9054         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9055       }
9056     }
9057   }
9058
9059   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9060     if (SVI->hasOneUse()) {
9061       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
9062       // a bitconvert to a vector with the same # elts.
9063       if (isa<VectorType>(DestTy) && 
9064           cast<VectorType>(DestTy)->getNumElements() ==
9065                 SVI->getType()->getNumElements() &&
9066           SVI->getType()->getNumElements() ==
9067             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9068         CastInst *Tmp;
9069         // If either of the operands is a cast from CI.getType(), then
9070         // evaluating the shuffle in the casted destination's type will allow
9071         // us to eliminate at least one cast.
9072         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
9073              Tmp->getOperand(0)->getType() == DestTy) ||
9074             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
9075              Tmp->getOperand(0)->getType() == DestTy)) {
9076           Value *LHS = InsertCastBefore(Instruction::BitCast,
9077                                         SVI->getOperand(0), DestTy, CI);
9078           Value *RHS = InsertCastBefore(Instruction::BitCast,
9079                                         SVI->getOperand(1), DestTy, CI);
9080           // Return a new shuffle vector.  Use the same element ID's, as we
9081           // know the vector types match #elts.
9082           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9083         }
9084       }
9085     }
9086   }
9087   return 0;
9088 }
9089
9090 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9091 ///   %C = or %A, %B
9092 ///   %D = select %cond, %C, %A
9093 /// into:
9094 ///   %C = select %cond, %B, 0
9095 ///   %D = or %A, %C
9096 ///
9097 /// Assuming that the specified instruction is an operand to the select, return
9098 /// a bitmask indicating which operands of this instruction are foldable if they
9099 /// equal the other incoming value of the select.
9100 ///
9101 static unsigned GetSelectFoldableOperands(Instruction *I) {
9102   switch (I->getOpcode()) {
9103   case Instruction::Add:
9104   case Instruction::Mul:
9105   case Instruction::And:
9106   case Instruction::Or:
9107   case Instruction::Xor:
9108     return 3;              // Can fold through either operand.
9109   case Instruction::Sub:   // Can only fold on the amount subtracted.
9110   case Instruction::Shl:   // Can only fold on the shift amount.
9111   case Instruction::LShr:
9112   case Instruction::AShr:
9113     return 1;
9114   default:
9115     return 0;              // Cannot fold
9116   }
9117 }
9118
9119 /// GetSelectFoldableConstant - For the same transformation as the previous
9120 /// function, return the identity constant that goes into the select.
9121 static Constant *GetSelectFoldableConstant(Instruction *I,
9122                                            LLVMContext *Context) {
9123   switch (I->getOpcode()) {
9124   default: llvm_unreachable("This cannot happen!");
9125   case Instruction::Add:
9126   case Instruction::Sub:
9127   case Instruction::Or:
9128   case Instruction::Xor:
9129   case Instruction::Shl:
9130   case Instruction::LShr:
9131   case Instruction::AShr:
9132     return Context->getNullValue(I->getType());
9133   case Instruction::And:
9134     return Context->getAllOnesValue(I->getType());
9135   case Instruction::Mul:
9136     return Context->getConstantInt(I->getType(), 1);
9137   }
9138 }
9139
9140 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9141 /// have the same opcode and only one use each.  Try to simplify this.
9142 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9143                                           Instruction *FI) {
9144   if (TI->getNumOperands() == 1) {
9145     // If this is a non-volatile load or a cast from the same type,
9146     // merge.
9147     if (TI->isCast()) {
9148       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9149         return 0;
9150     } else {
9151       return 0;  // unknown unary op.
9152     }
9153
9154     // Fold this by inserting a select from the input values.
9155     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9156                                            FI->getOperand(0), SI.getName()+".v");
9157     InsertNewInstBefore(NewSI, SI);
9158     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9159                             TI->getType());
9160   }
9161
9162   // Only handle binary operators here.
9163   if (!isa<BinaryOperator>(TI))
9164     return 0;
9165
9166   // Figure out if the operations have any operands in common.
9167   Value *MatchOp, *OtherOpT, *OtherOpF;
9168   bool MatchIsOpZero;
9169   if (TI->getOperand(0) == FI->getOperand(0)) {
9170     MatchOp  = TI->getOperand(0);
9171     OtherOpT = TI->getOperand(1);
9172     OtherOpF = FI->getOperand(1);
9173     MatchIsOpZero = true;
9174   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9175     MatchOp  = TI->getOperand(1);
9176     OtherOpT = TI->getOperand(0);
9177     OtherOpF = FI->getOperand(0);
9178     MatchIsOpZero = false;
9179   } else if (!TI->isCommutative()) {
9180     return 0;
9181   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9182     MatchOp  = TI->getOperand(0);
9183     OtherOpT = TI->getOperand(1);
9184     OtherOpF = FI->getOperand(0);
9185     MatchIsOpZero = true;
9186   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9187     MatchOp  = TI->getOperand(1);
9188     OtherOpT = TI->getOperand(0);
9189     OtherOpF = FI->getOperand(1);
9190     MatchIsOpZero = true;
9191   } else {
9192     return 0;
9193   }
9194
9195   // If we reach here, they do have operations in common.
9196   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9197                                          OtherOpF, SI.getName()+".v");
9198   InsertNewInstBefore(NewSI, SI);
9199
9200   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9201     if (MatchIsOpZero)
9202       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9203     else
9204       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9205   }
9206   llvm_unreachable("Shouldn't get here");
9207   return 0;
9208 }
9209
9210 static bool isSelect01(Constant *C1, Constant *C2) {
9211   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9212   if (!C1I)
9213     return false;
9214   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9215   if (!C2I)
9216     return false;
9217   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9218 }
9219
9220 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9221 /// facilitate further optimization.
9222 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9223                                             Value *FalseVal) {
9224   // See the comment above GetSelectFoldableOperands for a description of the
9225   // transformation we are doing here.
9226   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9227     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9228         !isa<Constant>(FalseVal)) {
9229       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9230         unsigned OpToFold = 0;
9231         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9232           OpToFold = 1;
9233         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9234           OpToFold = 2;
9235         }
9236
9237         if (OpToFold) {
9238           Constant *C = GetSelectFoldableConstant(TVI, Context);
9239           Value *OOp = TVI->getOperand(2-OpToFold);
9240           // Avoid creating select between 2 constants unless it's selecting
9241           // between 0 and 1.
9242           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9243             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9244             InsertNewInstBefore(NewSel, SI);
9245             NewSel->takeName(TVI);
9246             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9247               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9248             llvm_unreachable("Unknown instruction!!");
9249           }
9250         }
9251       }
9252     }
9253   }
9254
9255   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9256     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9257         !isa<Constant>(TrueVal)) {
9258       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9259         unsigned OpToFold = 0;
9260         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9261           OpToFold = 1;
9262         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9263           OpToFold = 2;
9264         }
9265
9266         if (OpToFold) {
9267           Constant *C = GetSelectFoldableConstant(FVI, Context);
9268           Value *OOp = FVI->getOperand(2-OpToFold);
9269           // Avoid creating select between 2 constants unless it's selecting
9270           // between 0 and 1.
9271           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9272             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9273             InsertNewInstBefore(NewSel, SI);
9274             NewSel->takeName(FVI);
9275             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9276               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9277             llvm_unreachable("Unknown instruction!!");
9278           }
9279         }
9280       }
9281     }
9282   }
9283
9284   return 0;
9285 }
9286
9287 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9288 /// ICmpInst as its first operand.
9289 ///
9290 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9291                                                    ICmpInst *ICI) {
9292   bool Changed = false;
9293   ICmpInst::Predicate Pred = ICI->getPredicate();
9294   Value *CmpLHS = ICI->getOperand(0);
9295   Value *CmpRHS = ICI->getOperand(1);
9296   Value *TrueVal = SI.getTrueValue();
9297   Value *FalseVal = SI.getFalseValue();
9298
9299   // Check cases where the comparison is with a constant that
9300   // can be adjusted to fit the min/max idiom. We may edit ICI in
9301   // place here, so make sure the select is the only user.
9302   if (ICI->hasOneUse())
9303     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9304       switch (Pred) {
9305       default: break;
9306       case ICmpInst::ICMP_ULT:
9307       case ICmpInst::ICMP_SLT: {
9308         // X < MIN ? T : F  -->  F
9309         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9310           return ReplaceInstUsesWith(SI, FalseVal);
9311         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9312         Constant *AdjustedRHS = SubOne(CI, Context);
9313         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9314             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9315           Pred = ICmpInst::getSwappedPredicate(Pred);
9316           CmpRHS = AdjustedRHS;
9317           std::swap(FalseVal, TrueVal);
9318           ICI->setPredicate(Pred);
9319           ICI->setOperand(1, CmpRHS);
9320           SI.setOperand(1, TrueVal);
9321           SI.setOperand(2, FalseVal);
9322           Changed = true;
9323         }
9324         break;
9325       }
9326       case ICmpInst::ICMP_UGT:
9327       case ICmpInst::ICMP_SGT: {
9328         // X > MAX ? T : F  -->  F
9329         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9330           return ReplaceInstUsesWith(SI, FalseVal);
9331         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9332         Constant *AdjustedRHS = AddOne(CI, Context);
9333         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9334             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9335           Pred = ICmpInst::getSwappedPredicate(Pred);
9336           CmpRHS = AdjustedRHS;
9337           std::swap(FalseVal, TrueVal);
9338           ICI->setPredicate(Pred);
9339           ICI->setOperand(1, CmpRHS);
9340           SI.setOperand(1, TrueVal);
9341           SI.setOperand(2, FalseVal);
9342           Changed = true;
9343         }
9344         break;
9345       }
9346       }
9347
9348       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9349       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9350       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9351       if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9352           match(FalseVal, m_ConstantInt<0>(), *Context))
9353         Pred = ICI->getPredicate();
9354       else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9355                match(FalseVal, m_ConstantInt<-1>(), *Context))
9356         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9357       
9358       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9359         // If we are just checking for a icmp eq of a single bit and zext'ing it
9360         // to an integer, then shift the bit to the appropriate place and then
9361         // cast to integer to avoid the comparison.
9362         const APInt &Op1CV = CI->getValue();
9363     
9364         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9365         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9366         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9367             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9368           Value *In = ICI->getOperand(0);
9369           Value *Sh = Context->getConstantInt(In->getType(),
9370                                        In->getType()->getScalarSizeInBits()-1);
9371           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9372                                                           In->getName()+".lobit"),
9373                                    *ICI);
9374           if (In->getType() != SI.getType())
9375             In = CastInst::CreateIntegerCast(In, SI.getType(),
9376                                              true/*SExt*/, "tmp", ICI);
9377     
9378           if (Pred == ICmpInst::ICMP_SGT)
9379             In = InsertNewInstBefore(BinaryOperator::CreateNot(*Context, In,
9380                                        In->getName()+".not"), *ICI);
9381     
9382           return ReplaceInstUsesWith(SI, In);
9383         }
9384       }
9385     }
9386
9387   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9388     // Transform (X == Y) ? X : Y  -> Y
9389     if (Pred == ICmpInst::ICMP_EQ)
9390       return ReplaceInstUsesWith(SI, FalseVal);
9391     // Transform (X != Y) ? X : Y  -> X
9392     if (Pred == ICmpInst::ICMP_NE)
9393       return ReplaceInstUsesWith(SI, TrueVal);
9394     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9395
9396   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9397     // Transform (X == Y) ? Y : X  -> X
9398     if (Pred == ICmpInst::ICMP_EQ)
9399       return ReplaceInstUsesWith(SI, FalseVal);
9400     // Transform (X != Y) ? Y : X  -> Y
9401     if (Pred == ICmpInst::ICMP_NE)
9402       return ReplaceInstUsesWith(SI, TrueVal);
9403     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9404   }
9405
9406   /// NOTE: if we wanted to, this is where to detect integer ABS
9407
9408   return Changed ? &SI : 0;
9409 }
9410
9411 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9412   Value *CondVal = SI.getCondition();
9413   Value *TrueVal = SI.getTrueValue();
9414   Value *FalseVal = SI.getFalseValue();
9415
9416   // select true, X, Y  -> X
9417   // select false, X, Y -> Y
9418   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9419     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9420
9421   // select C, X, X -> X
9422   if (TrueVal == FalseVal)
9423     return ReplaceInstUsesWith(SI, TrueVal);
9424
9425   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9426     return ReplaceInstUsesWith(SI, FalseVal);
9427   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9428     return ReplaceInstUsesWith(SI, TrueVal);
9429   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9430     if (isa<Constant>(TrueVal))
9431       return ReplaceInstUsesWith(SI, TrueVal);
9432     else
9433       return ReplaceInstUsesWith(SI, FalseVal);
9434   }
9435
9436   if (SI.getType() == Type::Int1Ty) {
9437     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9438       if (C->getZExtValue()) {
9439         // Change: A = select B, true, C --> A = or B, C
9440         return BinaryOperator::CreateOr(CondVal, FalseVal);
9441       } else {
9442         // Change: A = select B, false, C --> A = and !B, C
9443         Value *NotCond =
9444           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9445                                              "not."+CondVal->getName()), SI);
9446         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9447       }
9448     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9449       if (C->getZExtValue() == false) {
9450         // Change: A = select B, C, false --> A = and B, C
9451         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9452       } else {
9453         // Change: A = select B, C, true --> A = or !B, C
9454         Value *NotCond =
9455           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9456                                              "not."+CondVal->getName()), SI);
9457         return BinaryOperator::CreateOr(NotCond, TrueVal);
9458       }
9459     }
9460     
9461     // select a, b, a  -> a&b
9462     // select a, a, b  -> a|b
9463     if (CondVal == TrueVal)
9464       return BinaryOperator::CreateOr(CondVal, FalseVal);
9465     else if (CondVal == FalseVal)
9466       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9467   }
9468
9469   // Selecting between two integer constants?
9470   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9471     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9472       // select C, 1, 0 -> zext C to int
9473       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9474         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9475       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9476         // select C, 0, 1 -> zext !C to int
9477         Value *NotCond =
9478           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9479                                                "not."+CondVal->getName()), SI);
9480         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9481       }
9482
9483       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9484         // If one of the constants is zero (we know they can't both be) and we
9485         // have an icmp instruction with zero, and we have an 'and' with the
9486         // non-constant value, eliminate this whole mess.  This corresponds to
9487         // cases like this: ((X & 27) ? 27 : 0)
9488         if (TrueValC->isZero() || FalseValC->isZero())
9489           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9490               cast<Constant>(IC->getOperand(1))->isNullValue())
9491             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9492               if (ICA->getOpcode() == Instruction::And &&
9493                   isa<ConstantInt>(ICA->getOperand(1)) &&
9494                   (ICA->getOperand(1) == TrueValC ||
9495                    ICA->getOperand(1) == FalseValC) &&
9496                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9497                 // Okay, now we know that everything is set up, we just don't
9498                 // know whether we have a icmp_ne or icmp_eq and whether the 
9499                 // true or false val is the zero.
9500                 bool ShouldNotVal = !TrueValC->isZero();
9501                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9502                 Value *V = ICA;
9503                 if (ShouldNotVal)
9504                   V = InsertNewInstBefore(BinaryOperator::Create(
9505                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9506                 return ReplaceInstUsesWith(SI, V);
9507               }
9508       }
9509     }
9510
9511   // See if we are selecting two values based on a comparison of the two values.
9512   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9513     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9514       // Transform (X == Y) ? X : Y  -> Y
9515       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9516         // This is not safe in general for floating point:  
9517         // consider X== -0, Y== +0.
9518         // It becomes safe if either operand is a nonzero constant.
9519         ConstantFP *CFPt, *CFPf;
9520         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9521               !CFPt->getValueAPF().isZero()) ||
9522             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9523              !CFPf->getValueAPF().isZero()))
9524         return ReplaceInstUsesWith(SI, FalseVal);
9525       }
9526       // Transform (X != Y) ? X : Y  -> X
9527       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9528         return ReplaceInstUsesWith(SI, TrueVal);
9529       // NOTE: if we wanted to, this is where to detect MIN/MAX
9530
9531     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9532       // Transform (X == Y) ? Y : X  -> X
9533       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9534         // This is not safe in general for floating point:  
9535         // consider X== -0, Y== +0.
9536         // It becomes safe if either operand is a nonzero constant.
9537         ConstantFP *CFPt, *CFPf;
9538         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9539               !CFPt->getValueAPF().isZero()) ||
9540             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9541              !CFPf->getValueAPF().isZero()))
9542           return ReplaceInstUsesWith(SI, FalseVal);
9543       }
9544       // Transform (X != Y) ? Y : X  -> Y
9545       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9546         return ReplaceInstUsesWith(SI, TrueVal);
9547       // NOTE: if we wanted to, this is where to detect MIN/MAX
9548     }
9549     // NOTE: if we wanted to, this is where to detect ABS
9550   }
9551
9552   // See if we are selecting two values based on a comparison of the two values.
9553   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9554     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9555       return Result;
9556
9557   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9558     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9559       if (TI->hasOneUse() && FI->hasOneUse()) {
9560         Instruction *AddOp = 0, *SubOp = 0;
9561
9562         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9563         if (TI->getOpcode() == FI->getOpcode())
9564           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9565             return IV;
9566
9567         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9568         // even legal for FP.
9569         if ((TI->getOpcode() == Instruction::Sub &&
9570              FI->getOpcode() == Instruction::Add) ||
9571             (TI->getOpcode() == Instruction::FSub &&
9572              FI->getOpcode() == Instruction::FAdd)) {
9573           AddOp = FI; SubOp = TI;
9574         } else if ((FI->getOpcode() == Instruction::Sub &&
9575                     TI->getOpcode() == Instruction::Add) ||
9576                    (FI->getOpcode() == Instruction::FSub &&
9577                     TI->getOpcode() == Instruction::FAdd)) {
9578           AddOp = TI; SubOp = FI;
9579         }
9580
9581         if (AddOp) {
9582           Value *OtherAddOp = 0;
9583           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9584             OtherAddOp = AddOp->getOperand(1);
9585           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9586             OtherAddOp = AddOp->getOperand(0);
9587           }
9588
9589           if (OtherAddOp) {
9590             // So at this point we know we have (Y -> OtherAddOp):
9591             //        select C, (add X, Y), (sub X, Z)
9592             Value *NegVal;  // Compute -Z
9593             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9594               NegVal = Context->getConstantExprNeg(C);
9595             } else {
9596               NegVal = InsertNewInstBefore(
9597                     BinaryOperator::CreateNeg(*Context, SubOp->getOperand(1),
9598                                               "tmp"), SI);
9599             }
9600
9601             Value *NewTrueOp = OtherAddOp;
9602             Value *NewFalseOp = NegVal;
9603             if (AddOp != TI)
9604               std::swap(NewTrueOp, NewFalseOp);
9605             Instruction *NewSel =
9606               SelectInst::Create(CondVal, NewTrueOp,
9607                                  NewFalseOp, SI.getName() + ".p");
9608
9609             NewSel = InsertNewInstBefore(NewSel, SI);
9610             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9611           }
9612         }
9613       }
9614
9615   // See if we can fold the select into one of our operands.
9616   if (SI.getType()->isInteger()) {
9617     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9618     if (FoldI)
9619       return FoldI;
9620   }
9621
9622   if (BinaryOperator::isNot(CondVal)) {
9623     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9624     SI.setOperand(1, FalseVal);
9625     SI.setOperand(2, TrueVal);
9626     return &SI;
9627   }
9628
9629   return 0;
9630 }
9631
9632 /// EnforceKnownAlignment - If the specified pointer points to an object that
9633 /// we control, modify the object's alignment to PrefAlign. This isn't
9634 /// often possible though. If alignment is important, a more reliable approach
9635 /// is to simply align all global variables and allocation instructions to
9636 /// their preferred alignment from the beginning.
9637 ///
9638 static unsigned EnforceKnownAlignment(Value *V,
9639                                       unsigned Align, unsigned PrefAlign) {
9640
9641   User *U = dyn_cast<User>(V);
9642   if (!U) return Align;
9643
9644   switch (Operator::getOpcode(U)) {
9645   default: break;
9646   case Instruction::BitCast:
9647     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9648   case Instruction::GetElementPtr: {
9649     // If all indexes are zero, it is just the alignment of the base pointer.
9650     bool AllZeroOperands = true;
9651     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9652       if (!isa<Constant>(*i) ||
9653           !cast<Constant>(*i)->isNullValue()) {
9654         AllZeroOperands = false;
9655         break;
9656       }
9657
9658     if (AllZeroOperands) {
9659       // Treat this like a bitcast.
9660       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9661     }
9662     break;
9663   }
9664   }
9665
9666   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9667     // If there is a large requested alignment and we can, bump up the alignment
9668     // of the global.
9669     if (!GV->isDeclaration()) {
9670       if (GV->getAlignment() >= PrefAlign)
9671         Align = GV->getAlignment();
9672       else {
9673         GV->setAlignment(PrefAlign);
9674         Align = PrefAlign;
9675       }
9676     }
9677   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9678     // If there is a requested alignment and if this is an alloca, round up.  We
9679     // don't do this for malloc, because some systems can't respect the request.
9680     if (isa<AllocaInst>(AI)) {
9681       if (AI->getAlignment() >= PrefAlign)
9682         Align = AI->getAlignment();
9683       else {
9684         AI->setAlignment(PrefAlign);
9685         Align = PrefAlign;
9686       }
9687     }
9688   }
9689
9690   return Align;
9691 }
9692
9693 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9694 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9695 /// and it is more than the alignment of the ultimate object, see if we can
9696 /// increase the alignment of the ultimate object, making this check succeed.
9697 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9698                                                   unsigned PrefAlign) {
9699   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9700                       sizeof(PrefAlign) * CHAR_BIT;
9701   APInt Mask = APInt::getAllOnesValue(BitWidth);
9702   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9703   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9704   unsigned TrailZ = KnownZero.countTrailingOnes();
9705   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9706
9707   if (PrefAlign > Align)
9708     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9709   
9710     // We don't need to make any adjustment.
9711   return Align;
9712 }
9713
9714 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9715   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9716   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9717   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9718   unsigned CopyAlign = MI->getAlignment();
9719
9720   if (CopyAlign < MinAlign) {
9721     MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(), 
9722                                              MinAlign, false));
9723     return MI;
9724   }
9725   
9726   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9727   // load/store.
9728   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9729   if (MemOpLength == 0) return 0;
9730   
9731   // Source and destination pointer types are always "i8*" for intrinsic.  See
9732   // if the size is something we can handle with a single primitive load/store.
9733   // A single load+store correctly handles overlapping memory in the memmove
9734   // case.
9735   unsigned Size = MemOpLength->getZExtValue();
9736   if (Size == 0) return MI;  // Delete this mem transfer.
9737   
9738   if (Size > 8 || (Size&(Size-1)))
9739     return 0;  // If not 1/2/4/8 bytes, exit.
9740   
9741   // Use an integer load+store unless we can find something better.
9742   Type *NewPtrTy =
9743                 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
9744   
9745   // Memcpy forces the use of i8* for the source and destination.  That means
9746   // that if you're using memcpy to move one double around, you'll get a cast
9747   // from double* to i8*.  We'd much rather use a double load+store rather than
9748   // an i64 load+store, here because this improves the odds that the source or
9749   // dest address will be promotable.  See if we can find a better type than the
9750   // integer datatype.
9751   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9752     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9753     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9754       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9755       // down through these levels if so.
9756       while (!SrcETy->isSingleValueType()) {
9757         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9758           if (STy->getNumElements() == 1)
9759             SrcETy = STy->getElementType(0);
9760           else
9761             break;
9762         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9763           if (ATy->getNumElements() == 1)
9764             SrcETy = ATy->getElementType();
9765           else
9766             break;
9767         } else
9768           break;
9769       }
9770       
9771       if (SrcETy->isSingleValueType())
9772         NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
9773     }
9774   }
9775   
9776   
9777   // If the memcpy/memmove provides better alignment info than we can
9778   // infer, use it.
9779   SrcAlign = std::max(SrcAlign, CopyAlign);
9780   DstAlign = std::max(DstAlign, CopyAlign);
9781   
9782   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9783   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9784   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9785   InsertNewInstBefore(L, *MI);
9786   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9787
9788   // Set the size of the copy to 0, it will be deleted on the next iteration.
9789   MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
9790   return MI;
9791 }
9792
9793 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9794   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9795   if (MI->getAlignment() < Alignment) {
9796     MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9797                                              Alignment, false));
9798     return MI;
9799   }
9800   
9801   // Extract the length and alignment and fill if they are constant.
9802   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9803   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9804   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9805     return 0;
9806   uint64_t Len = LenC->getZExtValue();
9807   Alignment = MI->getAlignment();
9808   
9809   // If the length is zero, this is a no-op
9810   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9811   
9812   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9813   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9814     const Type *ITy = Context->getIntegerType(Len*8);  // n=1 -> i8.
9815     
9816     Value *Dest = MI->getDest();
9817     Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
9818
9819     // Alignment 0 is identity for alignment 1 for memset, but not store.
9820     if (Alignment == 0) Alignment = 1;
9821     
9822     // Extract the fill value and store.
9823     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9824     InsertNewInstBefore(new StoreInst(Context->getConstantInt(ITy, Fill),
9825                                       Dest, false, Alignment), *MI);
9826     
9827     // Set the size of the copy to 0, it will be deleted on the next iteration.
9828     MI->setLength(Context->getNullValue(LenC->getType()));
9829     return MI;
9830   }
9831
9832   return 0;
9833 }
9834
9835
9836 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9837 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9838 /// the heavy lifting.
9839 ///
9840 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9841   // If the caller function is nounwind, mark the call as nounwind, even if the
9842   // callee isn't.
9843   if (CI.getParent()->getParent()->doesNotThrow() &&
9844       !CI.doesNotThrow()) {
9845     CI.setDoesNotThrow();
9846     return &CI;
9847   }
9848   
9849   
9850   
9851   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9852   if (!II) return visitCallSite(&CI);
9853   
9854   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9855   // visitCallSite.
9856   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9857     bool Changed = false;
9858
9859     // memmove/cpy/set of zero bytes is a noop.
9860     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9861       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9862
9863       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9864         if (CI->getZExtValue() == 1) {
9865           // Replace the instruction with just byte operations.  We would
9866           // transform other cases to loads/stores, but we don't know if
9867           // alignment is sufficient.
9868         }
9869     }
9870
9871     // If we have a memmove and the source operation is a constant global,
9872     // then the source and dest pointers can't alias, so we can change this
9873     // into a call to memcpy.
9874     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9875       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9876         if (GVSrc->isConstant()) {
9877           Module *M = CI.getParent()->getParent()->getParent();
9878           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9879           const Type *Tys[1];
9880           Tys[0] = CI.getOperand(3)->getType();
9881           CI.setOperand(0, 
9882                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9883           Changed = true;
9884         }
9885
9886       // memmove(x,x,size) -> noop.
9887       if (MMI->getSource() == MMI->getDest())
9888         return EraseInstFromFunction(CI);
9889     }
9890
9891     // If we can determine a pointer alignment that is bigger than currently
9892     // set, update the alignment.
9893     if (isa<MemTransferInst>(MI)) {
9894       if (Instruction *I = SimplifyMemTransfer(MI))
9895         return I;
9896     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9897       if (Instruction *I = SimplifyMemSet(MSI))
9898         return I;
9899     }
9900           
9901     if (Changed) return II;
9902   }
9903   
9904   switch (II->getIntrinsicID()) {
9905   default: break;
9906   case Intrinsic::bswap:
9907     // bswap(bswap(x)) -> x
9908     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9909       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9910         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9911     break;
9912   case Intrinsic::ppc_altivec_lvx:
9913   case Intrinsic::ppc_altivec_lvxl:
9914   case Intrinsic::x86_sse_loadu_ps:
9915   case Intrinsic::x86_sse2_loadu_pd:
9916   case Intrinsic::x86_sse2_loadu_dq:
9917     // Turn PPC lvx     -> load if the pointer is known aligned.
9918     // Turn X86 loadups -> load if the pointer is known aligned.
9919     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9920       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9921                                    Context->getPointerTypeUnqual(II->getType()),
9922                                        CI);
9923       return new LoadInst(Ptr);
9924     }
9925     break;
9926   case Intrinsic::ppc_altivec_stvx:
9927   case Intrinsic::ppc_altivec_stvxl:
9928     // Turn stvx -> store if the pointer is known aligned.
9929     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9930       const Type *OpPtrTy = 
9931         Context->getPointerTypeUnqual(II->getOperand(1)->getType());
9932       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9933       return new StoreInst(II->getOperand(1), Ptr);
9934     }
9935     break;
9936   case Intrinsic::x86_sse_storeu_ps:
9937   case Intrinsic::x86_sse2_storeu_pd:
9938   case Intrinsic::x86_sse2_storeu_dq:
9939     // Turn X86 storeu -> store if the pointer is known aligned.
9940     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9941       const Type *OpPtrTy = 
9942         Context->getPointerTypeUnqual(II->getOperand(2)->getType());
9943       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9944       return new StoreInst(II->getOperand(2), Ptr);
9945     }
9946     break;
9947     
9948   case Intrinsic::x86_sse_cvttss2si: {
9949     // These intrinsics only demands the 0th element of its input vector.  If
9950     // we can simplify the input based on that, do so now.
9951     unsigned VWidth =
9952       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9953     APInt DemandedElts(VWidth, 1);
9954     APInt UndefElts(VWidth, 0);
9955     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9956                                               UndefElts)) {
9957       II->setOperand(1, V);
9958       return II;
9959     }
9960     break;
9961   }
9962     
9963   case Intrinsic::ppc_altivec_vperm:
9964     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9965     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9966       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9967       
9968       // Check that all of the elements are integer constants or undefs.
9969       bool AllEltsOk = true;
9970       for (unsigned i = 0; i != 16; ++i) {
9971         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9972             !isa<UndefValue>(Mask->getOperand(i))) {
9973           AllEltsOk = false;
9974           break;
9975         }
9976       }
9977       
9978       if (AllEltsOk) {
9979         // Cast the input vectors to byte vectors.
9980         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9981         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9982         Value *Result = Context->getUndef(Op0->getType());
9983         
9984         // Only extract each element once.
9985         Value *ExtractedElts[32];
9986         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9987         
9988         for (unsigned i = 0; i != 16; ++i) {
9989           if (isa<UndefValue>(Mask->getOperand(i)))
9990             continue;
9991           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9992           Idx &= 31;  // Match the hardware behavior.
9993           
9994           if (ExtractedElts[Idx] == 0) {
9995             Instruction *Elt = 
9996               new ExtractElementInst(Idx < 16 ? Op0 : Op1, 
9997                   Context->getConstantInt(Type::Int32Ty, Idx&15, false), "tmp");
9998             InsertNewInstBefore(Elt, CI);
9999             ExtractedElts[Idx] = Elt;
10000           }
10001         
10002           // Insert this value into the result vector.
10003           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
10004                                Context->getConstantInt(Type::Int32Ty, i, false), 
10005                                "tmp");
10006           InsertNewInstBefore(cast<Instruction>(Result), CI);
10007         }
10008         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
10009       }
10010     }
10011     break;
10012
10013   case Intrinsic::stackrestore: {
10014     // If the save is right next to the restore, remove the restore.  This can
10015     // happen when variable allocas are DCE'd.
10016     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10017       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10018         BasicBlock::iterator BI = SS;
10019         if (&*++BI == II)
10020           return EraseInstFromFunction(CI);
10021       }
10022     }
10023     
10024     // Scan down this block to see if there is another stack restore in the
10025     // same block without an intervening call/alloca.
10026     BasicBlock::iterator BI = II;
10027     TerminatorInst *TI = II->getParent()->getTerminator();
10028     bool CannotRemove = false;
10029     for (++BI; &*BI != TI; ++BI) {
10030       if (isa<AllocaInst>(BI)) {
10031         CannotRemove = true;
10032         break;
10033       }
10034       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10035         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10036           // If there is a stackrestore below this one, remove this one.
10037           if (II->getIntrinsicID() == Intrinsic::stackrestore)
10038             return EraseInstFromFunction(CI);
10039           // Otherwise, ignore the intrinsic.
10040         } else {
10041           // If we found a non-intrinsic call, we can't remove the stack
10042           // restore.
10043           CannotRemove = true;
10044           break;
10045         }
10046       }
10047     }
10048     
10049     // If the stack restore is in a return/unwind block and if there are no
10050     // allocas or calls between the restore and the return, nuke the restore.
10051     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10052       return EraseInstFromFunction(CI);
10053     break;
10054   }
10055   }
10056
10057   return visitCallSite(II);
10058 }
10059
10060 // InvokeInst simplification
10061 //
10062 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10063   return visitCallSite(&II);
10064 }
10065
10066 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
10067 /// passed through the varargs area, we can eliminate the use of the cast.
10068 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10069                                          const CastInst * const CI,
10070                                          const TargetData * const TD,
10071                                          const int ix) {
10072   if (!CI->isLosslessCast())
10073     return false;
10074
10075   // The size of ByVal arguments is derived from the type, so we
10076   // can't change to a type with a different size.  If the size were
10077   // passed explicitly we could avoid this check.
10078   if (!CS.paramHasAttr(ix, Attribute::ByVal))
10079     return true;
10080
10081   const Type* SrcTy = 
10082             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10083   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10084   if (!SrcTy->isSized() || !DstTy->isSized())
10085     return false;
10086   if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10087     return false;
10088   return true;
10089 }
10090
10091 // visitCallSite - Improvements for call and invoke instructions.
10092 //
10093 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10094   bool Changed = false;
10095
10096   // If the callee is a constexpr cast of a function, attempt to move the cast
10097   // to the arguments of the call/invoke.
10098   if (transformConstExprCastCall(CS)) return 0;
10099
10100   Value *Callee = CS.getCalledValue();
10101
10102   if (Function *CalleeF = dyn_cast<Function>(Callee))
10103     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10104       Instruction *OldCall = CS.getInstruction();
10105       // If the call and callee calling conventions don't match, this call must
10106       // be unreachable, as the call is undefined.
10107       new StoreInst(Context->getConstantIntTrue(),
10108                 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), 
10109                                   OldCall);
10110       if (!OldCall->use_empty())
10111         OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
10112       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10113         return EraseInstFromFunction(*OldCall);
10114       return 0;
10115     }
10116
10117   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10118     // This instruction is not reachable, just remove it.  We insert a store to
10119     // undef so that we know that this code is not reachable, despite the fact
10120     // that we can't modify the CFG here.
10121     new StoreInst(Context->getConstantIntTrue(),
10122                Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10123                   CS.getInstruction());
10124
10125     if (!CS.getInstruction()->use_empty())
10126       CS.getInstruction()->
10127         replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
10128
10129     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10130       // Don't break the CFG, insert a dummy cond branch.
10131       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10132                          Context->getConstantIntTrue(), II);
10133     }
10134     return EraseInstFromFunction(*CS.getInstruction());
10135   }
10136
10137   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10138     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10139       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10140         return transformCallThroughTrampoline(CS);
10141
10142   const PointerType *PTy = cast<PointerType>(Callee->getType());
10143   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10144   if (FTy->isVarArg()) {
10145     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10146     // See if we can optimize any arguments passed through the varargs area of
10147     // the call.
10148     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10149            E = CS.arg_end(); I != E; ++I, ++ix) {
10150       CastInst *CI = dyn_cast<CastInst>(*I);
10151       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10152         *I = CI->getOperand(0);
10153         Changed = true;
10154       }
10155     }
10156   }
10157
10158   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10159     // Inline asm calls cannot throw - mark them 'nounwind'.
10160     CS.setDoesNotThrow();
10161     Changed = true;
10162   }
10163
10164   return Changed ? CS.getInstruction() : 0;
10165 }
10166
10167 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10168 // attempt to move the cast to the arguments of the call/invoke.
10169 //
10170 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10171   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10172   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10173   if (CE->getOpcode() != Instruction::BitCast || 
10174       !isa<Function>(CE->getOperand(0)))
10175     return false;
10176   Function *Callee = cast<Function>(CE->getOperand(0));
10177   Instruction *Caller = CS.getInstruction();
10178   const AttrListPtr &CallerPAL = CS.getAttributes();
10179
10180   // Okay, this is a cast from a function to a different type.  Unless doing so
10181   // would cause a type conversion of one of our arguments, change this call to
10182   // be a direct call with arguments casted to the appropriate types.
10183   //
10184   const FunctionType *FT = Callee->getFunctionType();
10185   const Type *OldRetTy = Caller->getType();
10186   const Type *NewRetTy = FT->getReturnType();
10187
10188   if (isa<StructType>(NewRetTy))
10189     return false; // TODO: Handle multiple return values.
10190
10191   // Check to see if we are changing the return type...
10192   if (OldRetTy != NewRetTy) {
10193     if (Callee->isDeclaration() &&
10194         // Conversion is ok if changing from one pointer type to another or from
10195         // a pointer to an integer of the same size.
10196         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
10197           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
10198       return false;   // Cannot transform this return value.
10199
10200     if (!Caller->use_empty() &&
10201         // void -> non-void is handled specially
10202         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
10203       return false;   // Cannot transform this return value.
10204
10205     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10206       Attributes RAttrs = CallerPAL.getRetAttributes();
10207       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10208         return false;   // Attribute not compatible with transformed value.
10209     }
10210
10211     // If the callsite is an invoke instruction, and the return value is used by
10212     // a PHI node in a successor, we cannot change the return type of the call
10213     // because there is no place to put the cast instruction (without breaking
10214     // the critical edge).  Bail out in this case.
10215     if (!Caller->use_empty())
10216       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10217         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10218              UI != E; ++UI)
10219           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10220             if (PN->getParent() == II->getNormalDest() ||
10221                 PN->getParent() == II->getUnwindDest())
10222               return false;
10223   }
10224
10225   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10226   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10227
10228   CallSite::arg_iterator AI = CS.arg_begin();
10229   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10230     const Type *ParamTy = FT->getParamType(i);
10231     const Type *ActTy = (*AI)->getType();
10232
10233     if (!CastInst::isCastable(ActTy, ParamTy))
10234       return false;   // Cannot transform this parameter value.
10235
10236     if (CallerPAL.getParamAttributes(i + 1) 
10237         & Attribute::typeIncompatible(ParamTy))
10238       return false;   // Attribute not compatible with transformed value.
10239
10240     // Converting from one pointer type to another or between a pointer and an
10241     // integer of the same size is safe even if we do not have a body.
10242     bool isConvertible = ActTy == ParamTy ||
10243       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10244        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
10245     if (Callee->isDeclaration() && !isConvertible) return false;
10246   }
10247
10248   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10249       Callee->isDeclaration())
10250     return false;   // Do not delete arguments unless we have a function body.
10251
10252   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10253       !CallerPAL.isEmpty())
10254     // In this case we have more arguments than the new function type, but we
10255     // won't be dropping them.  Check that these extra arguments have attributes
10256     // that are compatible with being a vararg call argument.
10257     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10258       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10259         break;
10260       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10261       if (PAttrs & Attribute::VarArgsIncompatible)
10262         return false;
10263     }
10264
10265   // Okay, we decided that this is a safe thing to do: go ahead and start
10266   // inserting cast instructions as necessary...
10267   std::vector<Value*> Args;
10268   Args.reserve(NumActualArgs);
10269   SmallVector<AttributeWithIndex, 8> attrVec;
10270   attrVec.reserve(NumCommonArgs);
10271
10272   // Get any return attributes.
10273   Attributes RAttrs = CallerPAL.getRetAttributes();
10274
10275   // If the return value is not being used, the type may not be compatible
10276   // with the existing attributes.  Wipe out any problematic attributes.
10277   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10278
10279   // Add the new return attributes.
10280   if (RAttrs)
10281     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10282
10283   AI = CS.arg_begin();
10284   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10285     const Type *ParamTy = FT->getParamType(i);
10286     if ((*AI)->getType() == ParamTy) {
10287       Args.push_back(*AI);
10288     } else {
10289       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10290           false, ParamTy, false);
10291       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10292       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10293     }
10294
10295     // Add any parameter attributes.
10296     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10297       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10298   }
10299
10300   // If the function takes more arguments than the call was taking, add them
10301   // now...
10302   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10303     Args.push_back(Context->getNullValue(FT->getParamType(i)));
10304
10305   // If we are removing arguments to the function, emit an obnoxious warning...
10306   if (FT->getNumParams() < NumActualArgs) {
10307     if (!FT->isVarArg()) {
10308       cerr << "WARNING: While resolving call to function '"
10309            << Callee->getName() << "' arguments were dropped!\n";
10310     } else {
10311       // Add all of the arguments in their promoted form to the arg list...
10312       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10313         const Type *PTy = getPromotedType((*AI)->getType());
10314         if (PTy != (*AI)->getType()) {
10315           // Must promote to pass through va_arg area!
10316           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
10317                                                                 PTy, false);
10318           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10319           InsertNewInstBefore(Cast, *Caller);
10320           Args.push_back(Cast);
10321         } else {
10322           Args.push_back(*AI);
10323         }
10324
10325         // Add any parameter attributes.
10326         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10327           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10328       }
10329     }
10330   }
10331
10332   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10333     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10334
10335   if (NewRetTy == Type::VoidTy)
10336     Caller->setName("");   // Void type should not have a name.
10337
10338   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
10339
10340   Instruction *NC;
10341   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10342     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10343                             Args.begin(), Args.end(),
10344                             Caller->getName(), Caller);
10345     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10346     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10347   } else {
10348     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10349                           Caller->getName(), Caller);
10350     CallInst *CI = cast<CallInst>(Caller);
10351     if (CI->isTailCall())
10352       cast<CallInst>(NC)->setTailCall();
10353     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10354     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10355   }
10356
10357   // Insert a cast of the return type as necessary.
10358   Value *NV = NC;
10359   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10360     if (NV->getType() != Type::VoidTy) {
10361       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10362                                                             OldRetTy, false);
10363       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10364
10365       // If this is an invoke instruction, we should insert it after the first
10366       // non-phi, instruction in the normal successor block.
10367       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10368         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10369         InsertNewInstBefore(NC, *I);
10370       } else {
10371         // Otherwise, it's a call, just insert cast right after the call instr
10372         InsertNewInstBefore(NC, *Caller);
10373       }
10374       AddUsersToWorkList(*Caller);
10375     } else {
10376       NV = Context->getUndef(Caller->getType());
10377     }
10378   }
10379
10380   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10381     Caller->replaceAllUsesWith(NV);
10382   Caller->eraseFromParent();
10383   RemoveFromWorkList(Caller);
10384   return true;
10385 }
10386
10387 // transformCallThroughTrampoline - Turn a call to a function created by the
10388 // init_trampoline intrinsic into a direct call to the underlying function.
10389 //
10390 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10391   Value *Callee = CS.getCalledValue();
10392   const PointerType *PTy = cast<PointerType>(Callee->getType());
10393   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10394   const AttrListPtr &Attrs = CS.getAttributes();
10395
10396   // If the call already has the 'nest' attribute somewhere then give up -
10397   // otherwise 'nest' would occur twice after splicing in the chain.
10398   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10399     return 0;
10400
10401   IntrinsicInst *Tramp =
10402     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10403
10404   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10405   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10406   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10407
10408   const AttrListPtr &NestAttrs = NestF->getAttributes();
10409   if (!NestAttrs.isEmpty()) {
10410     unsigned NestIdx = 1;
10411     const Type *NestTy = 0;
10412     Attributes NestAttr = Attribute::None;
10413
10414     // Look for a parameter marked with the 'nest' attribute.
10415     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10416          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10417       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10418         // Record the parameter type and any other attributes.
10419         NestTy = *I;
10420         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10421         break;
10422       }
10423
10424     if (NestTy) {
10425       Instruction *Caller = CS.getInstruction();
10426       std::vector<Value*> NewArgs;
10427       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10428
10429       SmallVector<AttributeWithIndex, 8> NewAttrs;
10430       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10431
10432       // Insert the nest argument into the call argument list, which may
10433       // mean appending it.  Likewise for attributes.
10434
10435       // Add any result attributes.
10436       if (Attributes Attr = Attrs.getRetAttributes())
10437         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10438
10439       {
10440         unsigned Idx = 1;
10441         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10442         do {
10443           if (Idx == NestIdx) {
10444             // Add the chain argument and attributes.
10445             Value *NestVal = Tramp->getOperand(3);
10446             if (NestVal->getType() != NestTy)
10447               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10448             NewArgs.push_back(NestVal);
10449             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10450           }
10451
10452           if (I == E)
10453             break;
10454
10455           // Add the original argument and attributes.
10456           NewArgs.push_back(*I);
10457           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10458             NewAttrs.push_back
10459               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10460
10461           ++Idx, ++I;
10462         } while (1);
10463       }
10464
10465       // Add any function attributes.
10466       if (Attributes Attr = Attrs.getFnAttributes())
10467         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10468
10469       // The trampoline may have been bitcast to a bogus type (FTy).
10470       // Handle this by synthesizing a new function type, equal to FTy
10471       // with the chain parameter inserted.
10472
10473       std::vector<const Type*> NewTypes;
10474       NewTypes.reserve(FTy->getNumParams()+1);
10475
10476       // Insert the chain's type into the list of parameter types, which may
10477       // mean appending it.
10478       {
10479         unsigned Idx = 1;
10480         FunctionType::param_iterator I = FTy->param_begin(),
10481           E = FTy->param_end();
10482
10483         do {
10484           if (Idx == NestIdx)
10485             // Add the chain's type.
10486             NewTypes.push_back(NestTy);
10487
10488           if (I == E)
10489             break;
10490
10491           // Add the original type.
10492           NewTypes.push_back(*I);
10493
10494           ++Idx, ++I;
10495         } while (1);
10496       }
10497
10498       // Replace the trampoline call with a direct call.  Let the generic
10499       // code sort out any function type mismatches.
10500       FunctionType *NewFTy =
10501                        Context->getFunctionType(FTy->getReturnType(), NewTypes, 
10502                                                 FTy->isVarArg());
10503       Constant *NewCallee =
10504         NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10505         NestF : Context->getConstantExprBitCast(NestF, 
10506                                          Context->getPointerTypeUnqual(NewFTy));
10507       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
10508
10509       Instruction *NewCaller;
10510       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10511         NewCaller = InvokeInst::Create(NewCallee,
10512                                        II->getNormalDest(), II->getUnwindDest(),
10513                                        NewArgs.begin(), NewArgs.end(),
10514                                        Caller->getName(), Caller);
10515         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10516         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10517       } else {
10518         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10519                                      Caller->getName(), Caller);
10520         if (cast<CallInst>(Caller)->isTailCall())
10521           cast<CallInst>(NewCaller)->setTailCall();
10522         cast<CallInst>(NewCaller)->
10523           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10524         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10525       }
10526       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10527         Caller->replaceAllUsesWith(NewCaller);
10528       Caller->eraseFromParent();
10529       RemoveFromWorkList(Caller);
10530       return 0;
10531     }
10532   }
10533
10534   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10535   // parameter, there is no need to adjust the argument list.  Let the generic
10536   // code sort out any function type mismatches.
10537   Constant *NewCallee =
10538     NestF->getType() == PTy ? NestF : 
10539                               Context->getConstantExprBitCast(NestF, PTy);
10540   CS.setCalledFunction(NewCallee);
10541   return CS.getInstruction();
10542 }
10543
10544 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10545 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10546 /// and a single binop.
10547 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10548   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10549   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10550   unsigned Opc = FirstInst->getOpcode();
10551   Value *LHSVal = FirstInst->getOperand(0);
10552   Value *RHSVal = FirstInst->getOperand(1);
10553     
10554   const Type *LHSType = LHSVal->getType();
10555   const Type *RHSType = RHSVal->getType();
10556   
10557   // Scan to see if all operands are the same opcode, all have one use, and all
10558   // kill their operands (i.e. the operands have one use).
10559   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10560     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10561     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10562         // Verify type of the LHS matches so we don't fold cmp's of different
10563         // types or GEP's with different index types.
10564         I->getOperand(0)->getType() != LHSType ||
10565         I->getOperand(1)->getType() != RHSType)
10566       return 0;
10567
10568     // If they are CmpInst instructions, check their predicates
10569     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10570       if (cast<CmpInst>(I)->getPredicate() !=
10571           cast<CmpInst>(FirstInst)->getPredicate())
10572         return 0;
10573     
10574     // Keep track of which operand needs a phi node.
10575     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10576     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10577   }
10578   
10579   // Otherwise, this is safe to transform!
10580   
10581   Value *InLHS = FirstInst->getOperand(0);
10582   Value *InRHS = FirstInst->getOperand(1);
10583   PHINode *NewLHS = 0, *NewRHS = 0;
10584   if (LHSVal == 0) {
10585     NewLHS = PHINode::Create(LHSType,
10586                              FirstInst->getOperand(0)->getName() + ".pn");
10587     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10588     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10589     InsertNewInstBefore(NewLHS, PN);
10590     LHSVal = NewLHS;
10591   }
10592   
10593   if (RHSVal == 0) {
10594     NewRHS = PHINode::Create(RHSType,
10595                              FirstInst->getOperand(1)->getName() + ".pn");
10596     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10597     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10598     InsertNewInstBefore(NewRHS, PN);
10599     RHSVal = NewRHS;
10600   }
10601   
10602   // Add all operands to the new PHIs.
10603   if (NewLHS || NewRHS) {
10604     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10605       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10606       if (NewLHS) {
10607         Value *NewInLHS = InInst->getOperand(0);
10608         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10609       }
10610       if (NewRHS) {
10611         Value *NewInRHS = InInst->getOperand(1);
10612         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10613       }
10614     }
10615   }
10616     
10617   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10618     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10619   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10620   return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10621                          LHSVal, RHSVal);
10622 }
10623
10624 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10625   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10626   
10627   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10628                                         FirstInst->op_end());
10629   // This is true if all GEP bases are allocas and if all indices into them are
10630   // constants.
10631   bool AllBasePointersAreAllocas = true;
10632   
10633   // Scan to see if all operands are the same opcode, all have one use, and all
10634   // kill their operands (i.e. the operands have one use).
10635   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10636     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10637     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10638       GEP->getNumOperands() != FirstInst->getNumOperands())
10639       return 0;
10640
10641     // Keep track of whether or not all GEPs are of alloca pointers.
10642     if (AllBasePointersAreAllocas &&
10643         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10644          !GEP->hasAllConstantIndices()))
10645       AllBasePointersAreAllocas = false;
10646     
10647     // Compare the operand lists.
10648     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10649       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10650         continue;
10651       
10652       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10653       // if one of the PHIs has a constant for the index.  The index may be
10654       // substantially cheaper to compute for the constants, so making it a
10655       // variable index could pessimize the path.  This also handles the case
10656       // for struct indices, which must always be constant.
10657       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10658           isa<ConstantInt>(GEP->getOperand(op)))
10659         return 0;
10660       
10661       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10662         return 0;
10663       FixedOperands[op] = 0;  // Needs a PHI.
10664     }
10665   }
10666   
10667   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10668   // bother doing this transformation.  At best, this will just save a bit of
10669   // offset calculation, but all the predecessors will have to materialize the
10670   // stack address into a register anyway.  We'd actually rather *clone* the
10671   // load up into the predecessors so that we have a load of a gep of an alloca,
10672   // which can usually all be folded into the load.
10673   if (AllBasePointersAreAllocas)
10674     return 0;
10675   
10676   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10677   // that is variable.
10678   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10679   
10680   bool HasAnyPHIs = false;
10681   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10682     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10683     Value *FirstOp = FirstInst->getOperand(i);
10684     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10685                                      FirstOp->getName()+".pn");
10686     InsertNewInstBefore(NewPN, PN);
10687     
10688     NewPN->reserveOperandSpace(e);
10689     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10690     OperandPhis[i] = NewPN;
10691     FixedOperands[i] = NewPN;
10692     HasAnyPHIs = true;
10693   }
10694
10695   
10696   // Add all operands to the new PHIs.
10697   if (HasAnyPHIs) {
10698     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10699       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10700       BasicBlock *InBB = PN.getIncomingBlock(i);
10701       
10702       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10703         if (PHINode *OpPhi = OperandPhis[op])
10704           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10705     }
10706   }
10707   
10708   Value *Base = FixedOperands[0];
10709   return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10710                                    FixedOperands.end());
10711 }
10712
10713
10714 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10715 /// sink the load out of the block that defines it.  This means that it must be
10716 /// obvious the value of the load is not changed from the point of the load to
10717 /// the end of the block it is in.
10718 ///
10719 /// Finally, it is safe, but not profitable, to sink a load targetting a
10720 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10721 /// to a register.
10722 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10723   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10724   
10725   for (++BBI; BBI != E; ++BBI)
10726     if (BBI->mayWriteToMemory())
10727       return false;
10728   
10729   // Check for non-address taken alloca.  If not address-taken already, it isn't
10730   // profitable to do this xform.
10731   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10732     bool isAddressTaken = false;
10733     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10734          UI != E; ++UI) {
10735       if (isa<LoadInst>(UI)) continue;
10736       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10737         // If storing TO the alloca, then the address isn't taken.
10738         if (SI->getOperand(1) == AI) continue;
10739       }
10740       isAddressTaken = true;
10741       break;
10742     }
10743     
10744     if (!isAddressTaken && AI->isStaticAlloca())
10745       return false;
10746   }
10747   
10748   // If this load is a load from a GEP with a constant offset from an alloca,
10749   // then we don't want to sink it.  In its present form, it will be
10750   // load [constant stack offset].  Sinking it will cause us to have to
10751   // materialize the stack addresses in each predecessor in a register only to
10752   // do a shared load from register in the successor.
10753   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10754     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10755       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10756         return false;
10757   
10758   return true;
10759 }
10760
10761
10762 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10763 // operator and they all are only used by the PHI, PHI together their
10764 // inputs, and do the operation once, to the result of the PHI.
10765 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10766   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10767
10768   // Scan the instruction, looking for input operations that can be folded away.
10769   // If all input operands to the phi are the same instruction (e.g. a cast from
10770   // the same type or "+42") we can pull the operation through the PHI, reducing
10771   // code size and simplifying code.
10772   Constant *ConstantOp = 0;
10773   const Type *CastSrcTy = 0;
10774   bool isVolatile = false;
10775   if (isa<CastInst>(FirstInst)) {
10776     CastSrcTy = FirstInst->getOperand(0)->getType();
10777   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10778     // Can fold binop, compare or shift here if the RHS is a constant, 
10779     // otherwise call FoldPHIArgBinOpIntoPHI.
10780     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10781     if (ConstantOp == 0)
10782       return FoldPHIArgBinOpIntoPHI(PN);
10783   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10784     isVolatile = LI->isVolatile();
10785     // We can't sink the load if the loaded value could be modified between the
10786     // load and the PHI.
10787     if (LI->getParent() != PN.getIncomingBlock(0) ||
10788         !isSafeAndProfitableToSinkLoad(LI))
10789       return 0;
10790     
10791     // If the PHI is of volatile loads and the load block has multiple
10792     // successors, sinking it would remove a load of the volatile value from
10793     // the path through the other successor.
10794     if (isVolatile &&
10795         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10796       return 0;
10797     
10798   } else if (isa<GetElementPtrInst>(FirstInst)) {
10799     return FoldPHIArgGEPIntoPHI(PN);
10800   } else {
10801     return 0;  // Cannot fold this operation.
10802   }
10803
10804   // Check to see if all arguments are the same operation.
10805   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10806     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10807     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10808     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10809       return 0;
10810     if (CastSrcTy) {
10811       if (I->getOperand(0)->getType() != CastSrcTy)
10812         return 0;  // Cast operation must match.
10813     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10814       // We can't sink the load if the loaded value could be modified between 
10815       // the load and the PHI.
10816       if (LI->isVolatile() != isVolatile ||
10817           LI->getParent() != PN.getIncomingBlock(i) ||
10818           !isSafeAndProfitableToSinkLoad(LI))
10819         return 0;
10820       
10821       // If the PHI is of volatile loads and the load block has multiple
10822       // successors, sinking it would remove a load of the volatile value from
10823       // the path through the other successor.
10824       if (isVolatile &&
10825           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10826         return 0;
10827       
10828     } else if (I->getOperand(1) != ConstantOp) {
10829       return 0;
10830     }
10831   }
10832
10833   // Okay, they are all the same operation.  Create a new PHI node of the
10834   // correct type, and PHI together all of the LHS's of the instructions.
10835   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10836                                    PN.getName()+".in");
10837   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10838
10839   Value *InVal = FirstInst->getOperand(0);
10840   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10841
10842   // Add all operands to the new PHI.
10843   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10844     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10845     if (NewInVal != InVal)
10846       InVal = 0;
10847     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10848   }
10849
10850   Value *PhiVal;
10851   if (InVal) {
10852     // The new PHI unions all of the same values together.  This is really
10853     // common, so we handle it intelligently here for compile-time speed.
10854     PhiVal = InVal;
10855     delete NewPN;
10856   } else {
10857     InsertNewInstBefore(NewPN, PN);
10858     PhiVal = NewPN;
10859   }
10860
10861   // Insert and return the new operation.
10862   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10863     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10864   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10865     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10866   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10867     return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10868                            PhiVal, ConstantOp);
10869   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10870   
10871   // If this was a volatile load that we are merging, make sure to loop through
10872   // and mark all the input loads as non-volatile.  If we don't do this, we will
10873   // insert a new volatile load and the old ones will not be deletable.
10874   if (isVolatile)
10875     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10876       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10877   
10878   return new LoadInst(PhiVal, "", isVolatile);
10879 }
10880
10881 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10882 /// that is dead.
10883 static bool DeadPHICycle(PHINode *PN,
10884                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10885   if (PN->use_empty()) return true;
10886   if (!PN->hasOneUse()) return false;
10887
10888   // Remember this node, and if we find the cycle, return.
10889   if (!PotentiallyDeadPHIs.insert(PN))
10890     return true;
10891   
10892   // Don't scan crazily complex things.
10893   if (PotentiallyDeadPHIs.size() == 16)
10894     return false;
10895
10896   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10897     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10898
10899   return false;
10900 }
10901
10902 /// PHIsEqualValue - Return true if this phi node is always equal to
10903 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10904 ///   z = some value; x = phi (y, z); y = phi (x, z)
10905 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10906                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10907   // See if we already saw this PHI node.
10908   if (!ValueEqualPHIs.insert(PN))
10909     return true;
10910   
10911   // Don't scan crazily complex things.
10912   if (ValueEqualPHIs.size() == 16)
10913     return false;
10914  
10915   // Scan the operands to see if they are either phi nodes or are equal to
10916   // the value.
10917   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10918     Value *Op = PN->getIncomingValue(i);
10919     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10920       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10921         return false;
10922     } else if (Op != NonPhiInVal)
10923       return false;
10924   }
10925   
10926   return true;
10927 }
10928
10929
10930 // PHINode simplification
10931 //
10932 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10933   // If LCSSA is around, don't mess with Phi nodes
10934   if (MustPreserveLCSSA) return 0;
10935   
10936   if (Value *V = PN.hasConstantValue())
10937     return ReplaceInstUsesWith(PN, V);
10938
10939   // If all PHI operands are the same operation, pull them through the PHI,
10940   // reducing code size.
10941   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10942       isa<Instruction>(PN.getIncomingValue(1)) &&
10943       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10944       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10945       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10946       // than themselves more than once.
10947       PN.getIncomingValue(0)->hasOneUse())
10948     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10949       return Result;
10950
10951   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10952   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10953   // PHI)... break the cycle.
10954   if (PN.hasOneUse()) {
10955     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10956     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10957       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10958       PotentiallyDeadPHIs.insert(&PN);
10959       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10960         return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10961     }
10962    
10963     // If this phi has a single use, and if that use just computes a value for
10964     // the next iteration of a loop, delete the phi.  This occurs with unused
10965     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10966     // common case here is good because the only other things that catch this
10967     // are induction variable analysis (sometimes) and ADCE, which is only run
10968     // late.
10969     if (PHIUser->hasOneUse() &&
10970         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10971         PHIUser->use_back() == &PN) {
10972       return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10973     }
10974   }
10975
10976   // We sometimes end up with phi cycles that non-obviously end up being the
10977   // same value, for example:
10978   //   z = some value; x = phi (y, z); y = phi (x, z)
10979   // where the phi nodes don't necessarily need to be in the same block.  Do a
10980   // quick check to see if the PHI node only contains a single non-phi value, if
10981   // so, scan to see if the phi cycle is actually equal to that value.
10982   {
10983     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10984     // Scan for the first non-phi operand.
10985     while (InValNo != NumOperandVals && 
10986            isa<PHINode>(PN.getIncomingValue(InValNo)))
10987       ++InValNo;
10988
10989     if (InValNo != NumOperandVals) {
10990       Value *NonPhiInVal = PN.getOperand(InValNo);
10991       
10992       // Scan the rest of the operands to see if there are any conflicts, if so
10993       // there is no need to recursively scan other phis.
10994       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10995         Value *OpVal = PN.getIncomingValue(InValNo);
10996         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10997           break;
10998       }
10999       
11000       // If we scanned over all operands, then we have one unique value plus
11001       // phi values.  Scan PHI nodes to see if they all merge in each other or
11002       // the value.
11003       if (InValNo == NumOperandVals) {
11004         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11005         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11006           return ReplaceInstUsesWith(PN, NonPhiInVal);
11007       }
11008     }
11009   }
11010   return 0;
11011 }
11012
11013 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
11014                                    Instruction *InsertPoint,
11015                                    InstCombiner *IC) {
11016   unsigned PtrSize = DTy->getScalarSizeInBits();
11017   unsigned VTySize = V->getType()->getScalarSizeInBits();
11018   // We must cast correctly to the pointer type. Ensure that we
11019   // sign extend the integer value if it is smaller as this is
11020   // used for address computation.
11021   Instruction::CastOps opcode = 
11022      (VTySize < PtrSize ? Instruction::SExt :
11023       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
11024   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
11025 }
11026
11027
11028 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
11029   Value *PtrOp = GEP.getOperand(0);
11030   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
11031   // If so, eliminate the noop.
11032   if (GEP.getNumOperands() == 1)
11033     return ReplaceInstUsesWith(GEP, PtrOp);
11034
11035   if (isa<UndefValue>(GEP.getOperand(0)))
11036     return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
11037
11038   bool HasZeroPointerIndex = false;
11039   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11040     HasZeroPointerIndex = C->isNullValue();
11041
11042   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11043     return ReplaceInstUsesWith(GEP, PtrOp);
11044
11045   // Eliminate unneeded casts for indices.
11046   bool MadeChange = false;
11047   
11048   gep_type_iterator GTI = gep_type_begin(GEP);
11049   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11050        i != e; ++i, ++GTI) {
11051     if (isa<SequentialType>(*GTI)) {
11052       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
11053         if (CI->getOpcode() == Instruction::ZExt ||
11054             CI->getOpcode() == Instruction::SExt) {
11055           const Type *SrcTy = CI->getOperand(0)->getType();
11056           // We can eliminate a cast from i32 to i64 iff the target 
11057           // is a 32-bit pointer target.
11058           if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
11059             MadeChange = true;
11060             *i = CI->getOperand(0);
11061           }
11062         }
11063       }
11064       // If we are using a wider index than needed for this platform, shrink it
11065       // to what we need.  If narrower, sign-extend it to what we need.
11066       // If the incoming value needs a cast instruction,
11067       // insert it.  This explicit cast can make subsequent optimizations more
11068       // obvious.
11069       Value *Op = *i;
11070       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
11071         if (Constant *C = dyn_cast<Constant>(Op)) {
11072           *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
11073           MadeChange = true;
11074         } else {
11075           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11076                                 GEP);
11077           *i = Op;
11078           MadeChange = true;
11079         }
11080       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
11081         if (Constant *C = dyn_cast<Constant>(Op)) {
11082           *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
11083           MadeChange = true;
11084         } else {
11085           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11086                                 GEP);
11087           *i = Op;
11088           MadeChange = true;
11089         }
11090       }
11091     }
11092   }
11093   if (MadeChange) return &GEP;
11094
11095   // Combine Indices - If the source pointer to this getelementptr instruction
11096   // is a getelementptr instruction, combine the indices of the two
11097   // getelementptr instructions into a single instruction.
11098   //
11099   SmallVector<Value*, 8> SrcGEPOperands;
11100   if (User *Src = dyn_castGetElementPtr(PtrOp))
11101     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
11102
11103   if (!SrcGEPOperands.empty()) {
11104     // Note that if our source is a gep chain itself that we wait for that
11105     // chain to be resolved before we perform this transformation.  This
11106     // avoids us creating a TON of code in some cases.
11107     //
11108     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11109         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11110       return 0;   // Wait until our source is folded to completion.
11111
11112     SmallVector<Value*, 8> Indices;
11113
11114     // Find out whether the last index in the source GEP is a sequential idx.
11115     bool EndsWithSequential = false;
11116     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11117            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11118       EndsWithSequential = !isa<StructType>(*I);
11119
11120     // Can we combine the two pointer arithmetics offsets?
11121     if (EndsWithSequential) {
11122       // Replace: gep (gep %P, long B), long A, ...
11123       // With:    T = long A+B; gep %P, T, ...
11124       //
11125       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
11126       if (SO1 == Context->getNullValue(SO1->getType())) {
11127         Sum = GO1;
11128       } else if (GO1 == Context->getNullValue(GO1->getType())) {
11129         Sum = SO1;
11130       } else {
11131         // If they aren't the same type, convert both to an integer of the
11132         // target's pointer size.
11133         if (SO1->getType() != GO1->getType()) {
11134           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
11135             SO1 =
11136                 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
11137           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
11138             GO1 =
11139                 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
11140           } else {
11141             unsigned PS = TD->getPointerSizeInBits();
11142             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
11143               // Convert GO1 to SO1's type.
11144               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11145
11146             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
11147               // Convert SO1 to GO1's type.
11148               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11149             } else {
11150               const Type *PT = TD->getIntPtrType();
11151               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11152               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11153             }
11154           }
11155         }
11156         if (isa<Constant>(SO1) && isa<Constant>(GO1))
11157           Sum = Context->getConstantExprAdd(cast<Constant>(SO1), 
11158                                             cast<Constant>(GO1));
11159         else {
11160           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11161           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11162         }
11163       }
11164
11165       // Recycle the GEP we already have if possible.
11166       if (SrcGEPOperands.size() == 2) {
11167         GEP.setOperand(0, SrcGEPOperands[0]);
11168         GEP.setOperand(1, Sum);
11169         return &GEP;
11170       } else {
11171         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11172                        SrcGEPOperands.end()-1);
11173         Indices.push_back(Sum);
11174         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11175       }
11176     } else if (isa<Constant>(*GEP.idx_begin()) &&
11177                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11178                SrcGEPOperands.size() != 1) {
11179       // Otherwise we can do the fold if the first index of the GEP is a zero
11180       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11181                      SrcGEPOperands.end());
11182       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11183     }
11184
11185     if (!Indices.empty())
11186       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11187                                        Indices.end(), GEP.getName());
11188
11189   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11190     // GEP of global variable.  If all of the indices for this GEP are
11191     // constants, we can promote this to a constexpr instead of an instruction.
11192
11193     // Scan for nonconstants...
11194     SmallVector<Constant*, 8> Indices;
11195     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11196     for (; I != E && isa<Constant>(*I); ++I)
11197       Indices.push_back(cast<Constant>(*I));
11198
11199     if (I == E) {  // If they are all constants...
11200       Constant *CE = Context->getConstantExprGetElementPtr(GV,
11201                                                     &Indices[0],Indices.size());
11202
11203       // Replace all uses of the GEP with the new constexpr...
11204       return ReplaceInstUsesWith(GEP, CE);
11205     }
11206   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
11207     if (!isa<PointerType>(X->getType())) {
11208       // Not interesting.  Source pointer must be a cast from pointer.
11209     } else if (HasZeroPointerIndex) {
11210       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11211       // into     : GEP [10 x i8]* X, i32 0, ...
11212       //
11213       // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11214       //           into     : GEP i8* X, ...
11215       // 
11216       // This occurs when the program declares an array extern like "int X[];"
11217       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11218       const PointerType *XTy = cast<PointerType>(X->getType());
11219       if (const ArrayType *CATy =
11220           dyn_cast<ArrayType>(CPTy->getElementType())) {
11221         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11222         if (CATy->getElementType() == XTy->getElementType()) {
11223           // -> GEP i8* X, ...
11224           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11225           return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11226                                            GEP.getName());
11227         } else if (const ArrayType *XATy =
11228                  dyn_cast<ArrayType>(XTy->getElementType())) {
11229           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11230           if (CATy->getElementType() == XATy->getElementType()) {
11231             // -> GEP [10 x i8]* X, i32 0, ...
11232             // At this point, we know that the cast source type is a pointer
11233             // to an array of the same type as the destination pointer
11234             // array.  Because the array type is never stepped over (there
11235             // is a leading zero) we can fold the cast into this GEP.
11236             GEP.setOperand(0, X);
11237             return &GEP;
11238           }
11239         }
11240       }
11241     } else if (GEP.getNumOperands() == 2) {
11242       // Transform things like:
11243       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11244       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11245       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11246       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11247       if (isa<ArrayType>(SrcElTy) &&
11248           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11249           TD->getTypeAllocSize(ResElTy)) {
11250         Value *Idx[2];
11251         Idx[0] = Context->getNullValue(Type::Int32Ty);
11252         Idx[1] = GEP.getOperand(1);
11253         Value *V = InsertNewInstBefore(
11254                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
11255         // V and GEP are both pointer types --> BitCast
11256         return new BitCastInst(V, GEP.getType());
11257       }
11258       
11259       // Transform things like:
11260       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11261       //   (where tmp = 8*tmp2) into:
11262       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11263       
11264       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
11265         uint64_t ArrayEltSize =
11266             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11267         
11268         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11269         // allow either a mul, shift, or constant here.
11270         Value *NewIdx = 0;
11271         ConstantInt *Scale = 0;
11272         if (ArrayEltSize == 1) {
11273           NewIdx = GEP.getOperand(1);
11274           Scale = 
11275                Context->getConstantInt(cast<IntegerType>(NewIdx->getType()), 1);
11276         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11277           NewIdx = Context->getConstantInt(CI->getType(), 1);
11278           Scale = CI;
11279         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11280           if (Inst->getOpcode() == Instruction::Shl &&
11281               isa<ConstantInt>(Inst->getOperand(1))) {
11282             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11283             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11284             Scale = Context->getConstantInt(cast<IntegerType>(Inst->getType()),
11285                                      1ULL << ShAmtVal);
11286             NewIdx = Inst->getOperand(0);
11287           } else if (Inst->getOpcode() == Instruction::Mul &&
11288                      isa<ConstantInt>(Inst->getOperand(1))) {
11289             Scale = cast<ConstantInt>(Inst->getOperand(1));
11290             NewIdx = Inst->getOperand(0);
11291           }
11292         }
11293         
11294         // If the index will be to exactly the right offset with the scale taken
11295         // out, perform the transformation. Note, we don't know whether Scale is
11296         // signed or not. We'll use unsigned version of division/modulo
11297         // operation after making sure Scale doesn't have the sign bit set.
11298         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11299             Scale->getZExtValue() % ArrayEltSize == 0) {
11300           Scale = Context->getConstantInt(Scale->getType(),
11301                                    Scale->getZExtValue() / ArrayEltSize);
11302           if (Scale->getZExtValue() != 1) {
11303             Constant *C =
11304                    Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
11305                                                        false /*ZExt*/);
11306             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11307             NewIdx = InsertNewInstBefore(Sc, GEP);
11308           }
11309
11310           // Insert the new GEP instruction.
11311           Value *Idx[2];
11312           Idx[0] = Context->getNullValue(Type::Int32Ty);
11313           Idx[1] = NewIdx;
11314           Instruction *NewGEP =
11315             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11316           NewGEP = InsertNewInstBefore(NewGEP, GEP);
11317           // The NewGEP must be pointer typed, so must the old one -> BitCast
11318           return new BitCastInst(NewGEP, GEP.getType());
11319         }
11320       }
11321     }
11322   }
11323   
11324   /// See if we can simplify:
11325   ///   X = bitcast A to B*
11326   ///   Y = gep X, <...constant indices...>
11327   /// into a gep of the original struct.  This is important for SROA and alias
11328   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11329   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11330     if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11331       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11332       // a constant back from EmitGEPOffset.
11333       ConstantInt *OffsetV =
11334                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11335       int64_t Offset = OffsetV->getSExtValue();
11336       
11337       // If this GEP instruction doesn't move the pointer, just replace the GEP
11338       // with a bitcast of the real input to the dest type.
11339       if (Offset == 0) {
11340         // If the bitcast is of an allocation, and the allocation will be
11341         // converted to match the type of the cast, don't touch this.
11342         if (isa<AllocationInst>(BCI->getOperand(0))) {
11343           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11344           if (Instruction *I = visitBitCast(*BCI)) {
11345             if (I != BCI) {
11346               I->takeName(BCI);
11347               BCI->getParent()->getInstList().insert(BCI, I);
11348               ReplaceInstUsesWith(*BCI, I);
11349             }
11350             return &GEP;
11351           }
11352         }
11353         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11354       }
11355       
11356       // Otherwise, if the offset is non-zero, we need to find out if there is a
11357       // field at Offset in 'A's type.  If so, we can pull the cast through the
11358       // GEP.
11359       SmallVector<Value*, 8> NewIndices;
11360       const Type *InTy =
11361         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11362       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11363         Instruction *NGEP =
11364            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11365                                      NewIndices.end());
11366         if (NGEP->getType() == GEP.getType()) return NGEP;
11367         InsertNewInstBefore(NGEP, GEP);
11368         NGEP->takeName(&GEP);
11369         return new BitCastInst(NGEP, GEP.getType());
11370       }
11371     }
11372   }    
11373     
11374   return 0;
11375 }
11376
11377 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11378   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11379   if (AI.isArrayAllocation()) {  // Check C != 1
11380     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11381       const Type *NewTy = 
11382         Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
11383       AllocationInst *New = 0;
11384
11385       // Create and insert the replacement instruction...
11386       if (isa<MallocInst>(AI))
11387         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11388       else {
11389         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11390         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11391       }
11392
11393       InsertNewInstBefore(New, AI);
11394
11395       // Scan to the end of the allocation instructions, to skip over a block of
11396       // allocas if possible...also skip interleaved debug info
11397       //
11398       BasicBlock::iterator It = New;
11399       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11400
11401       // Now that I is pointing to the first non-allocation-inst in the block,
11402       // insert our getelementptr instruction...
11403       //
11404       Value *NullIdx = Context->getNullValue(Type::Int32Ty);
11405       Value *Idx[2];
11406       Idx[0] = NullIdx;
11407       Idx[1] = NullIdx;
11408       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11409                                            New->getName()+".sub", It);
11410
11411       // Now make everything use the getelementptr instead of the original
11412       // allocation.
11413       return ReplaceInstUsesWith(AI, V);
11414     } else if (isa<UndefValue>(AI.getArraySize())) {
11415       return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11416     }
11417   }
11418
11419   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11420     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11421     // Note that we only do this for alloca's, because malloc should allocate
11422     // and return a unique pointer, even for a zero byte allocation.
11423     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11424       return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11425
11426     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11427     if (AI.getAlignment() == 0)
11428       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11429   }
11430
11431   return 0;
11432 }
11433
11434 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11435   Value *Op = FI.getOperand(0);
11436
11437   // free undef -> unreachable.
11438   if (isa<UndefValue>(Op)) {
11439     // Insert a new store to null because we cannot modify the CFG here.
11440     new StoreInst(Context->getConstantIntTrue(),
11441            Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
11442     return EraseInstFromFunction(FI);
11443   }
11444   
11445   // If we have 'free null' delete the instruction.  This can happen in stl code
11446   // when lots of inlining happens.
11447   if (isa<ConstantPointerNull>(Op))
11448     return EraseInstFromFunction(FI);
11449   
11450   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11451   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11452     FI.setOperand(0, CI->getOperand(0));
11453     return &FI;
11454   }
11455   
11456   // Change free (gep X, 0,0,0,0) into free(X)
11457   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11458     if (GEPI->hasAllZeroIndices()) {
11459       AddToWorkList(GEPI);
11460       FI.setOperand(0, GEPI->getOperand(0));
11461       return &FI;
11462     }
11463   }
11464   
11465   // Change free(malloc) into nothing, if the malloc has a single use.
11466   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11467     if (MI->hasOneUse()) {
11468       EraseInstFromFunction(FI);
11469       return EraseInstFromFunction(*MI);
11470     }
11471
11472   return 0;
11473 }
11474
11475
11476 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11477 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11478                                         const TargetData *TD) {
11479   User *CI = cast<User>(LI.getOperand(0));
11480   Value *CastOp = CI->getOperand(0);
11481   LLVMContext *Context = IC.getContext();
11482
11483   if (TD) {
11484     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11485       // Instead of loading constant c string, use corresponding integer value
11486       // directly if string length is small enough.
11487       std::string Str;
11488       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11489         unsigned len = Str.length();
11490         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11491         unsigned numBits = Ty->getPrimitiveSizeInBits();
11492         // Replace LI with immediate integer store.
11493         if ((numBits >> 3) == len + 1) {
11494           APInt StrVal(numBits, 0);
11495           APInt SingleChar(numBits, 0);
11496           if (TD->isLittleEndian()) {
11497             for (signed i = len-1; i >= 0; i--) {
11498               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11499               StrVal = (StrVal << 8) | SingleChar;
11500             }
11501           } else {
11502             for (unsigned i = 0; i < len; i++) {
11503               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11504               StrVal = (StrVal << 8) | SingleChar;
11505             }
11506             // Append NULL at the end.
11507             SingleChar = 0;
11508             StrVal = (StrVal << 8) | SingleChar;
11509           }
11510           Value *NL = Context->getConstantInt(StrVal);
11511           return IC.ReplaceInstUsesWith(LI, NL);
11512         }
11513       }
11514     }
11515   }
11516
11517   const PointerType *DestTy = cast<PointerType>(CI->getType());
11518   const Type *DestPTy = DestTy->getElementType();
11519   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11520
11521     // If the address spaces don't match, don't eliminate the cast.
11522     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11523       return 0;
11524
11525     const Type *SrcPTy = SrcTy->getElementType();
11526
11527     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11528          isa<VectorType>(DestPTy)) {
11529       // If the source is an array, the code below will not succeed.  Check to
11530       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11531       // constants.
11532       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11533         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11534           if (ASrcTy->getNumElements() != 0) {
11535             Value *Idxs[2];
11536             Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11537             CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
11538             SrcTy = cast<PointerType>(CastOp->getType());
11539             SrcPTy = SrcTy->getElementType();
11540           }
11541
11542       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11543             isa<VectorType>(SrcPTy)) &&
11544           // Do not allow turning this into a load of an integer, which is then
11545           // casted to a pointer, this pessimizes pointer analysis a lot.
11546           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11547           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11548                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11549
11550         // Okay, we are casting from one integer or pointer type to another of
11551         // the same size.  Instead of casting the pointer before the load, cast
11552         // the result of the loaded value.
11553         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11554                                                              CI->getName(),
11555                                                          LI.isVolatile()),LI);
11556         // Now cast the result of the load.
11557         return new BitCastInst(NewLoad, LI.getType());
11558       }
11559     }
11560   }
11561   return 0;
11562 }
11563
11564 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11565   Value *Op = LI.getOperand(0);
11566
11567   // Attempt to improve the alignment.
11568   unsigned KnownAlign =
11569     GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11570   if (KnownAlign >
11571       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11572                                 LI.getAlignment()))
11573     LI.setAlignment(KnownAlign);
11574
11575   // load (cast X) --> cast (load X) iff safe
11576   if (isa<CastInst>(Op))
11577     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11578       return Res;
11579
11580   // None of the following transforms are legal for volatile loads.
11581   if (LI.isVolatile()) return 0;
11582   
11583   // Do really simple store-to-load forwarding and load CSE, to catch cases
11584   // where there are several consequtive memory accesses to the same location,
11585   // separated by a few arithmetic operations.
11586   BasicBlock::iterator BBI = &LI;
11587   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11588     return ReplaceInstUsesWith(LI, AvailableVal);
11589
11590   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11591     const Value *GEPI0 = GEPI->getOperand(0);
11592     // TODO: Consider a target hook for valid address spaces for this xform.
11593     if (isa<ConstantPointerNull>(GEPI0) &&
11594         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11595       // Insert a new store to null instruction before the load to indicate
11596       // that this code is not reachable.  We do this instead of inserting
11597       // an unreachable instruction directly because we cannot modify the
11598       // CFG.
11599       new StoreInst(Context->getUndef(LI.getType()),
11600                     Context->getNullValue(Op->getType()), &LI);
11601       return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11602     }
11603   } 
11604
11605   if (Constant *C = dyn_cast<Constant>(Op)) {
11606     // load null/undef -> undef
11607     // TODO: Consider a target hook for valid address spaces for this xform.
11608     if (isa<UndefValue>(C) || (C->isNullValue() && 
11609         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11610       // Insert a new store to null instruction before the load to indicate that
11611       // this code is not reachable.  We do this instead of inserting an
11612       // unreachable instruction directly because we cannot modify the CFG.
11613       new StoreInst(Context->getUndef(LI.getType()),
11614                     Context->getNullValue(Op->getType()), &LI);
11615       return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11616     }
11617
11618     // Instcombine load (constant global) into the value loaded.
11619     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11620       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11621         return ReplaceInstUsesWith(LI, GV->getInitializer());
11622
11623     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11624     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11625       if (CE->getOpcode() == Instruction::GetElementPtr) {
11626         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11627           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11628             if (Constant *V = 
11629                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE, 
11630                                                       Context))
11631               return ReplaceInstUsesWith(LI, V);
11632         if (CE->getOperand(0)->isNullValue()) {
11633           // Insert a new store to null instruction before the load to indicate
11634           // that this code is not reachable.  We do this instead of inserting
11635           // an unreachable instruction directly because we cannot modify the
11636           // CFG.
11637           new StoreInst(Context->getUndef(LI.getType()),
11638                         Context->getNullValue(Op->getType()), &LI);
11639           return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11640         }
11641
11642       } else if (CE->isCast()) {
11643         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11644           return Res;
11645       }
11646     }
11647   }
11648     
11649   // If this load comes from anywhere in a constant global, and if the global
11650   // is all undef or zero, we know what it loads.
11651   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11652     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11653       if (GV->getInitializer()->isNullValue())
11654         return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
11655       else if (isa<UndefValue>(GV->getInitializer()))
11656         return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11657     }
11658   }
11659
11660   if (Op->hasOneUse()) {
11661     // Change select and PHI nodes to select values instead of addresses: this
11662     // helps alias analysis out a lot, allows many others simplifications, and
11663     // exposes redundancy in the code.
11664     //
11665     // Note that we cannot do the transformation unless we know that the
11666     // introduced loads cannot trap!  Something like this is valid as long as
11667     // the condition is always false: load (select bool %C, int* null, int* %G),
11668     // but it would not be valid if we transformed it to load from null
11669     // unconditionally.
11670     //
11671     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11672       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11673       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11674           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11675         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11676                                      SI->getOperand(1)->getName()+".val"), LI);
11677         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11678                                      SI->getOperand(2)->getName()+".val"), LI);
11679         return SelectInst::Create(SI->getCondition(), V1, V2);
11680       }
11681
11682       // load (select (cond, null, P)) -> load P
11683       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11684         if (C->isNullValue()) {
11685           LI.setOperand(0, SI->getOperand(2));
11686           return &LI;
11687         }
11688
11689       // load (select (cond, P, null)) -> load P
11690       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11691         if (C->isNullValue()) {
11692           LI.setOperand(0, SI->getOperand(1));
11693           return &LI;
11694         }
11695     }
11696   }
11697   return 0;
11698 }
11699
11700 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11701 /// when possible.  This makes it generally easy to do alias analysis and/or
11702 /// SROA/mem2reg of the memory object.
11703 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11704   User *CI = cast<User>(SI.getOperand(1));
11705   Value *CastOp = CI->getOperand(0);
11706   LLVMContext *Context = IC.getContext();
11707
11708   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11709   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11710   if (SrcTy == 0) return 0;
11711   
11712   const Type *SrcPTy = SrcTy->getElementType();
11713
11714   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11715     return 0;
11716   
11717   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11718   /// to its first element.  This allows us to handle things like:
11719   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11720   /// on 32-bit hosts.
11721   SmallVector<Value*, 4> NewGEPIndices;
11722   
11723   // If the source is an array, the code below will not succeed.  Check to
11724   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11725   // constants.
11726   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11727     // Index through pointer.
11728     Constant *Zero = Context->getNullValue(Type::Int32Ty);
11729     NewGEPIndices.push_back(Zero);
11730     
11731     while (1) {
11732       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11733         if (!STy->getNumElements()) /* Struct can be empty {} */
11734           break;
11735         NewGEPIndices.push_back(Zero);
11736         SrcPTy = STy->getElementType(0);
11737       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11738         NewGEPIndices.push_back(Zero);
11739         SrcPTy = ATy->getElementType();
11740       } else {
11741         break;
11742       }
11743     }
11744     
11745     SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
11746   }
11747
11748   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11749     return 0;
11750   
11751   // If the pointers point into different address spaces or if they point to
11752   // values with different sizes, we can't do the transformation.
11753   if (SrcTy->getAddressSpace() != 
11754         cast<PointerType>(CI->getType())->getAddressSpace() ||
11755       IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
11756       IC.getTargetData().getTypeSizeInBits(DestPTy))
11757     return 0;
11758
11759   // Okay, we are casting from one integer or pointer type to another of
11760   // the same size.  Instead of casting the pointer before 
11761   // the store, cast the value to be stored.
11762   Value *NewCast;
11763   Value *SIOp0 = SI.getOperand(0);
11764   Instruction::CastOps opcode = Instruction::BitCast;
11765   const Type* CastSrcTy = SIOp0->getType();
11766   const Type* CastDstTy = SrcPTy;
11767   if (isa<PointerType>(CastDstTy)) {
11768     if (CastSrcTy->isInteger())
11769       opcode = Instruction::IntToPtr;
11770   } else if (isa<IntegerType>(CastDstTy)) {
11771     if (isa<PointerType>(SIOp0->getType()))
11772       opcode = Instruction::PtrToInt;
11773   }
11774   
11775   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11776   // emit a GEP to index into its first field.
11777   if (!NewGEPIndices.empty()) {
11778     if (Constant *C = dyn_cast<Constant>(CastOp))
11779       CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0], 
11780                                               NewGEPIndices.size());
11781     else
11782       CastOp = IC.InsertNewInstBefore(
11783               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11784                                         NewGEPIndices.end()), SI);
11785   }
11786   
11787   if (Constant *C = dyn_cast<Constant>(SIOp0))
11788     NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
11789   else
11790     NewCast = IC.InsertNewInstBefore(
11791       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11792       SI);
11793   return new StoreInst(NewCast, CastOp);
11794 }
11795
11796 /// equivalentAddressValues - Test if A and B will obviously have the same
11797 /// value. This includes recognizing that %t0 and %t1 will have the same
11798 /// value in code like this:
11799 ///   %t0 = getelementptr \@a, 0, 3
11800 ///   store i32 0, i32* %t0
11801 ///   %t1 = getelementptr \@a, 0, 3
11802 ///   %t2 = load i32* %t1
11803 ///
11804 static bool equivalentAddressValues(Value *A, Value *B) {
11805   // Test if the values are trivially equivalent.
11806   if (A == B) return true;
11807   
11808   // Test if the values come form identical arithmetic instructions.
11809   if (isa<BinaryOperator>(A) ||
11810       isa<CastInst>(A) ||
11811       isa<PHINode>(A) ||
11812       isa<GetElementPtrInst>(A))
11813     if (Instruction *BI = dyn_cast<Instruction>(B))
11814       if (cast<Instruction>(A)->isIdenticalTo(BI))
11815         return true;
11816   
11817   // Otherwise they may not be equivalent.
11818   return false;
11819 }
11820
11821 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11822 // return the llvm.dbg.declare.
11823 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11824   if (!V->hasNUses(2))
11825     return 0;
11826   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11827        UI != E; ++UI) {
11828     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11829       return DI;
11830     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11831       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11832         return DI;
11833       }
11834   }
11835   return 0;
11836 }
11837
11838 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11839   Value *Val = SI.getOperand(0);
11840   Value *Ptr = SI.getOperand(1);
11841
11842   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11843     EraseInstFromFunction(SI);
11844     ++NumCombined;
11845     return 0;
11846   }
11847   
11848   // If the RHS is an alloca with a single use, zapify the store, making the
11849   // alloca dead.
11850   // If the RHS is an alloca with a two uses, the other one being a 
11851   // llvm.dbg.declare, zapify the store and the declare, making the
11852   // alloca dead.  We must do this to prevent declare's from affecting
11853   // codegen.
11854   if (!SI.isVolatile()) {
11855     if (Ptr->hasOneUse()) {
11856       if (isa<AllocaInst>(Ptr)) {
11857         EraseInstFromFunction(SI);
11858         ++NumCombined;
11859         return 0;
11860       }
11861       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11862         if (isa<AllocaInst>(GEP->getOperand(0))) {
11863           if (GEP->getOperand(0)->hasOneUse()) {
11864             EraseInstFromFunction(SI);
11865             ++NumCombined;
11866             return 0;
11867           }
11868           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11869             EraseInstFromFunction(*DI);
11870             EraseInstFromFunction(SI);
11871             ++NumCombined;
11872             return 0;
11873           }
11874         }
11875       }
11876     }
11877     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11878       EraseInstFromFunction(*DI);
11879       EraseInstFromFunction(SI);
11880       ++NumCombined;
11881       return 0;
11882     }
11883   }
11884
11885   // Attempt to improve the alignment.
11886   unsigned KnownAlign =
11887     GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11888   if (KnownAlign >
11889       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11890                                 SI.getAlignment()))
11891     SI.setAlignment(KnownAlign);
11892
11893   // Do really simple DSE, to catch cases where there are several consecutive
11894   // stores to the same location, separated by a few arithmetic operations. This
11895   // situation often occurs with bitfield accesses.
11896   BasicBlock::iterator BBI = &SI;
11897   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11898        --ScanInsts) {
11899     --BBI;
11900     // Don't count debug info directives, lest they affect codegen,
11901     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11902     // It is necessary for correctness to skip those that feed into a
11903     // llvm.dbg.declare, as these are not present when debugging is off.
11904     if (isa<DbgInfoIntrinsic>(BBI) ||
11905         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11906       ScanInsts++;
11907       continue;
11908     }    
11909     
11910     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11911       // Prev store isn't volatile, and stores to the same location?
11912       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11913                                                           SI.getOperand(1))) {
11914         ++NumDeadStore;
11915         ++BBI;
11916         EraseInstFromFunction(*PrevSI);
11917         continue;
11918       }
11919       break;
11920     }
11921     
11922     // If this is a load, we have to stop.  However, if the loaded value is from
11923     // the pointer we're loading and is producing the pointer we're storing,
11924     // then *this* store is dead (X = load P; store X -> P).
11925     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11926       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11927           !SI.isVolatile()) {
11928         EraseInstFromFunction(SI);
11929         ++NumCombined;
11930         return 0;
11931       }
11932       // Otherwise, this is a load from some other location.  Stores before it
11933       // may not be dead.
11934       break;
11935     }
11936     
11937     // Don't skip over loads or things that can modify memory.
11938     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11939       break;
11940   }
11941   
11942   
11943   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11944
11945   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11946   if (isa<ConstantPointerNull>(Ptr) &&
11947       cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11948     if (!isa<UndefValue>(Val)) {
11949       SI.setOperand(0, Context->getUndef(Val->getType()));
11950       if (Instruction *U = dyn_cast<Instruction>(Val))
11951         AddToWorkList(U);  // Dropped a use.
11952       ++NumCombined;
11953     }
11954     return 0;  // Do not modify these!
11955   }
11956
11957   // store undef, Ptr -> noop
11958   if (isa<UndefValue>(Val)) {
11959     EraseInstFromFunction(SI);
11960     ++NumCombined;
11961     return 0;
11962   }
11963
11964   // If the pointer destination is a cast, see if we can fold the cast into the
11965   // source instead.
11966   if (isa<CastInst>(Ptr))
11967     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11968       return Res;
11969   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11970     if (CE->isCast())
11971       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11972         return Res;
11973
11974   
11975   // If this store is the last instruction in the basic block (possibly
11976   // excepting debug info instructions and the pointer bitcasts that feed
11977   // into them), and if the block ends with an unconditional branch, try
11978   // to move it to the successor block.
11979   BBI = &SI; 
11980   do {
11981     ++BBI;
11982   } while (isa<DbgInfoIntrinsic>(BBI) ||
11983            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11984   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11985     if (BI->isUnconditional())
11986       if (SimplifyStoreAtEndOfBlock(SI))
11987         return 0;  // xform done!
11988   
11989   return 0;
11990 }
11991
11992 /// SimplifyStoreAtEndOfBlock - Turn things like:
11993 ///   if () { *P = v1; } else { *P = v2 }
11994 /// into a phi node with a store in the successor.
11995 ///
11996 /// Simplify things like:
11997 ///   *P = v1; if () { *P = v2; }
11998 /// into a phi node with a store in the successor.
11999 ///
12000 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12001   BasicBlock *StoreBB = SI.getParent();
12002   
12003   // Check to see if the successor block has exactly two incoming edges.  If
12004   // so, see if the other predecessor contains a store to the same location.
12005   // if so, insert a PHI node (if needed) and move the stores down.
12006   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
12007   
12008   // Determine whether Dest has exactly two predecessors and, if so, compute
12009   // the other predecessor.
12010   pred_iterator PI = pred_begin(DestBB);
12011   BasicBlock *OtherBB = 0;
12012   if (*PI != StoreBB)
12013     OtherBB = *PI;
12014   ++PI;
12015   if (PI == pred_end(DestBB))
12016     return false;
12017   
12018   if (*PI != StoreBB) {
12019     if (OtherBB)
12020       return false;
12021     OtherBB = *PI;
12022   }
12023   if (++PI != pred_end(DestBB))
12024     return false;
12025
12026   // Bail out if all the relevant blocks aren't distinct (this can happen,
12027   // for example, if SI is in an infinite loop)
12028   if (StoreBB == DestBB || OtherBB == DestBB)
12029     return false;
12030
12031   // Verify that the other block ends in a branch and is not otherwise empty.
12032   BasicBlock::iterator BBI = OtherBB->getTerminator();
12033   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12034   if (!OtherBr || BBI == OtherBB->begin())
12035     return false;
12036   
12037   // If the other block ends in an unconditional branch, check for the 'if then
12038   // else' case.  there is an instruction before the branch.
12039   StoreInst *OtherStore = 0;
12040   if (OtherBr->isUnconditional()) {
12041     --BBI;
12042     // Skip over debugging info.
12043     while (isa<DbgInfoIntrinsic>(BBI) ||
12044            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12045       if (BBI==OtherBB->begin())
12046         return false;
12047       --BBI;
12048     }
12049     // If this isn't a store, or isn't a store to the same location, bail out.
12050     OtherStore = dyn_cast<StoreInst>(BBI);
12051     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12052       return false;
12053   } else {
12054     // Otherwise, the other block ended with a conditional branch. If one of the
12055     // destinations is StoreBB, then we have the if/then case.
12056     if (OtherBr->getSuccessor(0) != StoreBB && 
12057         OtherBr->getSuccessor(1) != StoreBB)
12058       return false;
12059     
12060     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12061     // if/then triangle.  See if there is a store to the same ptr as SI that
12062     // lives in OtherBB.
12063     for (;; --BBI) {
12064       // Check to see if we find the matching store.
12065       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12066         if (OtherStore->getOperand(1) != SI.getOperand(1))
12067           return false;
12068         break;
12069       }
12070       // If we find something that may be using or overwriting the stored
12071       // value, or if we run out of instructions, we can't do the xform.
12072       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12073           BBI == OtherBB->begin())
12074         return false;
12075     }
12076     
12077     // In order to eliminate the store in OtherBr, we have to
12078     // make sure nothing reads or overwrites the stored value in
12079     // StoreBB.
12080     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12081       // FIXME: This should really be AA driven.
12082       if (I->mayReadFromMemory() || I->mayWriteToMemory())
12083         return false;
12084     }
12085   }
12086   
12087   // Insert a PHI node now if we need it.
12088   Value *MergedVal = OtherStore->getOperand(0);
12089   if (MergedVal != SI.getOperand(0)) {
12090     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12091     PN->reserveOperandSpace(2);
12092     PN->addIncoming(SI.getOperand(0), SI.getParent());
12093     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12094     MergedVal = InsertNewInstBefore(PN, DestBB->front());
12095   }
12096   
12097   // Advance to a place where it is safe to insert the new store and
12098   // insert it.
12099   BBI = DestBB->getFirstNonPHI();
12100   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12101                                     OtherStore->isVolatile()), *BBI);
12102   
12103   // Nuke the old stores.
12104   EraseInstFromFunction(SI);
12105   EraseInstFromFunction(*OtherStore);
12106   ++NumCombined;
12107   return true;
12108 }
12109
12110
12111 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12112   // Change br (not X), label True, label False to: br X, label False, True
12113   Value *X = 0;
12114   BasicBlock *TrueDest;
12115   BasicBlock *FalseDest;
12116   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
12117       !isa<Constant>(X)) {
12118     // Swap Destinations and condition...
12119     BI.setCondition(X);
12120     BI.setSuccessor(0, FalseDest);
12121     BI.setSuccessor(1, TrueDest);
12122     return &BI;
12123   }
12124
12125   // Cannonicalize fcmp_one -> fcmp_oeq
12126   FCmpInst::Predicate FPred; Value *Y;
12127   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
12128                              TrueDest, FalseDest), *Context))
12129     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12130          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12131       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12132       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
12133       Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
12134       NewSCC->takeName(I);
12135       // Swap Destinations and condition...
12136       BI.setCondition(NewSCC);
12137       BI.setSuccessor(0, FalseDest);
12138       BI.setSuccessor(1, TrueDest);
12139       RemoveFromWorkList(I);
12140       I->eraseFromParent();
12141       AddToWorkList(NewSCC);
12142       return &BI;
12143     }
12144
12145   // Cannonicalize icmp_ne -> icmp_eq
12146   ICmpInst::Predicate IPred;
12147   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12148                       TrueDest, FalseDest), *Context))
12149     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12150          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12151          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12152       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12153       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
12154       Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
12155       NewSCC->takeName(I);
12156       // Swap Destinations and condition...
12157       BI.setCondition(NewSCC);
12158       BI.setSuccessor(0, FalseDest);
12159       BI.setSuccessor(1, TrueDest);
12160       RemoveFromWorkList(I);
12161       I->eraseFromParent();;
12162       AddToWorkList(NewSCC);
12163       return &BI;
12164     }
12165
12166   return 0;
12167 }
12168
12169 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12170   Value *Cond = SI.getCondition();
12171   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12172     if (I->getOpcode() == Instruction::Add)
12173       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12174         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12175         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12176           SI.setOperand(i,
12177                    Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
12178                                                 AddRHS));
12179         SI.setOperand(0, I->getOperand(0));
12180         AddToWorkList(I);
12181         return &SI;
12182       }
12183   }
12184   return 0;
12185 }
12186
12187 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12188   Value *Agg = EV.getAggregateOperand();
12189
12190   if (!EV.hasIndices())
12191     return ReplaceInstUsesWith(EV, Agg);
12192
12193   if (Constant *C = dyn_cast<Constant>(Agg)) {
12194     if (isa<UndefValue>(C))
12195       return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
12196       
12197     if (isa<ConstantAggregateZero>(C))
12198       return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
12199
12200     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12201       // Extract the element indexed by the first index out of the constant
12202       Value *V = C->getOperand(*EV.idx_begin());
12203       if (EV.getNumIndices() > 1)
12204         // Extract the remaining indices out of the constant indexed by the
12205         // first index
12206         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12207       else
12208         return ReplaceInstUsesWith(EV, V);
12209     }
12210     return 0; // Can't handle other constants
12211   } 
12212   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12213     // We're extracting from an insertvalue instruction, compare the indices
12214     const unsigned *exti, *exte, *insi, *inse;
12215     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12216          exte = EV.idx_end(), inse = IV->idx_end();
12217          exti != exte && insi != inse;
12218          ++exti, ++insi) {
12219       if (*insi != *exti)
12220         // The insert and extract both reference distinctly different elements.
12221         // This means the extract is not influenced by the insert, and we can
12222         // replace the aggregate operand of the extract with the aggregate
12223         // operand of the insert. i.e., replace
12224         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12225         // %E = extractvalue { i32, { i32 } } %I, 0
12226         // with
12227         // %E = extractvalue { i32, { i32 } } %A, 0
12228         return ExtractValueInst::Create(IV->getAggregateOperand(),
12229                                         EV.idx_begin(), EV.idx_end());
12230     }
12231     if (exti == exte && insi == inse)
12232       // Both iterators are at the end: Index lists are identical. Replace
12233       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12234       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12235       // with "i32 42"
12236       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12237     if (exti == exte) {
12238       // The extract list is a prefix of the insert list. i.e. replace
12239       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12240       // %E = extractvalue { i32, { i32 } } %I, 1
12241       // with
12242       // %X = extractvalue { i32, { i32 } } %A, 1
12243       // %E = insertvalue { i32 } %X, i32 42, 0
12244       // by switching the order of the insert and extract (though the
12245       // insertvalue should be left in, since it may have other uses).
12246       Value *NewEV = InsertNewInstBefore(
12247         ExtractValueInst::Create(IV->getAggregateOperand(),
12248                                  EV.idx_begin(), EV.idx_end()),
12249         EV);
12250       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12251                                      insi, inse);
12252     }
12253     if (insi == inse)
12254       // The insert list is a prefix of the extract list
12255       // We can simply remove the common indices from the extract and make it
12256       // operate on the inserted value instead of the insertvalue result.
12257       // i.e., replace
12258       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12259       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12260       // with
12261       // %E extractvalue { i32 } { i32 42 }, 0
12262       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12263                                       exti, exte);
12264   }
12265   // Can't simplify extracts from other values. Note that nested extracts are
12266   // already simplified implicitely by the above (extract ( extract (insert) )
12267   // will be translated into extract ( insert ( extract ) ) first and then just
12268   // the value inserted, if appropriate).
12269   return 0;
12270 }
12271
12272 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12273 /// is to leave as a vector operation.
12274 static bool CheapToScalarize(Value *V, bool isConstant) {
12275   if (isa<ConstantAggregateZero>(V)) 
12276     return true;
12277   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12278     if (isConstant) return true;
12279     // If all elts are the same, we can extract.
12280     Constant *Op0 = C->getOperand(0);
12281     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12282       if (C->getOperand(i) != Op0)
12283         return false;
12284     return true;
12285   }
12286   Instruction *I = dyn_cast<Instruction>(V);
12287   if (!I) return false;
12288   
12289   // Insert element gets simplified to the inserted element or is deleted if
12290   // this is constant idx extract element and its a constant idx insertelt.
12291   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12292       isa<ConstantInt>(I->getOperand(2)))
12293     return true;
12294   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12295     return true;
12296   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12297     if (BO->hasOneUse() &&
12298         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12299          CheapToScalarize(BO->getOperand(1), isConstant)))
12300       return true;
12301   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12302     if (CI->hasOneUse() &&
12303         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12304          CheapToScalarize(CI->getOperand(1), isConstant)))
12305       return true;
12306   
12307   return false;
12308 }
12309
12310 /// Read and decode a shufflevector mask.
12311 ///
12312 /// It turns undef elements into values that are larger than the number of
12313 /// elements in the input.
12314 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12315   unsigned NElts = SVI->getType()->getNumElements();
12316   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12317     return std::vector<unsigned>(NElts, 0);
12318   if (isa<UndefValue>(SVI->getOperand(2)))
12319     return std::vector<unsigned>(NElts, 2*NElts);
12320
12321   std::vector<unsigned> Result;
12322   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12323   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12324     if (isa<UndefValue>(*i))
12325       Result.push_back(NElts*2);  // undef -> 8
12326     else
12327       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12328   return Result;
12329 }
12330
12331 /// FindScalarElement - Given a vector and an element number, see if the scalar
12332 /// value is already around as a register, for example if it were inserted then
12333 /// extracted from the vector.
12334 static Value *FindScalarElement(Value *V, unsigned EltNo,
12335                                 LLVMContext *Context) {
12336   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12337   const VectorType *PTy = cast<VectorType>(V->getType());
12338   unsigned Width = PTy->getNumElements();
12339   if (EltNo >= Width)  // Out of range access.
12340     return Context->getUndef(PTy->getElementType());
12341   
12342   if (isa<UndefValue>(V))
12343     return Context->getUndef(PTy->getElementType());
12344   else if (isa<ConstantAggregateZero>(V))
12345     return Context->getNullValue(PTy->getElementType());
12346   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12347     return CP->getOperand(EltNo);
12348   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12349     // If this is an insert to a variable element, we don't know what it is.
12350     if (!isa<ConstantInt>(III->getOperand(2))) 
12351       return 0;
12352     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12353     
12354     // If this is an insert to the element we are looking for, return the
12355     // inserted value.
12356     if (EltNo == IIElt) 
12357       return III->getOperand(1);
12358     
12359     // Otherwise, the insertelement doesn't modify the value, recurse on its
12360     // vector input.
12361     return FindScalarElement(III->getOperand(0), EltNo, Context);
12362   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12363     unsigned LHSWidth =
12364       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12365     unsigned InEl = getShuffleMask(SVI)[EltNo];
12366     if (InEl < LHSWidth)
12367       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12368     else if (InEl < LHSWidth*2)
12369       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12370     else
12371       return Context->getUndef(PTy->getElementType());
12372   }
12373   
12374   // Otherwise, we don't know.
12375   return 0;
12376 }
12377
12378 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12379   // If vector val is undef, replace extract with scalar undef.
12380   if (isa<UndefValue>(EI.getOperand(0)))
12381     return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12382
12383   // If vector val is constant 0, replace extract with scalar 0.
12384   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12385     return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
12386   
12387   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12388     // If vector val is constant with all elements the same, replace EI with
12389     // that element. When the elements are not identical, we cannot replace yet
12390     // (we do that below, but only when the index is constant).
12391     Constant *op0 = C->getOperand(0);
12392     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12393       if (C->getOperand(i) != op0) {
12394         op0 = 0; 
12395         break;
12396       }
12397     if (op0)
12398       return ReplaceInstUsesWith(EI, op0);
12399   }
12400   
12401   // If extracting a specified index from the vector, see if we can recursively
12402   // find a previously computed scalar that was inserted into the vector.
12403   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12404     unsigned IndexVal = IdxC->getZExtValue();
12405     unsigned VectorWidth = 
12406       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12407       
12408     // If this is extracting an invalid index, turn this into undef, to avoid
12409     // crashing the code below.
12410     if (IndexVal >= VectorWidth)
12411       return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12412     
12413     // This instruction only demands the single element from the input vector.
12414     // If the input vector has a single use, simplify it based on this use
12415     // property.
12416     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12417       APInt UndefElts(VectorWidth, 0);
12418       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12419       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12420                                                 DemandedMask, UndefElts)) {
12421         EI.setOperand(0, V);
12422         return &EI;
12423       }
12424     }
12425     
12426     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12427       return ReplaceInstUsesWith(EI, Elt);
12428     
12429     // If the this extractelement is directly using a bitcast from a vector of
12430     // the same number of elements, see if we can find the source element from
12431     // it.  In this case, we will end up needing to bitcast the scalars.
12432     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12433       if (const VectorType *VT = 
12434               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12435         if (VT->getNumElements() == VectorWidth)
12436           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12437                                              IndexVal, Context))
12438             return new BitCastInst(Elt, EI.getType());
12439     }
12440   }
12441   
12442   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12443     if (I->hasOneUse()) {
12444       // Push extractelement into predecessor operation if legal and
12445       // profitable to do so
12446       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12447         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12448         if (CheapToScalarize(BO, isConstantElt)) {
12449           ExtractElementInst *newEI0 = 
12450             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12451                                    EI.getName()+".lhs");
12452           ExtractElementInst *newEI1 =
12453             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12454                                    EI.getName()+".rhs");
12455           InsertNewInstBefore(newEI0, EI);
12456           InsertNewInstBefore(newEI1, EI);
12457           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12458         }
12459       } else if (isa<LoadInst>(I)) {
12460         unsigned AS = 
12461           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12462         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12463                                   Context->getPointerType(EI.getType(), AS),EI);
12464         GetElementPtrInst *GEP =
12465           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12466         InsertNewInstBefore(GEP, EI);
12467         return new LoadInst(GEP);
12468       }
12469     }
12470     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12471       // Extracting the inserted element?
12472       if (IE->getOperand(2) == EI.getOperand(1))
12473         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12474       // If the inserted and extracted elements are constants, they must not
12475       // be the same value, extract from the pre-inserted value instead.
12476       if (isa<Constant>(IE->getOperand(2)) &&
12477           isa<Constant>(EI.getOperand(1))) {
12478         AddUsesToWorkList(EI);
12479         EI.setOperand(0, IE->getOperand(0));
12480         return &EI;
12481       }
12482     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12483       // If this is extracting an element from a shufflevector, figure out where
12484       // it came from and extract from the appropriate input element instead.
12485       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12486         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12487         Value *Src;
12488         unsigned LHSWidth =
12489           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12490
12491         if (SrcIdx < LHSWidth)
12492           Src = SVI->getOperand(0);
12493         else if (SrcIdx < LHSWidth*2) {
12494           SrcIdx -= LHSWidth;
12495           Src = SVI->getOperand(1);
12496         } else {
12497           return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12498         }
12499         return new ExtractElementInst(Src,
12500                          Context->getConstantInt(Type::Int32Ty, SrcIdx, false));
12501       }
12502     }
12503     // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12504   }
12505   return 0;
12506 }
12507
12508 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12509 /// elements from either LHS or RHS, return the shuffle mask and true. 
12510 /// Otherwise, return false.
12511 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12512                                          std::vector<Constant*> &Mask,
12513                                          LLVMContext *Context) {
12514   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12515          "Invalid CollectSingleShuffleElements");
12516   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12517
12518   if (isa<UndefValue>(V)) {
12519     Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12520     return true;
12521   } else if (V == LHS) {
12522     for (unsigned i = 0; i != NumElts; ++i)
12523       Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12524     return true;
12525   } else if (V == RHS) {
12526     for (unsigned i = 0; i != NumElts; ++i)
12527       Mask.push_back(Context->getConstantInt(Type::Int32Ty, i+NumElts));
12528     return true;
12529   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12530     // If this is an insert of an extract from some other vector, include it.
12531     Value *VecOp    = IEI->getOperand(0);
12532     Value *ScalarOp = IEI->getOperand(1);
12533     Value *IdxOp    = IEI->getOperand(2);
12534     
12535     if (!isa<ConstantInt>(IdxOp))
12536       return false;
12537     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12538     
12539     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12540       // Okay, we can handle this if the vector we are insertinting into is
12541       // transitively ok.
12542       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12543         // If so, update the mask to reflect the inserted undef.
12544         Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
12545         return true;
12546       }      
12547     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12548       if (isa<ConstantInt>(EI->getOperand(1)) &&
12549           EI->getOperand(0)->getType() == V->getType()) {
12550         unsigned ExtractedIdx =
12551           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12552         
12553         // This must be extracting from either LHS or RHS.
12554         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12555           // Okay, we can handle this if the vector we are insertinting into is
12556           // transitively ok.
12557           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12558             // If so, update the mask to reflect the inserted value.
12559             if (EI->getOperand(0) == LHS) {
12560               Mask[InsertedIdx % NumElts] = 
12561                  Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12562             } else {
12563               assert(EI->getOperand(0) == RHS);
12564               Mask[InsertedIdx % NumElts] = 
12565                 Context->getConstantInt(Type::Int32Ty, ExtractedIdx+NumElts);
12566               
12567             }
12568             return true;
12569           }
12570         }
12571       }
12572     }
12573   }
12574   // TODO: Handle shufflevector here!
12575   
12576   return false;
12577 }
12578
12579 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12580 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12581 /// that computes V and the LHS value of the shuffle.
12582 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12583                                      Value *&RHS, LLVMContext *Context) {
12584   assert(isa<VectorType>(V->getType()) && 
12585          (RHS == 0 || V->getType() == RHS->getType()) &&
12586          "Invalid shuffle!");
12587   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12588
12589   if (isa<UndefValue>(V)) {
12590     Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12591     return V;
12592   } else if (isa<ConstantAggregateZero>(V)) {
12593     Mask.assign(NumElts, Context->getConstantInt(Type::Int32Ty, 0));
12594     return V;
12595   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12596     // If this is an insert of an extract from some other vector, include it.
12597     Value *VecOp    = IEI->getOperand(0);
12598     Value *ScalarOp = IEI->getOperand(1);
12599     Value *IdxOp    = IEI->getOperand(2);
12600     
12601     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12602       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12603           EI->getOperand(0)->getType() == V->getType()) {
12604         unsigned ExtractedIdx =
12605           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12606         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12607         
12608         // Either the extracted from or inserted into vector must be RHSVec,
12609         // otherwise we'd end up with a shuffle of three inputs.
12610         if (EI->getOperand(0) == RHS || RHS == 0) {
12611           RHS = EI->getOperand(0);
12612           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12613           Mask[InsertedIdx % NumElts] = 
12614             Context->getConstantInt(Type::Int32Ty, NumElts+ExtractedIdx);
12615           return V;
12616         }
12617         
12618         if (VecOp == RHS) {
12619           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12620                                             RHS, Context);
12621           // Everything but the extracted element is replaced with the RHS.
12622           for (unsigned i = 0; i != NumElts; ++i) {
12623             if (i != InsertedIdx)
12624               Mask[i] = Context->getConstantInt(Type::Int32Ty, NumElts+i);
12625           }
12626           return V;
12627         }
12628         
12629         // If this insertelement is a chain that comes from exactly these two
12630         // vectors, return the vector and the effective shuffle.
12631         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12632                                          Context))
12633           return EI->getOperand(0);
12634         
12635       }
12636     }
12637   }
12638   // TODO: Handle shufflevector here!
12639   
12640   // Otherwise, can't do anything fancy.  Return an identity vector.
12641   for (unsigned i = 0; i != NumElts; ++i)
12642     Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12643   return V;
12644 }
12645
12646 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12647   Value *VecOp    = IE.getOperand(0);
12648   Value *ScalarOp = IE.getOperand(1);
12649   Value *IdxOp    = IE.getOperand(2);
12650   
12651   // Inserting an undef or into an undefined place, remove this.
12652   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12653     ReplaceInstUsesWith(IE, VecOp);
12654   
12655   // If the inserted element was extracted from some other vector, and if the 
12656   // indexes are constant, try to turn this into a shufflevector operation.
12657   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12658     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12659         EI->getOperand(0)->getType() == IE.getType()) {
12660       unsigned NumVectorElts = IE.getType()->getNumElements();
12661       unsigned ExtractedIdx =
12662         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12663       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12664       
12665       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12666         return ReplaceInstUsesWith(IE, VecOp);
12667       
12668       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12669         return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
12670       
12671       // If we are extracting a value from a vector, then inserting it right
12672       // back into the same place, just use the input vector.
12673       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12674         return ReplaceInstUsesWith(IE, VecOp);      
12675       
12676       // We could theoretically do this for ANY input.  However, doing so could
12677       // turn chains of insertelement instructions into a chain of shufflevector
12678       // instructions, and right now we do not merge shufflevectors.  As such,
12679       // only do this in a situation where it is clear that there is benefit.
12680       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12681         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12682         // the values of VecOp, except then one read from EIOp0.
12683         // Build a new shuffle mask.
12684         std::vector<Constant*> Mask;
12685         if (isa<UndefValue>(VecOp))
12686           Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
12687         else {
12688           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12689           Mask.assign(NumVectorElts, Context->getConstantInt(Type::Int32Ty,
12690                                                        NumVectorElts));
12691         } 
12692         Mask[InsertedIdx] = 
12693                            Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12694         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12695                                      Context->getConstantVector(Mask));
12696       }
12697       
12698       // If this insertelement isn't used by some other insertelement, turn it
12699       // (and any insertelements it points to), into one big shuffle.
12700       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12701         std::vector<Constant*> Mask;
12702         Value *RHS = 0;
12703         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12704         if (RHS == 0) RHS = Context->getUndef(LHS->getType());
12705         // We now have a shuffle of LHS, RHS, Mask.
12706         return new ShuffleVectorInst(LHS, RHS,
12707                                      Context->getConstantVector(Mask));
12708       }
12709     }
12710   }
12711
12712   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12713   APInt UndefElts(VWidth, 0);
12714   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12715   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12716     return &IE;
12717
12718   return 0;
12719 }
12720
12721
12722 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12723   Value *LHS = SVI.getOperand(0);
12724   Value *RHS = SVI.getOperand(1);
12725   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12726
12727   bool MadeChange = false;
12728
12729   // Undefined shuffle mask -> undefined value.
12730   if (isa<UndefValue>(SVI.getOperand(2)))
12731     return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
12732
12733   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12734
12735   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12736     return 0;
12737
12738   APInt UndefElts(VWidth, 0);
12739   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12740   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12741     LHS = SVI.getOperand(0);
12742     RHS = SVI.getOperand(1);
12743     MadeChange = true;
12744   }
12745   
12746   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12747   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12748   if (LHS == RHS || isa<UndefValue>(LHS)) {
12749     if (isa<UndefValue>(LHS) && LHS == RHS) {
12750       // shuffle(undef,undef,mask) -> undef.
12751       return ReplaceInstUsesWith(SVI, LHS);
12752     }
12753     
12754     // Remap any references to RHS to use LHS.
12755     std::vector<Constant*> Elts;
12756     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12757       if (Mask[i] >= 2*e)
12758         Elts.push_back(Context->getUndef(Type::Int32Ty));
12759       else {
12760         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12761             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12762           Mask[i] = 2*e;     // Turn into undef.
12763           Elts.push_back(Context->getUndef(Type::Int32Ty));
12764         } else {
12765           Mask[i] = Mask[i] % e;  // Force to LHS.
12766           Elts.push_back(Context->getConstantInt(Type::Int32Ty, Mask[i]));
12767         }
12768       }
12769     }
12770     SVI.setOperand(0, SVI.getOperand(1));
12771     SVI.setOperand(1, Context->getUndef(RHS->getType()));
12772     SVI.setOperand(2, Context->getConstantVector(Elts));
12773     LHS = SVI.getOperand(0);
12774     RHS = SVI.getOperand(1);
12775     MadeChange = true;
12776   }
12777   
12778   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12779   bool isLHSID = true, isRHSID = true;
12780     
12781   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12782     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12783     // Is this an identity shuffle of the LHS value?
12784     isLHSID &= (Mask[i] == i);
12785       
12786     // Is this an identity shuffle of the RHS value?
12787     isRHSID &= (Mask[i]-e == i);
12788   }
12789
12790   // Eliminate identity shuffles.
12791   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12792   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12793   
12794   // If the LHS is a shufflevector itself, see if we can combine it with this
12795   // one without producing an unusual shuffle.  Here we are really conservative:
12796   // we are absolutely afraid of producing a shuffle mask not in the input
12797   // program, because the code gen may not be smart enough to turn a merged
12798   // shuffle into two specific shuffles: it may produce worse code.  As such,
12799   // we only merge two shuffles if the result is one of the two input shuffle
12800   // masks.  In this case, merging the shuffles just removes one instruction,
12801   // which we know is safe.  This is good for things like turning:
12802   // (splat(splat)) -> splat.
12803   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12804     if (isa<UndefValue>(RHS)) {
12805       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12806
12807       std::vector<unsigned> NewMask;
12808       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12809         if (Mask[i] >= 2*e)
12810           NewMask.push_back(2*e);
12811         else
12812           NewMask.push_back(LHSMask[Mask[i]]);
12813       
12814       // If the result mask is equal to the src shuffle or this shuffle mask, do
12815       // the replacement.
12816       if (NewMask == LHSMask || NewMask == Mask) {
12817         unsigned LHSInNElts =
12818           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12819         std::vector<Constant*> Elts;
12820         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12821           if (NewMask[i] >= LHSInNElts*2) {
12822             Elts.push_back(Context->getUndef(Type::Int32Ty));
12823           } else {
12824             Elts.push_back(Context->getConstantInt(Type::Int32Ty, NewMask[i]));
12825           }
12826         }
12827         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12828                                      LHSSVI->getOperand(1),
12829                                      Context->getConstantVector(Elts));
12830       }
12831     }
12832   }
12833
12834   return MadeChange ? &SVI : 0;
12835 }
12836
12837
12838
12839
12840 /// TryToSinkInstruction - Try to move the specified instruction from its
12841 /// current block into the beginning of DestBlock, which can only happen if it's
12842 /// safe to move the instruction past all of the instructions between it and the
12843 /// end of its block.
12844 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12845   assert(I->hasOneUse() && "Invariants didn't hold!");
12846
12847   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12848   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12849     return false;
12850
12851   // Do not sink alloca instructions out of the entry block.
12852   if (isa<AllocaInst>(I) && I->getParent() ==
12853         &DestBlock->getParent()->getEntryBlock())
12854     return false;
12855
12856   // We can only sink load instructions if there is nothing between the load and
12857   // the end of block that could change the value.
12858   if (I->mayReadFromMemory()) {
12859     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12860          Scan != E; ++Scan)
12861       if (Scan->mayWriteToMemory())
12862         return false;
12863   }
12864
12865   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12866
12867   CopyPrecedingStopPoint(I, InsertPos);
12868   I->moveBefore(InsertPos);
12869   ++NumSunkInst;
12870   return true;
12871 }
12872
12873
12874 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12875 /// all reachable code to the worklist.
12876 ///
12877 /// This has a couple of tricks to make the code faster and more powerful.  In
12878 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12879 /// them to the worklist (this significantly speeds up instcombine on code where
12880 /// many instructions are dead or constant).  Additionally, if we find a branch
12881 /// whose condition is a known constant, we only visit the reachable successors.
12882 ///
12883 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12884                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12885                                        InstCombiner &IC,
12886                                        const TargetData *TD) {
12887   SmallVector<BasicBlock*, 256> Worklist;
12888   Worklist.push_back(BB);
12889
12890   while (!Worklist.empty()) {
12891     BB = Worklist.back();
12892     Worklist.pop_back();
12893     
12894     // We have now visited this block!  If we've already been here, ignore it.
12895     if (!Visited.insert(BB)) continue;
12896
12897     DbgInfoIntrinsic *DBI_Prev = NULL;
12898     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12899       Instruction *Inst = BBI++;
12900       
12901       // DCE instruction if trivially dead.
12902       if (isInstructionTriviallyDead(Inst)) {
12903         ++NumDeadInst;
12904         DOUT << "IC: DCE: " << *Inst;
12905         Inst->eraseFromParent();
12906         continue;
12907       }
12908       
12909       // ConstantProp instruction if trivially constant.
12910       if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12911         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12912         Inst->replaceAllUsesWith(C);
12913         ++NumConstProp;
12914         Inst->eraseFromParent();
12915         continue;
12916       }
12917      
12918       // If there are two consecutive llvm.dbg.stoppoint calls then
12919       // it is likely that the optimizer deleted code in between these
12920       // two intrinsics. 
12921       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12922       if (DBI_Next) {
12923         if (DBI_Prev
12924             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12925             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12926           IC.RemoveFromWorkList(DBI_Prev);
12927           DBI_Prev->eraseFromParent();
12928         }
12929         DBI_Prev = DBI_Next;
12930       } else {
12931         DBI_Prev = 0;
12932       }
12933
12934       IC.AddToWorkList(Inst);
12935     }
12936
12937     // Recursively visit successors.  If this is a branch or switch on a
12938     // constant, only visit the reachable successor.
12939     TerminatorInst *TI = BB->getTerminator();
12940     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12941       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12942         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12943         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12944         Worklist.push_back(ReachableBB);
12945         continue;
12946       }
12947     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12948       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12949         // See if this is an explicit destination.
12950         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12951           if (SI->getCaseValue(i) == Cond) {
12952             BasicBlock *ReachableBB = SI->getSuccessor(i);
12953             Worklist.push_back(ReachableBB);
12954             continue;
12955           }
12956         
12957         // Otherwise it is the default destination.
12958         Worklist.push_back(SI->getSuccessor(0));
12959         continue;
12960       }
12961     }
12962     
12963     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12964       Worklist.push_back(TI->getSuccessor(i));
12965   }
12966 }
12967
12968 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12969   bool Changed = false;
12970   TD = &getAnalysis<TargetData>();
12971   
12972   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12973              << F.getNameStr() << "\n");
12974
12975   {
12976     // Do a depth-first traversal of the function, populate the worklist with
12977     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12978     // track of which blocks we visit.
12979     SmallPtrSet<BasicBlock*, 64> Visited;
12980     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12981
12982     // Do a quick scan over the function.  If we find any blocks that are
12983     // unreachable, remove any instructions inside of them.  This prevents
12984     // the instcombine code from having to deal with some bad special cases.
12985     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12986       if (!Visited.count(BB)) {
12987         Instruction *Term = BB->getTerminator();
12988         while (Term != BB->begin()) {   // Remove instrs bottom-up
12989           BasicBlock::iterator I = Term; --I;
12990
12991           DOUT << "IC: DCE: " << *I;
12992           // A debug intrinsic shouldn't force another iteration if we weren't
12993           // going to do one without it.
12994           if (!isa<DbgInfoIntrinsic>(I)) {
12995             ++NumDeadInst;
12996             Changed = true;
12997           }
12998           if (!I->use_empty())
12999             I->replaceAllUsesWith(Context->getUndef(I->getType()));
13000           I->eraseFromParent();
13001         }
13002       }
13003   }
13004
13005   while (!Worklist.empty()) {
13006     Instruction *I = RemoveOneFromWorkList();
13007     if (I == 0) continue;  // skip null values.
13008
13009     // Check to see if we can DCE the instruction.
13010     if (isInstructionTriviallyDead(I)) {
13011       // Add operands to the worklist.
13012       if (I->getNumOperands() < 4)
13013         AddUsesToWorkList(*I);
13014       ++NumDeadInst;
13015
13016       DOUT << "IC: DCE: " << *I;
13017
13018       I->eraseFromParent();
13019       RemoveFromWorkList(I);
13020       Changed = true;
13021       continue;
13022     }
13023
13024     // Instruction isn't dead, see if we can constant propagate it.
13025     if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
13026       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
13027
13028       // Add operands to the worklist.
13029       AddUsesToWorkList(*I);
13030       ReplaceInstUsesWith(*I, C);
13031
13032       ++NumConstProp;
13033       I->eraseFromParent();
13034       RemoveFromWorkList(I);
13035       Changed = true;
13036       continue;
13037     }
13038
13039     if (TD) {
13040       // See if we can constant fold its operands.
13041       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13042         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
13043           if (Constant *NewC = ConstantFoldConstantExpression(CE,   
13044                                   F.getContext(), TD))
13045             if (NewC != CE) {
13046               i->set(NewC);
13047               Changed = true;
13048             }
13049     }
13050
13051     // See if we can trivially sink this instruction to a successor basic block.
13052     if (I->hasOneUse()) {
13053       BasicBlock *BB = I->getParent();
13054       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13055       if (UserParent != BB) {
13056         bool UserIsSuccessor = false;
13057         // See if the user is one of our successors.
13058         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13059           if (*SI == UserParent) {
13060             UserIsSuccessor = true;
13061             break;
13062           }
13063
13064         // If the user is one of our immediate successors, and if that successor
13065         // only has us as a predecessors (we'd have to split the critical edge
13066         // otherwise), we can keep going.
13067         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13068             next(pred_begin(UserParent)) == pred_end(UserParent))
13069           // Okay, the CFG is simple enough, try to sink this instruction.
13070           Changed |= TryToSinkInstruction(I, UserParent);
13071       }
13072     }
13073
13074     // Now that we have an instruction, try combining it to simplify it...
13075 #ifndef NDEBUG
13076     std::string OrigI;
13077 #endif
13078     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
13079     if (Instruction *Result = visit(*I)) {
13080       ++NumCombined;
13081       // Should we replace the old instruction with a new one?
13082       if (Result != I) {
13083         DOUT << "IC: Old = " << *I
13084              << "    New = " << *Result;
13085
13086         // Everything uses the new instruction now.
13087         I->replaceAllUsesWith(Result);
13088
13089         // Push the new instruction and any users onto the worklist.
13090         AddToWorkList(Result);
13091         AddUsersToWorkList(*Result);
13092
13093         // Move the name to the new instruction first.
13094         Result->takeName(I);
13095
13096         // Insert the new instruction into the basic block...
13097         BasicBlock *InstParent = I->getParent();
13098         BasicBlock::iterator InsertPos = I;
13099
13100         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
13101           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13102             ++InsertPos;
13103
13104         InstParent->getInstList().insert(InsertPos, Result);
13105
13106         // Make sure that we reprocess all operands now that we reduced their
13107         // use counts.
13108         AddUsesToWorkList(*I);
13109
13110         // Instructions can end up on the worklist more than once.  Make sure
13111         // we do not process an instruction that has been deleted.
13112         RemoveFromWorkList(I);
13113
13114         // Erase the old instruction.
13115         InstParent->getInstList().erase(I);
13116       } else {
13117 #ifndef NDEBUG
13118         DOUT << "IC: Mod = " << OrigI
13119              << "    New = " << *I;
13120 #endif
13121
13122         // If the instruction was modified, it's possible that it is now dead.
13123         // if so, remove it.
13124         if (isInstructionTriviallyDead(I)) {
13125           // Make sure we process all operands now that we are reducing their
13126           // use counts.
13127           AddUsesToWorkList(*I);
13128
13129           // Instructions may end up in the worklist more than once.  Erase all
13130           // occurrences of this instruction.
13131           RemoveFromWorkList(I);
13132           I->eraseFromParent();
13133         } else {
13134           AddToWorkList(I);
13135           AddUsersToWorkList(*I);
13136         }
13137       }
13138       Changed = true;
13139     }
13140   }
13141
13142   assert(WorklistMap.empty() && "Worklist empty, but map not?");
13143     
13144   // Do an explicit clear, this shrinks the map if needed.
13145   WorklistMap.clear();
13146   return Changed;
13147 }
13148
13149
13150 bool InstCombiner::runOnFunction(Function &F) {
13151   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13152   
13153   bool EverMadeChange = false;
13154
13155   // Iterate while there is work to do.
13156   unsigned Iteration = 0;
13157   while (DoOneIteration(F, Iteration++))
13158     EverMadeChange = true;
13159   return EverMadeChange;
13160 }
13161
13162 FunctionPass *llvm::createInstructionCombiningPass() {
13163   return new InstCombiner();
13164 }