Canonicalize boolean +/- a constant to a select.
[oota-llvm.git] / lib / Transforms / Scalar / InstructionCombining.cpp
1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions.  This pass does not modify the CFG.  This pass is where
12 // algebraic simplification happens.
13 //
14 // This pass combines things like:
15 //    %Y = add i32 %X, 1
16 //    %Z = add i32 %Y, 1
17 // into:
18 //    %Z = add i32 %X, 2
19 //
20 // This is a simple worklist driven algorithm.
21 //
22 // This pass guarantees that the following canonicalizations are performed on
23 // the program:
24 //    1. If a binary operator has a constant operand, it is moved to the RHS
25 //    2. Bitwise operators with constant operands are always grouped so that
26 //       shifts are performed first, then or's, then and's, then xor's.
27 //    3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All cmp instructions on boolean values are replaced with logical ops
29 //    5. add X, X is represented as (X*2) => (X << 1)
30 //    6. Multiplies with a power-of-two constant argument are transformed into
31 //       shifts.
32 //   ... etc.
33 //
34 //===----------------------------------------------------------------------===//
35
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/LLVMContext.h"
40 #include "llvm/Pass.h"
41 #include "llvm/DerivedTypes.h"
42 #include "llvm/GlobalVariable.h"
43 #include "llvm/Analysis/ConstantFolding.h"
44 #include "llvm/Analysis/ValueTracking.h"
45 #include "llvm/Target/TargetData.h"
46 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
47 #include "llvm/Transforms/Utils/Local.h"
48 #include "llvm/Support/CallSite.h"
49 #include "llvm/Support/ConstantRange.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/GetElementPtrTypeIterator.h"
53 #include "llvm/Support/InstVisitor.h"
54 #include "llvm/Support/MathExtras.h"
55 #include "llvm/Support/PatternMatch.h"
56 #include "llvm/Support/Compiler.h"
57 #include "llvm/ADT/DenseMap.h"
58 #include "llvm/ADT/SmallVector.h"
59 #include "llvm/ADT/SmallPtrSet.h"
60 #include "llvm/ADT/Statistic.h"
61 #include "llvm/ADT/STLExtras.h"
62 #include <algorithm>
63 #include <climits>
64 #include <sstream>
65 using namespace llvm;
66 using namespace llvm::PatternMatch;
67
68 STATISTIC(NumCombined , "Number of insts combined");
69 STATISTIC(NumConstProp, "Number of constant folds");
70 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
71 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
72 STATISTIC(NumSunkInst , "Number of instructions sunk");
73
74 namespace {
75   class VISIBILITY_HIDDEN InstCombiner
76     : public FunctionPass,
77       public InstVisitor<InstCombiner, Instruction*> {
78     // Worklist of all of the instructions that need to be simplified.
79     SmallVector<Instruction*, 256> Worklist;
80     DenseMap<Instruction*, unsigned> WorklistMap;
81     TargetData *TD;
82     bool MustPreserveLCSSA;
83   public:
84     static char ID; // Pass identification, replacement for typeid
85     InstCombiner() : FunctionPass(&ID) {}
86
87     LLVMContext *getContext() { return Context; }
88
89     /// AddToWorkList - Add the specified instruction to the worklist if it
90     /// isn't already in it.
91     void AddToWorkList(Instruction *I) {
92       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
93         Worklist.push_back(I);
94     }
95     
96     // RemoveFromWorkList - remove I from the worklist if it exists.
97     void RemoveFromWorkList(Instruction *I) {
98       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
99       if (It == WorklistMap.end()) return; // Not in worklist.
100       
101       // Don't bother moving everything down, just null out the slot.
102       Worklist[It->second] = 0;
103       
104       WorklistMap.erase(It);
105     }
106     
107     Instruction *RemoveOneFromWorkList() {
108       Instruction *I = Worklist.back();
109       Worklist.pop_back();
110       WorklistMap.erase(I);
111       return I;
112     }
113
114     
115     /// AddUsersToWorkList - When an instruction is simplified, add all users of
116     /// the instruction to the work lists because they might get more simplified
117     /// now.
118     ///
119     void AddUsersToWorkList(Value &I) {
120       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
121            UI != UE; ++UI)
122         AddToWorkList(cast<Instruction>(*UI));
123     }
124
125     /// AddUsesToWorkList - When an instruction is simplified, add operands to
126     /// the work lists because they might get more simplified now.
127     ///
128     void AddUsesToWorkList(Instruction &I) {
129       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
130         if (Instruction *Op = dyn_cast<Instruction>(*i))
131           AddToWorkList(Op);
132     }
133     
134     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
135     /// dead.  Add all of its operands to the worklist, turning them into
136     /// undef's to reduce the number of uses of those instructions.
137     ///
138     /// Return the specified operand before it is turned into an undef.
139     ///
140     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
141       Value *R = I.getOperand(op);
142       
143       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
144         if (Instruction *Op = dyn_cast<Instruction>(*i)) {
145           AddToWorkList(Op);
146           // Set the operand to undef to drop the use.
147           *i = Context->getUndef(Op->getType());
148         }
149       
150       return R;
151     }
152
153   public:
154     virtual bool runOnFunction(Function &F);
155     
156     bool DoOneIteration(Function &F, unsigned ItNum);
157
158     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
159       AU.addRequired<TargetData>();
160       AU.addPreservedID(LCSSAID);
161       AU.setPreservesCFG();
162     }
163
164     TargetData &getTargetData() const { return *TD; }
165
166     // Visitation implementation - Implement instruction combining for different
167     // instruction types.  The semantics are as follows:
168     // Return Value:
169     //    null        - No change was made
170     //     I          - Change was made, I is still valid, I may be dead though
171     //   otherwise    - Change was made, replace I with returned instruction
172     //
173     Instruction *visitAdd(BinaryOperator &I);
174     Instruction *visitFAdd(BinaryOperator &I);
175     Instruction *visitSub(BinaryOperator &I);
176     Instruction *visitFSub(BinaryOperator &I);
177     Instruction *visitMul(BinaryOperator &I);
178     Instruction *visitFMul(BinaryOperator &I);
179     Instruction *visitURem(BinaryOperator &I);
180     Instruction *visitSRem(BinaryOperator &I);
181     Instruction *visitFRem(BinaryOperator &I);
182     bool SimplifyDivRemOfSelect(BinaryOperator &I);
183     Instruction *commonRemTransforms(BinaryOperator &I);
184     Instruction *commonIRemTransforms(BinaryOperator &I);
185     Instruction *commonDivTransforms(BinaryOperator &I);
186     Instruction *commonIDivTransforms(BinaryOperator &I);
187     Instruction *visitUDiv(BinaryOperator &I);
188     Instruction *visitSDiv(BinaryOperator &I);
189     Instruction *visitFDiv(BinaryOperator &I);
190     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
191     Instruction *visitAnd(BinaryOperator &I);
192     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
193     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
194                                      Value *A, Value *B, Value *C);
195     Instruction *visitOr (BinaryOperator &I);
196     Instruction *visitXor(BinaryOperator &I);
197     Instruction *visitShl(BinaryOperator &I);
198     Instruction *visitAShr(BinaryOperator &I);
199     Instruction *visitLShr(BinaryOperator &I);
200     Instruction *commonShiftTransforms(BinaryOperator &I);
201     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
202                                       Constant *RHSC);
203     Instruction *visitFCmpInst(FCmpInst &I);
204     Instruction *visitICmpInst(ICmpInst &I);
205     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
206     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
207                                                 Instruction *LHS,
208                                                 ConstantInt *RHS);
209     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
210                                 ConstantInt *DivRHS);
211
212     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
213                              ICmpInst::Predicate Cond, Instruction &I);
214     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
215                                      BinaryOperator &I);
216     Instruction *commonCastTransforms(CastInst &CI);
217     Instruction *commonIntCastTransforms(CastInst &CI);
218     Instruction *commonPointerCastTransforms(CastInst &CI);
219     Instruction *visitTrunc(TruncInst &CI);
220     Instruction *visitZExt(ZExtInst &CI);
221     Instruction *visitSExt(SExtInst &CI);
222     Instruction *visitFPTrunc(FPTruncInst &CI);
223     Instruction *visitFPExt(CastInst &CI);
224     Instruction *visitFPToUI(FPToUIInst &FI);
225     Instruction *visitFPToSI(FPToSIInst &FI);
226     Instruction *visitUIToFP(CastInst &CI);
227     Instruction *visitSIToFP(CastInst &CI);
228     Instruction *visitPtrToInt(PtrToIntInst &CI);
229     Instruction *visitIntToPtr(IntToPtrInst &CI);
230     Instruction *visitBitCast(BitCastInst &CI);
231     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
232                                 Instruction *FI);
233     Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
234     Instruction *visitSelectInst(SelectInst &SI);
235     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
236     Instruction *visitCallInst(CallInst &CI);
237     Instruction *visitInvokeInst(InvokeInst &II);
238     Instruction *visitPHINode(PHINode &PN);
239     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
240     Instruction *visitAllocationInst(AllocationInst &AI);
241     Instruction *visitFreeInst(FreeInst &FI);
242     Instruction *visitLoadInst(LoadInst &LI);
243     Instruction *visitStoreInst(StoreInst &SI);
244     Instruction *visitBranchInst(BranchInst &BI);
245     Instruction *visitSwitchInst(SwitchInst &SI);
246     Instruction *visitInsertElementInst(InsertElementInst &IE);
247     Instruction *visitExtractElementInst(ExtractElementInst &EI);
248     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
249     Instruction *visitExtractValueInst(ExtractValueInst &EV);
250
251     // visitInstruction - Specify what to return for unhandled instructions...
252     Instruction *visitInstruction(Instruction &I) { return 0; }
253
254   private:
255     Instruction *visitCallSite(CallSite CS);
256     bool transformConstExprCastCall(CallSite CS);
257     Instruction *transformCallThroughTrampoline(CallSite CS);
258     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
259                                    bool DoXform = true);
260     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
261     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
262
263
264   public:
265     // InsertNewInstBefore - insert an instruction New before instruction Old
266     // in the program.  Add the new instruction to the worklist.
267     //
268     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
269       assert(New && New->getParent() == 0 &&
270              "New instruction already inserted into a basic block!");
271       BasicBlock *BB = Old.getParent();
272       BB->getInstList().insert(&Old, New);  // Insert inst
273       AddToWorkList(New);
274       return New;
275     }
276
277     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
278     /// This also adds the cast to the worklist.  Finally, this returns the
279     /// cast.
280     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
281                             Instruction &Pos) {
282       if (V->getType() == Ty) return V;
283
284       if (Constant *CV = dyn_cast<Constant>(V))
285         return Context->getConstantExprCast(opc, CV, Ty);
286       
287       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
288       AddToWorkList(C);
289       return C;
290     }
291         
292     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
293       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
294     }
295
296
297     // ReplaceInstUsesWith - This method is to be used when an instruction is
298     // found to be dead, replacable with another preexisting expression.  Here
299     // we add all uses of I to the worklist, replace all uses of I with the new
300     // value, then return I, so that the inst combiner will know that I was
301     // modified.
302     //
303     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
304       AddUsersToWorkList(I);         // Add all modified instrs to worklist
305       if (&I != V) {
306         I.replaceAllUsesWith(V);
307         return &I;
308       } else {
309         // If we are replacing the instruction with itself, this must be in a
310         // segment of unreachable code, so just clobber the instruction.
311         I.replaceAllUsesWith(Context->getUndef(I.getType()));
312         return &I;
313       }
314     }
315
316     // EraseInstFromFunction - When dealing with an instruction that has side
317     // effects or produces a void value, we can't rely on DCE to delete the
318     // instruction.  Instead, visit methods should return the value returned by
319     // this function.
320     Instruction *EraseInstFromFunction(Instruction &I) {
321       assert(I.use_empty() && "Cannot erase instruction that is used!");
322       AddUsesToWorkList(I);
323       RemoveFromWorkList(&I);
324       I.eraseFromParent();
325       return 0;  // Don't do anything with FI
326     }
327         
328     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
329                            APInt &KnownOne, unsigned Depth = 0) const {
330       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
331     }
332     
333     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
334                            unsigned Depth = 0) const {
335       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
336     }
337     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
338       return llvm::ComputeNumSignBits(Op, TD, Depth);
339     }
340
341   private:
342
343     /// SimplifyCommutative - This performs a few simplifications for 
344     /// commutative operators.
345     bool SimplifyCommutative(BinaryOperator &I);
346
347     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
348     /// most-complex to least-complex order.
349     bool SimplifyCompare(CmpInst &I);
350
351     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
352     /// based on the demanded bits.
353     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
354                                    APInt& KnownZero, APInt& KnownOne,
355                                    unsigned Depth);
356     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
357                               APInt& KnownZero, APInt& KnownOne,
358                               unsigned Depth=0);
359         
360     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
361     /// SimplifyDemandedBits knows about.  See if the instruction has any
362     /// properties that allow us to simplify its operands.
363     bool SimplifyDemandedInstructionBits(Instruction &Inst);
364         
365     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
366                                       APInt& UndefElts, unsigned Depth = 0);
367       
368     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
369     // PHI node as operand #0, see if we can fold the instruction into the PHI
370     // (which is only possible if all operands to the PHI are constants).
371     Instruction *FoldOpIntoPhi(Instruction &I);
372
373     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
374     // operator and they all are only used by the PHI, PHI together their
375     // inputs, and do the operation once, to the result of the PHI.
376     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
377     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
378     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
379
380     
381     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
382                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
383     
384     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
385                               bool isSub, Instruction &I);
386     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
387                                  bool isSigned, bool Inside, Instruction &IB);
388     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
389     Instruction *MatchBSwap(BinaryOperator &I);
390     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
391     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
392     Instruction *SimplifyMemSet(MemSetInst *MI);
393
394
395     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
396
397     bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
398                                     unsigned CastOpc, int &NumCastsRemoved);
399     unsigned GetOrEnforceKnownAlignment(Value *V,
400                                         unsigned PrefAlign = 0);
401
402   };
403 }
404
405 char InstCombiner::ID = 0;
406 static RegisterPass<InstCombiner>
407 X("instcombine", "Combine redundant instructions");
408
409 // getComplexity:  Assign a complexity or rank value to LLVM Values...
410 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
411 static unsigned getComplexity(LLVMContext *Context, Value *V) {
412   if (isa<Instruction>(V)) {
413     if (BinaryOperator::isNeg(V) ||
414         BinaryOperator::isFNeg(V) ||
415         BinaryOperator::isNot(V))
416       return 3;
417     return 4;
418   }
419   if (isa<Argument>(V)) return 3;
420   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
421 }
422
423 // isOnlyUse - Return true if this instruction will be deleted if we stop using
424 // it.
425 static bool isOnlyUse(Value *V) {
426   return V->hasOneUse() || isa<Constant>(V);
427 }
428
429 // getPromotedType - Return the specified type promoted as it would be to pass
430 // though a va_arg area...
431 static const Type *getPromotedType(const Type *Ty) {
432   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
433     if (ITy->getBitWidth() < 32)
434       return Type::Int32Ty;
435   }
436   return Ty;
437 }
438
439 /// getBitCastOperand - If the specified operand is a CastInst, a constant
440 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
441 /// operand value, otherwise return null.
442 static Value *getBitCastOperand(Value *V) {
443   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
444     // BitCastInst?
445     return I->getOperand(0);
446   else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
447     // GetElementPtrInst?
448     if (GEP->hasAllZeroIndices())
449       return GEP->getOperand(0);
450   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
451     if (CE->getOpcode() == Instruction::BitCast)
452       // BitCast ConstantExp?
453       return CE->getOperand(0);
454     else if (CE->getOpcode() == Instruction::GetElementPtr) {
455       // GetElementPtr ConstantExp?
456       for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
457            I != E; ++I) {
458         ConstantInt *CI = dyn_cast<ConstantInt>(I);
459         if (!CI || !CI->isZero())
460           // Any non-zero indices? Not cast-like.
461           return 0;
462       }
463       // All-zero indices? This is just like casting.
464       return CE->getOperand(0);
465     }
466   }
467   return 0;
468 }
469
470 /// This function is a wrapper around CastInst::isEliminableCastPair. It
471 /// simply extracts arguments and returns what that function returns.
472 static Instruction::CastOps 
473 isEliminableCastPair(
474   const CastInst *CI, ///< The first cast instruction
475   unsigned opcode,       ///< The opcode of the second cast instruction
476   const Type *DstTy,     ///< The target type for the second cast instruction
477   TargetData *TD         ///< The target data for pointer size
478 ) {
479   
480   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
481   const Type *MidTy = CI->getType();                  // B from above
482
483   // Get the opcodes of the two Cast instructions
484   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
485   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
486
487   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
488                                                 DstTy, TD->getIntPtrType());
489   
490   // We don't want to form an inttoptr or ptrtoint that converts to an integer
491   // type that differs from the pointer size.
492   if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
493       (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
494     Res = 0;
495   
496   return Instruction::CastOps(Res);
497 }
498
499 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
500 /// in any code being generated.  It does not require codegen if V is simple
501 /// enough or if the cast can be folded into other casts.
502 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
503                               const Type *Ty, TargetData *TD) {
504   if (V->getType() == Ty || isa<Constant>(V)) return false;
505   
506   // If this is another cast that can be eliminated, it isn't codegen either.
507   if (const CastInst *CI = dyn_cast<CastInst>(V))
508     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
509       return false;
510   return true;
511 }
512
513 // SimplifyCommutative - This performs a few simplifications for commutative
514 // operators:
515 //
516 //  1. Order operands such that they are listed from right (least complex) to
517 //     left (most complex).  This puts constants before unary operators before
518 //     binary operators.
519 //
520 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
521 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
522 //
523 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
524   bool Changed = false;
525   if (getComplexity(Context, I.getOperand(0)) < 
526       getComplexity(Context, I.getOperand(1)))
527     Changed = !I.swapOperands();
528
529   if (!I.isAssociative()) return Changed;
530   Instruction::BinaryOps Opcode = I.getOpcode();
531   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
532     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
533       if (isa<Constant>(I.getOperand(1))) {
534         Constant *Folded = Context->getConstantExpr(I.getOpcode(),
535                                              cast<Constant>(I.getOperand(1)),
536                                              cast<Constant>(Op->getOperand(1)));
537         I.setOperand(0, Op->getOperand(0));
538         I.setOperand(1, Folded);
539         return true;
540       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
541         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
542             isOnlyUse(Op) && isOnlyUse(Op1)) {
543           Constant *C1 = cast<Constant>(Op->getOperand(1));
544           Constant *C2 = cast<Constant>(Op1->getOperand(1));
545
546           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
547           Constant *Folded = Context->getConstantExpr(I.getOpcode(), C1, C2);
548           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
549                                                     Op1->getOperand(0),
550                                                     Op1->getName(), &I);
551           AddToWorkList(New);
552           I.setOperand(0, New);
553           I.setOperand(1, Folded);
554           return true;
555         }
556     }
557   return Changed;
558 }
559
560 /// SimplifyCompare - For a CmpInst this function just orders the operands
561 /// so that theyare listed from right (least complex) to left (most complex).
562 /// This puts constants before unary operators before binary operators.
563 bool InstCombiner::SimplifyCompare(CmpInst &I) {
564   if (getComplexity(Context, I.getOperand(0)) >=
565       getComplexity(Context, I.getOperand(1)))
566     return false;
567   I.swapOperands();
568   // Compare instructions are not associative so there's nothing else we can do.
569   return true;
570 }
571
572 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
573 // if the LHS is a constant zero (which is the 'negate' form).
574 //
575 static inline Value *dyn_castNegVal(Value *V, LLVMContext *Context) {
576   if (BinaryOperator::isNeg(V))
577     return BinaryOperator::getNegArgument(V);
578
579   // Constants can be considered to be negated values if they can be folded.
580   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
581     return Context->getConstantExprNeg(C);
582
583   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
584     if (C->getType()->getElementType()->isInteger())
585       return Context->getConstantExprNeg(C);
586
587   return 0;
588 }
589
590 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
591 // instruction if the LHS is a constant negative zero (which is the 'negate'
592 // form).
593 //
594 static inline Value *dyn_castFNegVal(Value *V, LLVMContext *Context) {
595   if (BinaryOperator::isFNeg(V))
596     return BinaryOperator::getFNegArgument(V);
597
598   // Constants can be considered to be negated values if they can be folded.
599   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
600     return Context->getConstantExprFNeg(C);
601
602   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
603     if (C->getType()->getElementType()->isFloatingPoint())
604       return Context->getConstantExprFNeg(C);
605
606   return 0;
607 }
608
609 static inline Value *dyn_castNotVal(Value *V, LLVMContext *Context) {
610   if (BinaryOperator::isNot(V))
611     return BinaryOperator::getNotArgument(V);
612
613   // Constants can be considered to be not'ed values...
614   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
615     return Context->getConstantInt(~C->getValue());
616   return 0;
617 }
618
619 // dyn_castFoldableMul - If this value is a multiply that can be folded into
620 // other computations (because it has a constant operand), return the
621 // non-constant operand of the multiply, and set CST to point to the multiplier.
622 // Otherwise, return null.
623 //
624 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST,
625                                          LLVMContext *Context) {
626   if (V->hasOneUse() && V->getType()->isInteger())
627     if (Instruction *I = dyn_cast<Instruction>(V)) {
628       if (I->getOpcode() == Instruction::Mul)
629         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
630           return I->getOperand(0);
631       if (I->getOpcode() == Instruction::Shl)
632         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
633           // The multiplier is really 1 << CST.
634           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
635           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
636           CST = Context->getConstantInt(APInt(BitWidth, 1).shl(CSTVal));
637           return I->getOperand(0);
638         }
639     }
640   return 0;
641 }
642
643 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
644 /// expression, return it.
645 static User *dyn_castGetElementPtr(Value *V) {
646   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
647   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
648     if (CE->getOpcode() == Instruction::GetElementPtr)
649       return cast<User>(V);
650   return false;
651 }
652
653 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
654 /// opcode value. Otherwise return UserOp1.
655 static unsigned getOpcode(const Value *V) {
656   if (const Instruction *I = dyn_cast<Instruction>(V))
657     return I->getOpcode();
658   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
659     return CE->getOpcode();
660   // Use UserOp1 to mean there's no opcode.
661   return Instruction::UserOp1;
662 }
663
664 /// AddOne - Add one to a ConstantInt
665 static Constant *AddOne(Constant *C, LLVMContext *Context) {
666   return Context->getConstantExprAdd(C, 
667     Context->getConstantInt(C->getType(), 1));
668 }
669 /// SubOne - Subtract one from a ConstantInt
670 static Constant *SubOne(ConstantInt *C, LLVMContext *Context) {
671   return Context->getConstantExprSub(C, 
672     Context->getConstantInt(C->getType(), 1));
673 }
674 /// MultiplyOverflows - True if the multiply can not be expressed in an int
675 /// this size.
676 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign,
677                               LLVMContext *Context) {
678   uint32_t W = C1->getBitWidth();
679   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
680   if (sign) {
681     LHSExt.sext(W * 2);
682     RHSExt.sext(W * 2);
683   } else {
684     LHSExt.zext(W * 2);
685     RHSExt.zext(W * 2);
686   }
687
688   APInt MulExt = LHSExt * RHSExt;
689
690   if (sign) {
691     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
692     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
693     return MulExt.slt(Min) || MulExt.sgt(Max);
694   } else 
695     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
696 }
697
698
699 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
700 /// specified instruction is a constant integer.  If so, check to see if there
701 /// are any bits set in the constant that are not demanded.  If so, shrink the
702 /// constant and return true.
703 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
704                                    APInt Demanded, LLVMContext *Context) {
705   assert(I && "No instruction?");
706   assert(OpNo < I->getNumOperands() && "Operand index too large");
707
708   // If the operand is not a constant integer, nothing to do.
709   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
710   if (!OpC) return false;
711
712   // If there are no bits set that aren't demanded, nothing to do.
713   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
714   if ((~Demanded & OpC->getValue()) == 0)
715     return false;
716
717   // This instruction is producing bits that are not demanded. Shrink the RHS.
718   Demanded &= OpC->getValue();
719   I->setOperand(OpNo, Context->getConstantInt(Demanded));
720   return true;
721 }
722
723 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
724 // set of known zero and one bits, compute the maximum and minimum values that
725 // could have the specified known zero and known one bits, returning them in
726 // min/max.
727 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
728                                                    const APInt& KnownOne,
729                                                    APInt& Min, APInt& Max) {
730   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
731          KnownZero.getBitWidth() == Min.getBitWidth() &&
732          KnownZero.getBitWidth() == Max.getBitWidth() &&
733          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
734   APInt UnknownBits = ~(KnownZero|KnownOne);
735
736   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
737   // bit if it is unknown.
738   Min = KnownOne;
739   Max = KnownOne|UnknownBits;
740   
741   if (UnknownBits.isNegative()) { // Sign bit is unknown
742     Min.set(Min.getBitWidth()-1);
743     Max.clear(Max.getBitWidth()-1);
744   }
745 }
746
747 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
748 // a set of known zero and one bits, compute the maximum and minimum values that
749 // could have the specified known zero and known one bits, returning them in
750 // min/max.
751 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
752                                                      const APInt &KnownOne,
753                                                      APInt &Min, APInt &Max) {
754   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
755          KnownZero.getBitWidth() == Min.getBitWidth() &&
756          KnownZero.getBitWidth() == Max.getBitWidth() &&
757          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
758   APInt UnknownBits = ~(KnownZero|KnownOne);
759   
760   // The minimum value is when the unknown bits are all zeros.
761   Min = KnownOne;
762   // The maximum value is when the unknown bits are all ones.
763   Max = KnownOne|UnknownBits;
764 }
765
766 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
767 /// SimplifyDemandedBits knows about.  See if the instruction has any
768 /// properties that allow us to simplify its operands.
769 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
770   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
771   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
772   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
773   
774   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
775                                      KnownZero, KnownOne, 0);
776   if (V == 0) return false;
777   if (V == &Inst) return true;
778   ReplaceInstUsesWith(Inst, V);
779   return true;
780 }
781
782 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
783 /// specified instruction operand if possible, updating it in place.  It returns
784 /// true if it made any change and false otherwise.
785 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
786                                         APInt &KnownZero, APInt &KnownOne,
787                                         unsigned Depth) {
788   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
789                                           KnownZero, KnownOne, Depth);
790   if (NewVal == 0) return false;
791   U.set(NewVal);
792   return true;
793 }
794
795
796 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
797 /// value based on the demanded bits.  When this function is called, it is known
798 /// that only the bits set in DemandedMask of the result of V are ever used
799 /// downstream. Consequently, depending on the mask and V, it may be possible
800 /// to replace V with a constant or one of its operands. In such cases, this
801 /// function does the replacement and returns true. In all other cases, it
802 /// returns false after analyzing the expression and setting KnownOne and known
803 /// to be one in the expression.  KnownZero contains all the bits that are known
804 /// to be zero in the expression. These are provided to potentially allow the
805 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
806 /// the expression. KnownOne and KnownZero always follow the invariant that 
807 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
808 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
809 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
810 /// and KnownOne must all be the same.
811 ///
812 /// This returns null if it did not change anything and it permits no
813 /// simplification.  This returns V itself if it did some simplification of V's
814 /// operands based on the information about what bits are demanded. This returns
815 /// some other non-null value if it found out that V is equal to another value
816 /// in the context where the specified bits are demanded, but not for all users.
817 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
818                                              APInt &KnownZero, APInt &KnownOne,
819                                              unsigned Depth) {
820   assert(V != 0 && "Null pointer of Value???");
821   assert(Depth <= 6 && "Limit Search Depth");
822   uint32_t BitWidth = DemandedMask.getBitWidth();
823   const Type *VTy = V->getType();
824   assert((TD || !isa<PointerType>(VTy)) &&
825          "SimplifyDemandedBits needs to know bit widths!");
826   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
827          (!VTy->isIntOrIntVector() ||
828           VTy->getScalarSizeInBits() == BitWidth) &&
829          KnownZero.getBitWidth() == BitWidth &&
830          KnownOne.getBitWidth() == BitWidth &&
831          "Value *V, DemandedMask, KnownZero and KnownOne "
832          "must have same BitWidth");
833   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
834     // We know all of the bits for a constant!
835     KnownOne = CI->getValue() & DemandedMask;
836     KnownZero = ~KnownOne & DemandedMask;
837     return 0;
838   }
839   if (isa<ConstantPointerNull>(V)) {
840     // We know all of the bits for a constant!
841     KnownOne.clear();
842     KnownZero = DemandedMask;
843     return 0;
844   }
845
846   KnownZero.clear();
847   KnownOne.clear();
848   if (DemandedMask == 0) {   // Not demanding any bits from V.
849     if (isa<UndefValue>(V))
850       return 0;
851     return Context->getUndef(VTy);
852   }
853   
854   if (Depth == 6)        // Limit search depth.
855     return 0;
856   
857   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
858   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
859
860   Instruction *I = dyn_cast<Instruction>(V);
861   if (!I) {
862     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
863     return 0;        // Only analyze instructions.
864   }
865
866   // If there are multiple uses of this value and we aren't at the root, then
867   // we can't do any simplifications of the operands, because DemandedMask
868   // only reflects the bits demanded by *one* of the users.
869   if (Depth != 0 && !I->hasOneUse()) {
870     // Despite the fact that we can't simplify this instruction in all User's
871     // context, we can at least compute the knownzero/knownone bits, and we can
872     // do simplifications that apply to *just* the one user if we know that
873     // this instruction has a simpler value in that context.
874     if (I->getOpcode() == Instruction::And) {
875       // If either the LHS or the RHS are Zero, the result is zero.
876       ComputeMaskedBits(I->getOperand(1), DemandedMask,
877                         RHSKnownZero, RHSKnownOne, Depth+1);
878       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
879                         LHSKnownZero, LHSKnownOne, Depth+1);
880       
881       // If all of the demanded bits are known 1 on one side, return the other.
882       // These bits cannot contribute to the result of the 'and' in this
883       // context.
884       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
885           (DemandedMask & ~LHSKnownZero))
886         return I->getOperand(0);
887       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
888           (DemandedMask & ~RHSKnownZero))
889         return I->getOperand(1);
890       
891       // If all of the demanded bits in the inputs are known zeros, return zero.
892       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
893         return Context->getNullValue(VTy);
894       
895     } else if (I->getOpcode() == Instruction::Or) {
896       // We can simplify (X|Y) -> X or Y in the user's context if we know that
897       // only bits from X or Y are demanded.
898       
899       // If either the LHS or the RHS are One, the result is One.
900       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
901                         RHSKnownZero, RHSKnownOne, Depth+1);
902       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
903                         LHSKnownZero, LHSKnownOne, Depth+1);
904       
905       // If all of the demanded bits are known zero on one side, return the
906       // other.  These bits cannot contribute to the result of the 'or' in this
907       // context.
908       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
909           (DemandedMask & ~LHSKnownOne))
910         return I->getOperand(0);
911       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
912           (DemandedMask & ~RHSKnownOne))
913         return I->getOperand(1);
914       
915       // If all of the potentially set bits on one side are known to be set on
916       // the other side, just use the 'other' side.
917       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
918           (DemandedMask & (~RHSKnownZero)))
919         return I->getOperand(0);
920       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
921           (DemandedMask & (~LHSKnownZero)))
922         return I->getOperand(1);
923     }
924     
925     // Compute the KnownZero/KnownOne bits to simplify things downstream.
926     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
927     return 0;
928   }
929   
930   // If this is the root being simplified, allow it to have multiple uses,
931   // just set the DemandedMask to all bits so that we can try to simplify the
932   // operands.  This allows visitTruncInst (for example) to simplify the
933   // operand of a trunc without duplicating all the logic below.
934   if (Depth == 0 && !V->hasOneUse())
935     DemandedMask = APInt::getAllOnesValue(BitWidth);
936   
937   switch (I->getOpcode()) {
938   default:
939     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
940     break;
941   case Instruction::And:
942     // If either the LHS or the RHS are Zero, the result is zero.
943     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
944                              RHSKnownZero, RHSKnownOne, Depth+1) ||
945         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
946                              LHSKnownZero, LHSKnownOne, Depth+1))
947       return I;
948     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
949     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
950
951     // If all of the demanded bits are known 1 on one side, return the other.
952     // These bits cannot contribute to the result of the 'and'.
953     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
954         (DemandedMask & ~LHSKnownZero))
955       return I->getOperand(0);
956     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
957         (DemandedMask & ~RHSKnownZero))
958       return I->getOperand(1);
959     
960     // If all of the demanded bits in the inputs are known zeros, return zero.
961     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
962       return Context->getNullValue(VTy);
963       
964     // If the RHS is a constant, see if we can simplify it.
965     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero, Context))
966       return I;
967       
968     // Output known-1 bits are only known if set in both the LHS & RHS.
969     RHSKnownOne &= LHSKnownOne;
970     // Output known-0 are known to be clear if zero in either the LHS | RHS.
971     RHSKnownZero |= LHSKnownZero;
972     break;
973   case Instruction::Or:
974     // If either the LHS or the RHS are One, the result is One.
975     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
976                              RHSKnownZero, RHSKnownOne, Depth+1) ||
977         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
978                              LHSKnownZero, LHSKnownOne, Depth+1))
979       return I;
980     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
981     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
982     
983     // If all of the demanded bits are known zero on one side, return the other.
984     // These bits cannot contribute to the result of the 'or'.
985     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
986         (DemandedMask & ~LHSKnownOne))
987       return I->getOperand(0);
988     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
989         (DemandedMask & ~RHSKnownOne))
990       return I->getOperand(1);
991
992     // If all of the potentially set bits on one side are known to be set on
993     // the other side, just use the 'other' side.
994     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
995         (DemandedMask & (~RHSKnownZero)))
996       return I->getOperand(0);
997     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
998         (DemandedMask & (~LHSKnownZero)))
999       return I->getOperand(1);
1000         
1001     // If the RHS is a constant, see if we can simplify it.
1002     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
1003       return I;
1004           
1005     // Output known-0 bits are only known if clear in both the LHS & RHS.
1006     RHSKnownZero &= LHSKnownZero;
1007     // Output known-1 are known to be set if set in either the LHS | RHS.
1008     RHSKnownOne |= LHSKnownOne;
1009     break;
1010   case Instruction::Xor: {
1011     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1012                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1013         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1014                              LHSKnownZero, LHSKnownOne, Depth+1))
1015       return I;
1016     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1017     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1018     
1019     // If all of the demanded bits are known zero on one side, return the other.
1020     // These bits cannot contribute to the result of the 'xor'.
1021     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1022       return I->getOperand(0);
1023     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1024       return I->getOperand(1);
1025     
1026     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1027     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1028                          (RHSKnownOne & LHSKnownOne);
1029     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1030     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1031                         (RHSKnownOne & LHSKnownZero);
1032     
1033     // If all of the demanded bits are known to be zero on one side or the
1034     // other, turn this into an *inclusive* or.
1035     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1036     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1037       Instruction *Or =
1038         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1039                                  I->getName());
1040       return InsertNewInstBefore(Or, *I);
1041     }
1042     
1043     // If all of the demanded bits on one side are known, and all of the set
1044     // bits on that side are also known to be set on the other side, turn this
1045     // into an AND, as we know the bits will be cleared.
1046     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1047     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1048       // all known
1049       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1050         Constant *AndC = Context->getConstantInt(~RHSKnownOne & DemandedMask);
1051         Instruction *And = 
1052           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1053         return InsertNewInstBefore(And, *I);
1054       }
1055     }
1056     
1057     // If the RHS is a constant, see if we can simplify it.
1058     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1059     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
1060       return I;
1061     
1062     RHSKnownZero = KnownZeroOut;
1063     RHSKnownOne  = KnownOneOut;
1064     break;
1065   }
1066   case Instruction::Select:
1067     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1068                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1069         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1070                              LHSKnownZero, LHSKnownOne, Depth+1))
1071       return I;
1072     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1073     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1074     
1075     // If the operands are constants, see if we can simplify them.
1076     if (ShrinkDemandedConstant(I, 1, DemandedMask, Context) ||
1077         ShrinkDemandedConstant(I, 2, DemandedMask, Context))
1078       return I;
1079     
1080     // Only known if known in both the LHS and RHS.
1081     RHSKnownOne &= LHSKnownOne;
1082     RHSKnownZero &= LHSKnownZero;
1083     break;
1084   case Instruction::Trunc: {
1085     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1086     DemandedMask.zext(truncBf);
1087     RHSKnownZero.zext(truncBf);
1088     RHSKnownOne.zext(truncBf);
1089     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1090                              RHSKnownZero, RHSKnownOne, Depth+1))
1091       return I;
1092     DemandedMask.trunc(BitWidth);
1093     RHSKnownZero.trunc(BitWidth);
1094     RHSKnownOne.trunc(BitWidth);
1095     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1096     break;
1097   }
1098   case Instruction::BitCast:
1099     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1100       return false;  // vector->int or fp->int?
1101
1102     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1103       if (const VectorType *SrcVTy =
1104             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1105         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1106           // Don't touch a bitcast between vectors of different element counts.
1107           return false;
1108       } else
1109         // Don't touch a scalar-to-vector bitcast.
1110         return false;
1111     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1112       // Don't touch a vector-to-scalar bitcast.
1113       return false;
1114
1115     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1116                              RHSKnownZero, RHSKnownOne, Depth+1))
1117       return I;
1118     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1119     break;
1120   case Instruction::ZExt: {
1121     // Compute the bits in the result that are not present in the input.
1122     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1123     
1124     DemandedMask.trunc(SrcBitWidth);
1125     RHSKnownZero.trunc(SrcBitWidth);
1126     RHSKnownOne.trunc(SrcBitWidth);
1127     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1128                              RHSKnownZero, RHSKnownOne, Depth+1))
1129       return I;
1130     DemandedMask.zext(BitWidth);
1131     RHSKnownZero.zext(BitWidth);
1132     RHSKnownOne.zext(BitWidth);
1133     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1134     // The top bits are known to be zero.
1135     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1136     break;
1137   }
1138   case Instruction::SExt: {
1139     // Compute the bits in the result that are not present in the input.
1140     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1141     
1142     APInt InputDemandedBits = DemandedMask & 
1143                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1144
1145     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1146     // If any of the sign extended bits are demanded, we know that the sign
1147     // bit is demanded.
1148     if ((NewBits & DemandedMask) != 0)
1149       InputDemandedBits.set(SrcBitWidth-1);
1150       
1151     InputDemandedBits.trunc(SrcBitWidth);
1152     RHSKnownZero.trunc(SrcBitWidth);
1153     RHSKnownOne.trunc(SrcBitWidth);
1154     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1155                              RHSKnownZero, RHSKnownOne, Depth+1))
1156       return I;
1157     InputDemandedBits.zext(BitWidth);
1158     RHSKnownZero.zext(BitWidth);
1159     RHSKnownOne.zext(BitWidth);
1160     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1161       
1162     // If the sign bit of the input is known set or clear, then we know the
1163     // top bits of the result.
1164
1165     // If the input sign bit is known zero, or if the NewBits are not demanded
1166     // convert this into a zero extension.
1167     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1168       // Convert to ZExt cast
1169       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1170       return InsertNewInstBefore(NewCast, *I);
1171     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1172       RHSKnownOne |= NewBits;
1173     }
1174     break;
1175   }
1176   case Instruction::Add: {
1177     // Figure out what the input bits are.  If the top bits of the and result
1178     // are not demanded, then the add doesn't demand them from its input
1179     // either.
1180     unsigned NLZ = DemandedMask.countLeadingZeros();
1181       
1182     // If there is a constant on the RHS, there are a variety of xformations
1183     // we can do.
1184     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1185       // If null, this should be simplified elsewhere.  Some of the xforms here
1186       // won't work if the RHS is zero.
1187       if (RHS->isZero())
1188         break;
1189       
1190       // If the top bit of the output is demanded, demand everything from the
1191       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1192       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1193
1194       // Find information about known zero/one bits in the input.
1195       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1196                                LHSKnownZero, LHSKnownOne, Depth+1))
1197         return I;
1198
1199       // If the RHS of the add has bits set that can't affect the input, reduce
1200       // the constant.
1201       if (ShrinkDemandedConstant(I, 1, InDemandedBits, Context))
1202         return I;
1203       
1204       // Avoid excess work.
1205       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1206         break;
1207       
1208       // Turn it into OR if input bits are zero.
1209       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1210         Instruction *Or =
1211           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1212                                    I->getName());
1213         return InsertNewInstBefore(Or, *I);
1214       }
1215       
1216       // We can say something about the output known-zero and known-one bits,
1217       // depending on potential carries from the input constant and the
1218       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1219       // bits set and the RHS constant is 0x01001, then we know we have a known
1220       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1221       
1222       // To compute this, we first compute the potential carry bits.  These are
1223       // the bits which may be modified.  I'm not aware of a better way to do
1224       // this scan.
1225       const APInt &RHSVal = RHS->getValue();
1226       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1227       
1228       // Now that we know which bits have carries, compute the known-1/0 sets.
1229       
1230       // Bits are known one if they are known zero in one operand and one in the
1231       // other, and there is no input carry.
1232       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1233                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1234       
1235       // Bits are known zero if they are known zero in both operands and there
1236       // is no input carry.
1237       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1238     } else {
1239       // If the high-bits of this ADD are not demanded, then it does not demand
1240       // the high bits of its LHS or RHS.
1241       if (DemandedMask[BitWidth-1] == 0) {
1242         // Right fill the mask of bits for this ADD to demand the most
1243         // significant bit and all those below it.
1244         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1245         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1246                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1247             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1248                                  LHSKnownZero, LHSKnownOne, Depth+1))
1249           return I;
1250       }
1251     }
1252     break;
1253   }
1254   case Instruction::Sub:
1255     // If the high-bits of this SUB are not demanded, then it does not demand
1256     // the high bits of its LHS or RHS.
1257     if (DemandedMask[BitWidth-1] == 0) {
1258       // Right fill the mask of bits for this SUB to demand the most
1259       // significant bit and all those below it.
1260       uint32_t NLZ = DemandedMask.countLeadingZeros();
1261       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1262       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1263                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1264           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1265                                LHSKnownZero, LHSKnownOne, Depth+1))
1266         return I;
1267     }
1268     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1269     // the known zeros and ones.
1270     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1271     break;
1272   case Instruction::Shl:
1273     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1274       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1275       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1276       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1277                                RHSKnownZero, RHSKnownOne, Depth+1))
1278         return I;
1279       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1280       RHSKnownZero <<= ShiftAmt;
1281       RHSKnownOne  <<= ShiftAmt;
1282       // low bits known zero.
1283       if (ShiftAmt)
1284         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1285     }
1286     break;
1287   case Instruction::LShr:
1288     // For a logical shift right
1289     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1290       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1291       
1292       // Unsigned shift right.
1293       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1294       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1295                                RHSKnownZero, RHSKnownOne, Depth+1))
1296         return I;
1297       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1298       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1299       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1300       if (ShiftAmt) {
1301         // Compute the new bits that are at the top now.
1302         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1303         RHSKnownZero |= HighBits;  // high bits known zero.
1304       }
1305     }
1306     break;
1307   case Instruction::AShr:
1308     // If this is an arithmetic shift right and only the low-bit is set, we can
1309     // always convert this into a logical shr, even if the shift amount is
1310     // variable.  The low bit of the shift cannot be an input sign bit unless
1311     // the shift amount is >= the size of the datatype, which is undefined.
1312     if (DemandedMask == 1) {
1313       // Perform the logical shift right.
1314       Instruction *NewVal = BinaryOperator::CreateLShr(
1315                         I->getOperand(0), I->getOperand(1), I->getName());
1316       return InsertNewInstBefore(NewVal, *I);
1317     }    
1318
1319     // If the sign bit is the only bit demanded by this ashr, then there is no
1320     // need to do it, the shift doesn't change the high bit.
1321     if (DemandedMask.isSignBit())
1322       return I->getOperand(0);
1323     
1324     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1325       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1326       
1327       // Signed shift right.
1328       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1329       // If any of the "high bits" are demanded, we should set the sign bit as
1330       // demanded.
1331       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1332         DemandedMaskIn.set(BitWidth-1);
1333       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1334                                RHSKnownZero, RHSKnownOne, Depth+1))
1335         return I;
1336       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1337       // Compute the new bits that are at the top now.
1338       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1339       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1340       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1341         
1342       // Handle the sign bits.
1343       APInt SignBit(APInt::getSignBit(BitWidth));
1344       // Adjust to where it is now in the mask.
1345       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1346         
1347       // If the input sign bit is known to be zero, or if none of the top bits
1348       // are demanded, turn this into an unsigned shift right.
1349       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1350           (HighBits & ~DemandedMask) == HighBits) {
1351         // Perform the logical shift right.
1352         Instruction *NewVal = BinaryOperator::CreateLShr(
1353                           I->getOperand(0), SA, I->getName());
1354         return InsertNewInstBefore(NewVal, *I);
1355       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1356         RHSKnownOne |= HighBits;
1357       }
1358     }
1359     break;
1360   case Instruction::SRem:
1361     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1362       APInt RA = Rem->getValue().abs();
1363       if (RA.isPowerOf2()) {
1364         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1365           return I->getOperand(0);
1366
1367         APInt LowBits = RA - 1;
1368         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1369         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1370                                  LHSKnownZero, LHSKnownOne, Depth+1))
1371           return I;
1372
1373         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1374           LHSKnownZero |= ~LowBits;
1375
1376         KnownZero |= LHSKnownZero & DemandedMask;
1377
1378         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1379       }
1380     }
1381     break;
1382   case Instruction::URem: {
1383     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1384     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1385     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1386                              KnownZero2, KnownOne2, Depth+1) ||
1387         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1388                              KnownZero2, KnownOne2, Depth+1))
1389       return I;
1390
1391     unsigned Leaders = KnownZero2.countLeadingOnes();
1392     Leaders = std::max(Leaders,
1393                        KnownZero2.countLeadingOnes());
1394     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1395     break;
1396   }
1397   case Instruction::Call:
1398     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1399       switch (II->getIntrinsicID()) {
1400       default: break;
1401       case Intrinsic::bswap: {
1402         // If the only bits demanded come from one byte of the bswap result,
1403         // just shift the input byte into position to eliminate the bswap.
1404         unsigned NLZ = DemandedMask.countLeadingZeros();
1405         unsigned NTZ = DemandedMask.countTrailingZeros();
1406           
1407         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1408         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1409         // have 14 leading zeros, round to 8.
1410         NLZ &= ~7;
1411         NTZ &= ~7;
1412         // If we need exactly one byte, we can do this transformation.
1413         if (BitWidth-NLZ-NTZ == 8) {
1414           unsigned ResultBit = NTZ;
1415           unsigned InputBit = BitWidth-NTZ-8;
1416           
1417           // Replace this with either a left or right shift to get the byte into
1418           // the right place.
1419           Instruction *NewVal;
1420           if (InputBit > ResultBit)
1421             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1422                     Context->getConstantInt(I->getType(), InputBit-ResultBit));
1423           else
1424             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1425                     Context->getConstantInt(I->getType(), ResultBit-InputBit));
1426           NewVal->takeName(I);
1427           return InsertNewInstBefore(NewVal, *I);
1428         }
1429           
1430         // TODO: Could compute known zero/one bits based on the input.
1431         break;
1432       }
1433       }
1434     }
1435     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1436     break;
1437   }
1438   
1439   // If the client is only demanding bits that we know, return the known
1440   // constant.
1441   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1442     Constant *C = Context->getConstantInt(RHSKnownOne);
1443     if (isa<PointerType>(V->getType()))
1444       C = Context->getConstantExprIntToPtr(C, V->getType());
1445     return C;
1446   }
1447   return false;
1448 }
1449
1450
1451 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1452 /// any number of elements. DemandedElts contains the set of elements that are
1453 /// actually used by the caller.  This method analyzes which elements of the
1454 /// operand are undef and returns that information in UndefElts.
1455 ///
1456 /// If the information about demanded elements can be used to simplify the
1457 /// operation, the operation is simplified, then the resultant value is
1458 /// returned.  This returns null if no change was made.
1459 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1460                                                 APInt& UndefElts,
1461                                                 unsigned Depth) {
1462   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1463   APInt EltMask(APInt::getAllOnesValue(VWidth));
1464   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1465
1466   if (isa<UndefValue>(V)) {
1467     // If the entire vector is undefined, just return this info.
1468     UndefElts = EltMask;
1469     return 0;
1470   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1471     UndefElts = EltMask;
1472     return Context->getUndef(V->getType());
1473   }
1474
1475   UndefElts = 0;
1476   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1477     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1478     Constant *Undef = Context->getUndef(EltTy);
1479
1480     std::vector<Constant*> Elts;
1481     for (unsigned i = 0; i != VWidth; ++i)
1482       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1483         Elts.push_back(Undef);
1484         UndefElts.set(i);
1485       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1486         Elts.push_back(Undef);
1487         UndefElts.set(i);
1488       } else {                               // Otherwise, defined.
1489         Elts.push_back(CP->getOperand(i));
1490       }
1491
1492     // If we changed the constant, return it.
1493     Constant *NewCP = Context->getConstantVector(Elts);
1494     return NewCP != CP ? NewCP : 0;
1495   } else if (isa<ConstantAggregateZero>(V)) {
1496     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1497     // set to undef.
1498     
1499     // Check if this is identity. If so, return 0 since we are not simplifying
1500     // anything.
1501     if (DemandedElts == ((1ULL << VWidth) -1))
1502       return 0;
1503     
1504     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1505     Constant *Zero = Context->getNullValue(EltTy);
1506     Constant *Undef = Context->getUndef(EltTy);
1507     std::vector<Constant*> Elts;
1508     for (unsigned i = 0; i != VWidth; ++i) {
1509       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1510       Elts.push_back(Elt);
1511     }
1512     UndefElts = DemandedElts ^ EltMask;
1513     return Context->getConstantVector(Elts);
1514   }
1515   
1516   // Limit search depth.
1517   if (Depth == 10)
1518     return 0;
1519
1520   // If multiple users are using the root value, procede with
1521   // simplification conservatively assuming that all elements
1522   // are needed.
1523   if (!V->hasOneUse()) {
1524     // Quit if we find multiple users of a non-root value though.
1525     // They'll be handled when it's their turn to be visited by
1526     // the main instcombine process.
1527     if (Depth != 0)
1528       // TODO: Just compute the UndefElts information recursively.
1529       return 0;
1530
1531     // Conservatively assume that all elements are needed.
1532     DemandedElts = EltMask;
1533   }
1534   
1535   Instruction *I = dyn_cast<Instruction>(V);
1536   if (!I) return 0;        // Only analyze instructions.
1537   
1538   bool MadeChange = false;
1539   APInt UndefElts2(VWidth, 0);
1540   Value *TmpV;
1541   switch (I->getOpcode()) {
1542   default: break;
1543     
1544   case Instruction::InsertElement: {
1545     // If this is a variable index, we don't know which element it overwrites.
1546     // demand exactly the same input as we produce.
1547     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1548     if (Idx == 0) {
1549       // Note that we can't propagate undef elt info, because we don't know
1550       // which elt is getting updated.
1551       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1552                                         UndefElts2, Depth+1);
1553       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1554       break;
1555     }
1556     
1557     // If this is inserting an element that isn't demanded, remove this
1558     // insertelement.
1559     unsigned IdxNo = Idx->getZExtValue();
1560     if (IdxNo >= VWidth || !DemandedElts[IdxNo])
1561       return AddSoonDeadInstToWorklist(*I, 0);
1562     
1563     // Otherwise, the element inserted overwrites whatever was there, so the
1564     // input demanded set is simpler than the output set.
1565     APInt DemandedElts2 = DemandedElts;
1566     DemandedElts2.clear(IdxNo);
1567     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1568                                       UndefElts, Depth+1);
1569     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1570
1571     // The inserted element is defined.
1572     UndefElts.clear(IdxNo);
1573     break;
1574   }
1575   case Instruction::ShuffleVector: {
1576     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1577     uint64_t LHSVWidth =
1578       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1579     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1580     for (unsigned i = 0; i < VWidth; i++) {
1581       if (DemandedElts[i]) {
1582         unsigned MaskVal = Shuffle->getMaskValue(i);
1583         if (MaskVal != -1u) {
1584           assert(MaskVal < LHSVWidth * 2 &&
1585                  "shufflevector mask index out of range!");
1586           if (MaskVal < LHSVWidth)
1587             LeftDemanded.set(MaskVal);
1588           else
1589             RightDemanded.set(MaskVal - LHSVWidth);
1590         }
1591       }
1592     }
1593
1594     APInt UndefElts4(LHSVWidth, 0);
1595     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1596                                       UndefElts4, Depth+1);
1597     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1598
1599     APInt UndefElts3(LHSVWidth, 0);
1600     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1601                                       UndefElts3, Depth+1);
1602     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1603
1604     bool NewUndefElts = false;
1605     for (unsigned i = 0; i < VWidth; i++) {
1606       unsigned MaskVal = Shuffle->getMaskValue(i);
1607       if (MaskVal == -1u) {
1608         UndefElts.set(i);
1609       } else if (MaskVal < LHSVWidth) {
1610         if (UndefElts4[MaskVal]) {
1611           NewUndefElts = true;
1612           UndefElts.set(i);
1613         }
1614       } else {
1615         if (UndefElts3[MaskVal - LHSVWidth]) {
1616           NewUndefElts = true;
1617           UndefElts.set(i);
1618         }
1619       }
1620     }
1621
1622     if (NewUndefElts) {
1623       // Add additional discovered undefs.
1624       std::vector<Constant*> Elts;
1625       for (unsigned i = 0; i < VWidth; ++i) {
1626         if (UndefElts[i])
1627           Elts.push_back(Context->getUndef(Type::Int32Ty));
1628         else
1629           Elts.push_back(Context->getConstantInt(Type::Int32Ty,
1630                                           Shuffle->getMaskValue(i)));
1631       }
1632       I->setOperand(2, Context->getConstantVector(Elts));
1633       MadeChange = true;
1634     }
1635     break;
1636   }
1637   case Instruction::BitCast: {
1638     // Vector->vector casts only.
1639     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1640     if (!VTy) break;
1641     unsigned InVWidth = VTy->getNumElements();
1642     APInt InputDemandedElts(InVWidth, 0);
1643     unsigned Ratio;
1644
1645     if (VWidth == InVWidth) {
1646       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1647       // elements as are demanded of us.
1648       Ratio = 1;
1649       InputDemandedElts = DemandedElts;
1650     } else if (VWidth > InVWidth) {
1651       // Untested so far.
1652       break;
1653       
1654       // If there are more elements in the result than there are in the source,
1655       // then an input element is live if any of the corresponding output
1656       // elements are live.
1657       Ratio = VWidth/InVWidth;
1658       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1659         if (DemandedElts[OutIdx])
1660           InputDemandedElts.set(OutIdx/Ratio);
1661       }
1662     } else {
1663       // Untested so far.
1664       break;
1665       
1666       // If there are more elements in the source than there are in the result,
1667       // then an input element is live if the corresponding output element is
1668       // live.
1669       Ratio = InVWidth/VWidth;
1670       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1671         if (DemandedElts[InIdx/Ratio])
1672           InputDemandedElts.set(InIdx);
1673     }
1674     
1675     // div/rem demand all inputs, because they don't want divide by zero.
1676     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1677                                       UndefElts2, Depth+1);
1678     if (TmpV) {
1679       I->setOperand(0, TmpV);
1680       MadeChange = true;
1681     }
1682     
1683     UndefElts = UndefElts2;
1684     if (VWidth > InVWidth) {
1685       LLVM_UNREACHABLE("Unimp");
1686       // If there are more elements in the result than there are in the source,
1687       // then an output element is undef if the corresponding input element is
1688       // undef.
1689       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1690         if (UndefElts2[OutIdx/Ratio])
1691           UndefElts.set(OutIdx);
1692     } else if (VWidth < InVWidth) {
1693       LLVM_UNREACHABLE("Unimp");
1694       // If there are more elements in the source than there are in the result,
1695       // then a result element is undef if all of the corresponding input
1696       // elements are undef.
1697       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1698       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1699         if (!UndefElts2[InIdx])            // Not undef?
1700           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1701     }
1702     break;
1703   }
1704   case Instruction::And:
1705   case Instruction::Or:
1706   case Instruction::Xor:
1707   case Instruction::Add:
1708   case Instruction::Sub:
1709   case Instruction::Mul:
1710     // div/rem demand all inputs, because they don't want divide by zero.
1711     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1712                                       UndefElts, Depth+1);
1713     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1714     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1715                                       UndefElts2, Depth+1);
1716     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1717       
1718     // Output elements are undefined if both are undefined.  Consider things
1719     // like undef&0.  The result is known zero, not undef.
1720     UndefElts &= UndefElts2;
1721     break;
1722     
1723   case Instruction::Call: {
1724     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1725     if (!II) break;
1726     switch (II->getIntrinsicID()) {
1727     default: break;
1728       
1729     // Binary vector operations that work column-wise.  A dest element is a
1730     // function of the corresponding input elements from the two inputs.
1731     case Intrinsic::x86_sse_sub_ss:
1732     case Intrinsic::x86_sse_mul_ss:
1733     case Intrinsic::x86_sse_min_ss:
1734     case Intrinsic::x86_sse_max_ss:
1735     case Intrinsic::x86_sse2_sub_sd:
1736     case Intrinsic::x86_sse2_mul_sd:
1737     case Intrinsic::x86_sse2_min_sd:
1738     case Intrinsic::x86_sse2_max_sd:
1739       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1740                                         UndefElts, Depth+1);
1741       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1742       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1743                                         UndefElts2, Depth+1);
1744       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1745
1746       // If only the low elt is demanded and this is a scalarizable intrinsic,
1747       // scalarize it now.
1748       if (DemandedElts == 1) {
1749         switch (II->getIntrinsicID()) {
1750         default: break;
1751         case Intrinsic::x86_sse_sub_ss:
1752         case Intrinsic::x86_sse_mul_ss:
1753         case Intrinsic::x86_sse2_sub_sd:
1754         case Intrinsic::x86_sse2_mul_sd:
1755           // TODO: Lower MIN/MAX/ABS/etc
1756           Value *LHS = II->getOperand(1);
1757           Value *RHS = II->getOperand(2);
1758           // Extract the element as scalars.
1759           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1760           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1761           
1762           switch (II->getIntrinsicID()) {
1763           default: LLVM_UNREACHABLE("Case stmts out of sync!");
1764           case Intrinsic::x86_sse_sub_ss:
1765           case Intrinsic::x86_sse2_sub_sd:
1766             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1767                                                         II->getName()), *II);
1768             break;
1769           case Intrinsic::x86_sse_mul_ss:
1770           case Intrinsic::x86_sse2_mul_sd:
1771             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1772                                                          II->getName()), *II);
1773             break;
1774           }
1775           
1776           Instruction *New =
1777             InsertElementInst::Create(
1778               Context->getUndef(II->getType()), TmpV, 0U, II->getName());
1779           InsertNewInstBefore(New, *II);
1780           AddSoonDeadInstToWorklist(*II, 0);
1781           return New;
1782         }            
1783       }
1784         
1785       // Output elements are undefined if both are undefined.  Consider things
1786       // like undef&0.  The result is known zero, not undef.
1787       UndefElts &= UndefElts2;
1788       break;
1789     }
1790     break;
1791   }
1792   }
1793   return MadeChange ? I : 0;
1794 }
1795
1796
1797 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1798 /// function is designed to check a chain of associative operators for a
1799 /// potential to apply a certain optimization.  Since the optimization may be
1800 /// applicable if the expression was reassociated, this checks the chain, then
1801 /// reassociates the expression as necessary to expose the optimization
1802 /// opportunity.  This makes use of a special Functor, which must define
1803 /// 'shouldApply' and 'apply' methods.
1804 ///
1805 template<typename Functor>
1806 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F,
1807                                    LLVMContext *Context) {
1808   unsigned Opcode = Root.getOpcode();
1809   Value *LHS = Root.getOperand(0);
1810
1811   // Quick check, see if the immediate LHS matches...
1812   if (F.shouldApply(LHS))
1813     return F.apply(Root);
1814
1815   // Otherwise, if the LHS is not of the same opcode as the root, return.
1816   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1817   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1818     // Should we apply this transform to the RHS?
1819     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1820
1821     // If not to the RHS, check to see if we should apply to the LHS...
1822     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1823       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1824       ShouldApply = true;
1825     }
1826
1827     // If the functor wants to apply the optimization to the RHS of LHSI,
1828     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1829     if (ShouldApply) {
1830       // Now all of the instructions are in the current basic block, go ahead
1831       // and perform the reassociation.
1832       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1833
1834       // First move the selected RHS to the LHS of the root...
1835       Root.setOperand(0, LHSI->getOperand(1));
1836
1837       // Make what used to be the LHS of the root be the user of the root...
1838       Value *ExtraOperand = TmpLHSI->getOperand(1);
1839       if (&Root == TmpLHSI) {
1840         Root.replaceAllUsesWith(Context->getNullValue(TmpLHSI->getType()));
1841         return 0;
1842       }
1843       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1844       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1845       BasicBlock::iterator ARI = &Root; ++ARI;
1846       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1847       ARI = Root;
1848
1849       // Now propagate the ExtraOperand down the chain of instructions until we
1850       // get to LHSI.
1851       while (TmpLHSI != LHSI) {
1852         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1853         // Move the instruction to immediately before the chain we are
1854         // constructing to avoid breaking dominance properties.
1855         NextLHSI->moveBefore(ARI);
1856         ARI = NextLHSI;
1857
1858         Value *NextOp = NextLHSI->getOperand(1);
1859         NextLHSI->setOperand(1, ExtraOperand);
1860         TmpLHSI = NextLHSI;
1861         ExtraOperand = NextOp;
1862       }
1863
1864       // Now that the instructions are reassociated, have the functor perform
1865       // the transformation...
1866       return F.apply(Root);
1867     }
1868
1869     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1870   }
1871   return 0;
1872 }
1873
1874 namespace {
1875
1876 // AddRHS - Implements: X + X --> X << 1
1877 struct AddRHS {
1878   Value *RHS;
1879   LLVMContext *Context;
1880   AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
1881   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1882   Instruction *apply(BinaryOperator &Add) const {
1883     return BinaryOperator::CreateShl(Add.getOperand(0),
1884                                      Context->getConstantInt(Add.getType(), 1));
1885   }
1886 };
1887
1888 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1889 //                 iff C1&C2 == 0
1890 struct AddMaskingAnd {
1891   Constant *C2;
1892   LLVMContext *Context;
1893   AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
1894   bool shouldApply(Value *LHS) const {
1895     ConstantInt *C1;
1896     return match(LHS, m_And(m_Value(), m_ConstantInt(C1)), *Context) &&
1897            Context->getConstantExprAnd(C1, C2)->isNullValue();
1898   }
1899   Instruction *apply(BinaryOperator &Add) const {
1900     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1901   }
1902 };
1903
1904 }
1905
1906 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1907                                              InstCombiner *IC) {
1908   LLVMContext *Context = IC->getContext();
1909   
1910   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1911     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1912   }
1913
1914   // Figure out if the constant is the left or the right argument.
1915   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1916   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1917
1918   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1919     if (ConstIsRHS)
1920       return Context->getConstantExpr(I.getOpcode(), SOC, ConstOperand);
1921     return Context->getConstantExpr(I.getOpcode(), ConstOperand, SOC);
1922   }
1923
1924   Value *Op0 = SO, *Op1 = ConstOperand;
1925   if (!ConstIsRHS)
1926     std::swap(Op0, Op1);
1927   Instruction *New;
1928   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1929     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1930   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1931     New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1932                           Op0, Op1, SO->getName()+".cmp");
1933   else {
1934     LLVM_UNREACHABLE("Unknown binary instruction type!");
1935   }
1936   return IC->InsertNewInstBefore(New, I);
1937 }
1938
1939 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1940 // constant as the other operand, try to fold the binary operator into the
1941 // select arguments.  This also works for Cast instructions, which obviously do
1942 // not have a second operand.
1943 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1944                                      InstCombiner *IC) {
1945   // Don't modify shared select instructions
1946   if (!SI->hasOneUse()) return 0;
1947   Value *TV = SI->getOperand(1);
1948   Value *FV = SI->getOperand(2);
1949
1950   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1951     // Bool selects with constant operands can be folded to logical ops.
1952     if (SI->getType() == Type::Int1Ty) return 0;
1953
1954     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1955     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1956
1957     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1958                               SelectFalseVal);
1959   }
1960   return 0;
1961 }
1962
1963
1964 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1965 /// node as operand #0, see if we can fold the instruction into the PHI (which
1966 /// is only possible if all operands to the PHI are constants).
1967 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1968   PHINode *PN = cast<PHINode>(I.getOperand(0));
1969   unsigned NumPHIValues = PN->getNumIncomingValues();
1970   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1971
1972   // Check to see if all of the operands of the PHI are constants.  If there is
1973   // one non-constant value, remember the BB it is.  If there is more than one
1974   // or if *it* is a PHI, bail out.
1975   BasicBlock *NonConstBB = 0;
1976   for (unsigned i = 0; i != NumPHIValues; ++i)
1977     if (!isa<Constant>(PN->getIncomingValue(i))) {
1978       if (NonConstBB) return 0;  // More than one non-const value.
1979       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1980       NonConstBB = PN->getIncomingBlock(i);
1981       
1982       // If the incoming non-constant value is in I's block, we have an infinite
1983       // loop.
1984       if (NonConstBB == I.getParent())
1985         return 0;
1986     }
1987   
1988   // If there is exactly one non-constant value, we can insert a copy of the
1989   // operation in that block.  However, if this is a critical edge, we would be
1990   // inserting the computation one some other paths (e.g. inside a loop).  Only
1991   // do this if the pred block is unconditionally branching into the phi block.
1992   if (NonConstBB) {
1993     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1994     if (!BI || !BI->isUnconditional()) return 0;
1995   }
1996
1997   // Okay, we can do the transformation: create the new PHI node.
1998   PHINode *NewPN = PHINode::Create(I.getType(), "");
1999   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2000   InsertNewInstBefore(NewPN, *PN);
2001   NewPN->takeName(PN);
2002
2003   // Next, add all of the operands to the PHI.
2004   if (I.getNumOperands() == 2) {
2005     Constant *C = cast<Constant>(I.getOperand(1));
2006     for (unsigned i = 0; i != NumPHIValues; ++i) {
2007       Value *InV = 0;
2008       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2009         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2010           InV = Context->getConstantExprCompare(CI->getPredicate(), InC, C);
2011         else
2012           InV = Context->getConstantExpr(I.getOpcode(), InC, C);
2013       } else {
2014         assert(PN->getIncomingBlock(i) == NonConstBB);
2015         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
2016           InV = BinaryOperator::Create(BO->getOpcode(),
2017                                        PN->getIncomingValue(i), C, "phitmp",
2018                                        NonConstBB->getTerminator());
2019         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2020           InV = CmpInst::Create(*Context, CI->getOpcode(), 
2021                                 CI->getPredicate(),
2022                                 PN->getIncomingValue(i), C, "phitmp",
2023                                 NonConstBB->getTerminator());
2024         else
2025           LLVM_UNREACHABLE("Unknown binop!");
2026         
2027         AddToWorkList(cast<Instruction>(InV));
2028       }
2029       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2030     }
2031   } else { 
2032     CastInst *CI = cast<CastInst>(&I);
2033     const Type *RetTy = CI->getType();
2034     for (unsigned i = 0; i != NumPHIValues; ++i) {
2035       Value *InV;
2036       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2037         InV = Context->getConstantExprCast(CI->getOpcode(), InC, RetTy);
2038       } else {
2039         assert(PN->getIncomingBlock(i) == NonConstBB);
2040         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2041                                I.getType(), "phitmp", 
2042                                NonConstBB->getTerminator());
2043         AddToWorkList(cast<Instruction>(InV));
2044       }
2045       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2046     }
2047   }
2048   return ReplaceInstUsesWith(I, NewPN);
2049 }
2050
2051
2052 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2053 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2054 /// This basically requires proving that the add in the original type would not
2055 /// overflow to change the sign bit or have a carry out.
2056 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2057   // There are different heuristics we can use for this.  Here are some simple
2058   // ones.
2059   
2060   // Add has the property that adding any two 2's complement numbers can only 
2061   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2062   // have at least two sign bits, we know that the addition of the two values will
2063   // sign extend fine.
2064   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2065     return true;
2066   
2067   
2068   // If one of the operands only has one non-zero bit, and if the other operand
2069   // has a known-zero bit in a more significant place than it (not including the
2070   // sign bit) the ripple may go up to and fill the zero, but won't change the
2071   // sign.  For example, (X & ~4) + 1.
2072   
2073   // TODO: Implement.
2074   
2075   return false;
2076 }
2077
2078
2079 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2080   bool Changed = SimplifyCommutative(I);
2081   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2082
2083   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2084     // X + undef -> undef
2085     if (isa<UndefValue>(RHS))
2086       return ReplaceInstUsesWith(I, RHS);
2087
2088     // X + 0 --> X
2089     if (RHSC->isNullValue())
2090       return ReplaceInstUsesWith(I, LHS);
2091
2092     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2093       // X + (signbit) --> X ^ signbit
2094       const APInt& Val = CI->getValue();
2095       uint32_t BitWidth = Val.getBitWidth();
2096       if (Val == APInt::getSignBit(BitWidth))
2097         return BinaryOperator::CreateXor(LHS, RHS);
2098       
2099       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2100       // (X & 254)+1 -> (X&254)|1
2101       if (SimplifyDemandedInstructionBits(I))
2102         return &I;
2103
2104       // zext(bool) + C -> bool ? C + 1 : C
2105       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2106         if (ZI->getSrcTy() == Type::Int1Ty)
2107           return SelectInst::Create(ZI->getOperand(0), AddOne(CI, Context), CI);
2108     }
2109
2110     if (isa<PHINode>(LHS))
2111       if (Instruction *NV = FoldOpIntoPhi(I))
2112         return NV;
2113     
2114     ConstantInt *XorRHS = 0;
2115     Value *XorLHS = 0;
2116     if (isa<ConstantInt>(RHSC) &&
2117         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)), *Context)) {
2118       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2119       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2120       
2121       uint32_t Size = TySizeBits / 2;
2122       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2123       APInt CFF80Val(-C0080Val);
2124       do {
2125         if (TySizeBits > Size) {
2126           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2127           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2128           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2129               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2130             // This is a sign extend if the top bits are known zero.
2131             if (!MaskedValueIsZero(XorLHS, 
2132                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2133               Size = 0;  // Not a sign ext, but can't be any others either.
2134             break;
2135           }
2136         }
2137         Size >>= 1;
2138         C0080Val = APIntOps::lshr(C0080Val, Size);
2139         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2140       } while (Size >= 1);
2141       
2142       // FIXME: This shouldn't be necessary. When the backends can handle types
2143       // with funny bit widths then this switch statement should be removed. It
2144       // is just here to get the size of the "middle" type back up to something
2145       // that the back ends can handle.
2146       const Type *MiddleType = 0;
2147       switch (Size) {
2148         default: break;
2149         case 32: MiddleType = Type::Int32Ty; break;
2150         case 16: MiddleType = Type::Int16Ty; break;
2151         case  8: MiddleType = Type::Int8Ty; break;
2152       }
2153       if (MiddleType) {
2154         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2155         InsertNewInstBefore(NewTrunc, I);
2156         return new SExtInst(NewTrunc, I.getType(), I.getName());
2157       }
2158     }
2159   }
2160
2161   if (I.getType() == Type::Int1Ty)
2162     return BinaryOperator::CreateXor(LHS, RHS);
2163
2164   // X + X --> X << 1
2165   if (I.getType()->isInteger()) {
2166     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2167       return Result;
2168
2169     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2170       if (RHSI->getOpcode() == Instruction::Sub)
2171         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2172           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2173     }
2174     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2175       if (LHSI->getOpcode() == Instruction::Sub)
2176         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2177           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2178     }
2179   }
2180
2181   // -A + B  -->  B - A
2182   // -A + -B  -->  -(A + B)
2183   if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
2184     if (LHS->getType()->isIntOrIntVector()) {
2185       if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
2186         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2187         InsertNewInstBefore(NewAdd, I);
2188         return BinaryOperator::CreateNeg(*Context, NewAdd);
2189       }
2190     }
2191     
2192     return BinaryOperator::CreateSub(RHS, LHSV);
2193   }
2194
2195   // A + -B  -->  A - B
2196   if (!isa<Constant>(RHS))
2197     if (Value *V = dyn_castNegVal(RHS, Context))
2198       return BinaryOperator::CreateSub(LHS, V);
2199
2200
2201   ConstantInt *C2;
2202   if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
2203     if (X == RHS)   // X*C + X --> X * (C+1)
2204       return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
2205
2206     // X*C1 + X*C2 --> X * (C1+C2)
2207     ConstantInt *C1;
2208     if (X == dyn_castFoldableMul(RHS, C1, Context))
2209       return BinaryOperator::CreateMul(X, Context->getConstantExprAdd(C1, C2));
2210   }
2211
2212   // X + X*C --> X * (C+1)
2213   if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2214     return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
2215
2216   // X + ~X --> -1   since   ~X = -X-1
2217   if (dyn_castNotVal(LHS, Context) == RHS ||
2218       dyn_castNotVal(RHS, Context) == LHS)
2219     return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
2220   
2221
2222   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2223   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)), *Context))
2224     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
2225       return R;
2226   
2227   // A+B --> A|B iff A and B have no bits set in common.
2228   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2229     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2230     APInt LHSKnownOne(IT->getBitWidth(), 0);
2231     APInt LHSKnownZero(IT->getBitWidth(), 0);
2232     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2233     if (LHSKnownZero != 0) {
2234       APInt RHSKnownOne(IT->getBitWidth(), 0);
2235       APInt RHSKnownZero(IT->getBitWidth(), 0);
2236       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2237       
2238       // No bits in common -> bitwise or.
2239       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2240         return BinaryOperator::CreateOr(LHS, RHS);
2241     }
2242   }
2243
2244   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2245   if (I.getType()->isIntOrIntVector()) {
2246     Value *W, *X, *Y, *Z;
2247     if (match(LHS, m_Mul(m_Value(W), m_Value(X)), *Context) &&
2248         match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
2249       if (W != Y) {
2250         if (W == Z) {
2251           std::swap(Y, Z);
2252         } else if (Y == X) {
2253           std::swap(W, X);
2254         } else if (X == Z) {
2255           std::swap(Y, Z);
2256           std::swap(W, X);
2257         }
2258       }
2259
2260       if (W == Y) {
2261         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2262                                                             LHS->getName()), I);
2263         return BinaryOperator::CreateMul(W, NewAdd);
2264       }
2265     }
2266   }
2267
2268   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2269     Value *X = 0;
2270     if (match(LHS, m_Not(m_Value(X)), *Context))    // ~X + C --> (C-1) - X
2271       return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
2272
2273     // (X & FF00) + xx00  -> (X+xx00) & FF00
2274     if (LHS->hasOneUse() &&
2275         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
2276       Constant *Anded = Context->getConstantExprAnd(CRHS, C2);
2277       if (Anded == CRHS) {
2278         // See if all bits from the first bit set in the Add RHS up are included
2279         // in the mask.  First, get the rightmost bit.
2280         const APInt& AddRHSV = CRHS->getValue();
2281
2282         // Form a mask of all bits from the lowest bit added through the top.
2283         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2284
2285         // See if the and mask includes all of these bits.
2286         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2287
2288         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2289           // Okay, the xform is safe.  Insert the new add pronto.
2290           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2291                                                             LHS->getName()), I);
2292           return BinaryOperator::CreateAnd(NewAdd, C2);
2293         }
2294       }
2295     }
2296
2297     // Try to fold constant add into select arguments.
2298     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2299       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2300         return R;
2301   }
2302
2303   // add (cast *A to intptrtype) B -> 
2304   //   cast (GEP (cast *A to i8*) B)  -->  intptrtype
2305   {
2306     CastInst *CI = dyn_cast<CastInst>(LHS);
2307     Value *Other = RHS;
2308     if (!CI) {
2309       CI = dyn_cast<CastInst>(RHS);
2310       Other = LHS;
2311     }
2312     if (CI && CI->getType()->isSized() && 
2313         (CI->getType()->getScalarSizeInBits() ==
2314          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2315         && isa<PointerType>(CI->getOperand(0)->getType())) {
2316       unsigned AS =
2317         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2318       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2319                                   Context->getPointerType(Type::Int8Ty, AS), I);
2320       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2321       return new PtrToIntInst(I2, CI->getType());
2322     }
2323   }
2324   
2325   // add (select X 0 (sub n A)) A  -->  select X A n
2326   {
2327     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2328     Value *A = RHS;
2329     if (!SI) {
2330       SI = dyn_cast<SelectInst>(RHS);
2331       A = LHS;
2332     }
2333     if (SI && SI->hasOneUse()) {
2334       Value *TV = SI->getTrueValue();
2335       Value *FV = SI->getFalseValue();
2336       Value *N;
2337
2338       // Can we fold the add into the argument of the select?
2339       // We check both true and false select arguments for a matching subtract.
2340       if (match(FV, m_Zero(), *Context) &&
2341           match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2342         // Fold the add into the true select value.
2343         return SelectInst::Create(SI->getCondition(), N, A);
2344       if (match(TV, m_Zero(), *Context) &&
2345           match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2346         // Fold the add into the false select value.
2347         return SelectInst::Create(SI->getCondition(), A, N);
2348     }
2349   }
2350
2351   // Check for (add (sext x), y), see if we can merge this into an
2352   // integer add followed by a sext.
2353   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2354     // (add (sext x), cst) --> (sext (add x, cst'))
2355     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2356       Constant *CI = 
2357         Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
2358       if (LHSConv->hasOneUse() &&
2359           Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
2360           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2361         // Insert the new, smaller add.
2362         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2363                                                         CI, "addconv");
2364         InsertNewInstBefore(NewAdd, I);
2365         return new SExtInst(NewAdd, I.getType());
2366       }
2367     }
2368     
2369     // (add (sext x), (sext y)) --> (sext (add int x, y))
2370     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2371       // Only do this if x/y have the same type, if at last one of them has a
2372       // single use (so we don't increase the number of sexts), and if the
2373       // integer add will not overflow.
2374       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2375           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2376           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2377                                    RHSConv->getOperand(0))) {
2378         // Insert the new integer add.
2379         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2380                                                         RHSConv->getOperand(0),
2381                                                         "addconv");
2382         InsertNewInstBefore(NewAdd, I);
2383         return new SExtInst(NewAdd, I.getType());
2384       }
2385     }
2386   }
2387
2388   return Changed ? &I : 0;
2389 }
2390
2391 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2392   bool Changed = SimplifyCommutative(I);
2393   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2394
2395   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2396     // X + 0 --> X
2397     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2398       if (CFP->isExactlyValue(Context->getConstantFPNegativeZero
2399                               (I.getType())->getValueAPF()))
2400         return ReplaceInstUsesWith(I, LHS);
2401     }
2402
2403     if (isa<PHINode>(LHS))
2404       if (Instruction *NV = FoldOpIntoPhi(I))
2405         return NV;
2406   }
2407
2408   // -A + B  -->  B - A
2409   // -A + -B  -->  -(A + B)
2410   if (Value *LHSV = dyn_castFNegVal(LHS, Context))
2411     return BinaryOperator::CreateFSub(RHS, LHSV);
2412
2413   // A + -B  -->  A - B
2414   if (!isa<Constant>(RHS))
2415     if (Value *V = dyn_castFNegVal(RHS, Context))
2416       return BinaryOperator::CreateFSub(LHS, V);
2417
2418   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2419   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2420     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2421       return ReplaceInstUsesWith(I, LHS);
2422
2423   // Check for (add double (sitofp x), y), see if we can merge this into an
2424   // integer add followed by a promotion.
2425   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2426     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2427     // ... if the constant fits in the integer value.  This is useful for things
2428     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2429     // requires a constant pool load, and generally allows the add to be better
2430     // instcombined.
2431     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2432       Constant *CI = 
2433       Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
2434       if (LHSConv->hasOneUse() &&
2435           Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
2436           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2437         // Insert the new integer add.
2438         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2439                                                         CI, "addconv");
2440         InsertNewInstBefore(NewAdd, I);
2441         return new SIToFPInst(NewAdd, I.getType());
2442       }
2443     }
2444     
2445     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2446     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2447       // Only do this if x/y have the same type, if at last one of them has a
2448       // single use (so we don't increase the number of int->fp conversions),
2449       // and if the integer add will not overflow.
2450       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2451           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2452           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2453                                    RHSConv->getOperand(0))) {
2454         // Insert the new integer add.
2455         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2456                                                         RHSConv->getOperand(0),
2457                                                         "addconv");
2458         InsertNewInstBefore(NewAdd, I);
2459         return new SIToFPInst(NewAdd, I.getType());
2460       }
2461     }
2462   }
2463   
2464   return Changed ? &I : 0;
2465 }
2466
2467 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2468   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2469
2470   if (Op0 == Op1)                        // sub X, X  -> 0
2471     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2472
2473   // If this is a 'B = x-(-A)', change to B = x+A...
2474   if (Value *V = dyn_castNegVal(Op1, Context))
2475     return BinaryOperator::CreateAdd(Op0, V);
2476
2477   if (isa<UndefValue>(Op0))
2478     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2479   if (isa<UndefValue>(Op1))
2480     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2481
2482   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2483     // Replace (-1 - A) with (~A)...
2484     if (C->isAllOnesValue())
2485       return BinaryOperator::CreateNot(*Context, Op1);
2486
2487     // C - ~X == X + (1+C)
2488     Value *X = 0;
2489     if (match(Op1, m_Not(m_Value(X)), *Context))
2490       return BinaryOperator::CreateAdd(X, AddOne(C, Context));
2491
2492     // -(X >>u 31) -> (X >>s 31)
2493     // -(X >>s 31) -> (X >>u 31)
2494     if (C->isZero()) {
2495       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2496         if (SI->getOpcode() == Instruction::LShr) {
2497           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2498             // Check to see if we are shifting out everything but the sign bit.
2499             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2500                 SI->getType()->getPrimitiveSizeInBits()-1) {
2501               // Ok, the transformation is safe.  Insert AShr.
2502               return BinaryOperator::Create(Instruction::AShr, 
2503                                           SI->getOperand(0), CU, SI->getName());
2504             }
2505           }
2506         }
2507         else if (SI->getOpcode() == Instruction::AShr) {
2508           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2509             // Check to see if we are shifting out everything but the sign bit.
2510             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2511                 SI->getType()->getPrimitiveSizeInBits()-1) {
2512               // Ok, the transformation is safe.  Insert LShr. 
2513               return BinaryOperator::CreateLShr(
2514                                           SI->getOperand(0), CU, SI->getName());
2515             }
2516           }
2517         }
2518       }
2519     }
2520
2521     // Try to fold constant sub into select arguments.
2522     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2523       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2524         return R;
2525
2526     // C - zext(bool) -> bool ? C - 1 : C
2527     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2528       if (ZI->getSrcTy() == Type::Int1Ty)
2529         return SelectInst::Create(ZI->getOperand(0), SubOne(C, Context), C);
2530   }
2531
2532   if (I.getType() == Type::Int1Ty)
2533     return BinaryOperator::CreateXor(Op0, Op1);
2534
2535   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2536     if (Op1I->getOpcode() == Instruction::Add) {
2537       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2538         return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(1),
2539                                          I.getName());
2540       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2541         return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(0), 
2542                                          I.getName());
2543       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2544         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2545           // C1-(X+C2) --> (C1-C2)-X
2546           return BinaryOperator::CreateSub(
2547             Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
2548       }
2549     }
2550
2551     if (Op1I->hasOneUse()) {
2552       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2553       // is not used by anyone else...
2554       //
2555       if (Op1I->getOpcode() == Instruction::Sub) {
2556         // Swap the two operands of the subexpr...
2557         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2558         Op1I->setOperand(0, IIOp1);
2559         Op1I->setOperand(1, IIOp0);
2560
2561         // Create the new top level add instruction...
2562         return BinaryOperator::CreateAdd(Op0, Op1);
2563       }
2564
2565       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2566       //
2567       if (Op1I->getOpcode() == Instruction::And &&
2568           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2569         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2570
2571         Value *NewNot =
2572           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, 
2573                                                         OtherOp, "B.not"), I);
2574         return BinaryOperator::CreateAnd(Op0, NewNot);
2575       }
2576
2577       // 0 - (X sdiv C)  -> (X sdiv -C)
2578       if (Op1I->getOpcode() == Instruction::SDiv)
2579         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2580           if (CSI->isZero())
2581             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2582               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2583                                           Context->getConstantExprNeg(DivRHS));
2584
2585       // X - X*C --> X * (1-C)
2586       ConstantInt *C2 = 0;
2587       if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2588         Constant *CP1 = 
2589           Context->getConstantExprSub(Context->getConstantInt(I.getType(), 1),
2590                                              C2);
2591         return BinaryOperator::CreateMul(Op0, CP1);
2592       }
2593     }
2594   }
2595
2596   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2597     if (Op0I->getOpcode() == Instruction::Add) {
2598       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2599         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2600       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2601         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2602     } else if (Op0I->getOpcode() == Instruction::Sub) {
2603       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2604         return BinaryOperator::CreateNeg(*Context, Op0I->getOperand(1),
2605                                          I.getName());
2606     }
2607   }
2608
2609   ConstantInt *C1;
2610   if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
2611     if (X == Op1)  // X*C - X --> X * (C-1)
2612       return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
2613
2614     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2615     if (X == dyn_castFoldableMul(Op1, C2, Context))
2616       return BinaryOperator::CreateMul(X, Context->getConstantExprSub(C1, C2));
2617   }
2618   return 0;
2619 }
2620
2621 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2622   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2623
2624   // If this is a 'B = x-(-A)', change to B = x+A...
2625   if (Value *V = dyn_castFNegVal(Op1, Context))
2626     return BinaryOperator::CreateFAdd(Op0, V);
2627
2628   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2629     if (Op1I->getOpcode() == Instruction::FAdd) {
2630       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2631         return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(1),
2632                                           I.getName());
2633       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2634         return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(0),
2635                                           I.getName());
2636     }
2637   }
2638
2639   return 0;
2640 }
2641
2642 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2643 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2644 /// TrueIfSigned if the result of the comparison is true when the input value is
2645 /// signed.
2646 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2647                            bool &TrueIfSigned) {
2648   switch (pred) {
2649   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2650     TrueIfSigned = true;
2651     return RHS->isZero();
2652   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2653     TrueIfSigned = true;
2654     return RHS->isAllOnesValue();
2655   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2656     TrueIfSigned = false;
2657     return RHS->isAllOnesValue();
2658   case ICmpInst::ICMP_UGT:
2659     // True if LHS u> RHS and RHS == high-bit-mask - 1
2660     TrueIfSigned = true;
2661     return RHS->getValue() ==
2662       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2663   case ICmpInst::ICMP_UGE: 
2664     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2665     TrueIfSigned = true;
2666     return RHS->getValue().isSignBit();
2667   default:
2668     return false;
2669   }
2670 }
2671
2672 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2673   bool Changed = SimplifyCommutative(I);
2674   Value *Op0 = I.getOperand(0);
2675
2676   // TODO: If Op1 is undef and Op0 is finite, return zero.
2677   if (!I.getType()->isFPOrFPVector() &&
2678       isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2679     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2680
2681   // Simplify mul instructions with a constant RHS...
2682   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2683     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2684
2685       // ((X << C1)*C2) == (X * (C2 << C1))
2686       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2687         if (SI->getOpcode() == Instruction::Shl)
2688           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2689             return BinaryOperator::CreateMul(SI->getOperand(0),
2690                                         Context->getConstantExprShl(CI, ShOp));
2691
2692       if (CI->isZero())
2693         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2694       if (CI->equalsInt(1))                  // X * 1  == X
2695         return ReplaceInstUsesWith(I, Op0);
2696       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2697         return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2698
2699       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2700       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2701         return BinaryOperator::CreateShl(Op0,
2702                  Context->getConstantInt(Op0->getType(), Val.logBase2()));
2703       }
2704     } else if (isa<VectorType>(Op1->getType())) {
2705       // TODO: If Op1 is all zeros and Op0 is all finite, return all zeros.
2706
2707       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2708         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2709           return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2710
2711         // As above, vector X*splat(1.0) -> X in all defined cases.
2712         if (Constant *Splat = Op1V->getSplatValue()) {
2713           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2714             if (CI->equalsInt(1))
2715               return ReplaceInstUsesWith(I, Op0);
2716         }
2717       }
2718     }
2719     
2720     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2721       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2722           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2723         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2724         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2725                                                      Op1, "tmp");
2726         InsertNewInstBefore(Add, I);
2727         Value *C1C2 = Context->getConstantExprMul(Op1, 
2728                                            cast<Constant>(Op0I->getOperand(1)));
2729         return BinaryOperator::CreateAdd(Add, C1C2);
2730         
2731       }
2732
2733     // Try to fold constant mul into select arguments.
2734     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2735       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2736         return R;
2737
2738     if (isa<PHINode>(Op0))
2739       if (Instruction *NV = FoldOpIntoPhi(I))
2740         return NV;
2741   }
2742
2743   if (Value *Op0v = dyn_castNegVal(Op0, Context))     // -X * -Y = X*Y
2744     if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
2745       return BinaryOperator::CreateMul(Op0v, Op1v);
2746
2747   // (X / Y) *  Y = X - (X % Y)
2748   // (X / Y) * -Y = (X % Y) - X
2749   {
2750     Value *Op1 = I.getOperand(1);
2751     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2752     if (!BO ||
2753         (BO->getOpcode() != Instruction::UDiv && 
2754          BO->getOpcode() != Instruction::SDiv)) {
2755       Op1 = Op0;
2756       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2757     }
2758     Value *Neg = dyn_castNegVal(Op1, Context);
2759     if (BO && BO->hasOneUse() &&
2760         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2761         (BO->getOpcode() == Instruction::UDiv ||
2762          BO->getOpcode() == Instruction::SDiv)) {
2763       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2764
2765       Instruction *Rem;
2766       if (BO->getOpcode() == Instruction::UDiv)
2767         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2768       else
2769         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2770
2771       InsertNewInstBefore(Rem, I);
2772       Rem->takeName(BO);
2773
2774       if (Op1BO == Op1)
2775         return BinaryOperator::CreateSub(Op0BO, Rem);
2776       else
2777         return BinaryOperator::CreateSub(Rem, Op0BO);
2778     }
2779   }
2780
2781   if (I.getType() == Type::Int1Ty)
2782     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2783
2784   // If one of the operands of the multiply is a cast from a boolean value, then
2785   // we know the bool is either zero or one, so this is a 'masking' multiply.
2786   // See if we can simplify things based on how the boolean was originally
2787   // formed.
2788   CastInst *BoolCast = 0;
2789   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2790     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2791       BoolCast = CI;
2792   if (!BoolCast)
2793     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2794       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2795         BoolCast = CI;
2796   if (BoolCast) {
2797     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2798       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2799       const Type *SCOpTy = SCIOp0->getType();
2800       bool TIS = false;
2801       
2802       // If the icmp is true iff the sign bit of X is set, then convert this
2803       // multiply into a shift/and combination.
2804       if (isa<ConstantInt>(SCIOp1) &&
2805           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2806           TIS) {
2807         // Shift the X value right to turn it into "all signbits".
2808         Constant *Amt = Context->getConstantInt(SCIOp0->getType(),
2809                                           SCOpTy->getPrimitiveSizeInBits()-1);
2810         Value *V =
2811           InsertNewInstBefore(
2812             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2813                                             BoolCast->getOperand(0)->getName()+
2814                                             ".mask"), I);
2815
2816         // If the multiply type is not the same as the source type, sign extend
2817         // or truncate to the multiply type.
2818         if (I.getType() != V->getType()) {
2819           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2820           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2821           Instruction::CastOps opcode = 
2822             (SrcBits == DstBits ? Instruction::BitCast : 
2823              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2824           V = InsertCastBefore(opcode, V, I.getType(), I);
2825         }
2826
2827         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2828         return BinaryOperator::CreateAnd(V, OtherOp);
2829       }
2830     }
2831   }
2832
2833   return Changed ? &I : 0;
2834 }
2835
2836 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2837   bool Changed = SimplifyCommutative(I);
2838   Value *Op0 = I.getOperand(0);
2839
2840   // Simplify mul instructions with a constant RHS...
2841   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2842     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2843       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2844       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2845       if (Op1F->isExactlyValue(1.0))
2846         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2847     } else if (isa<VectorType>(Op1->getType())) {
2848       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2849         // As above, vector X*splat(1.0) -> X in all defined cases.
2850         if (Constant *Splat = Op1V->getSplatValue()) {
2851           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2852             if (F->isExactlyValue(1.0))
2853               return ReplaceInstUsesWith(I, Op0);
2854         }
2855       }
2856     }
2857
2858     // Try to fold constant mul into select arguments.
2859     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2860       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2861         return R;
2862
2863     if (isa<PHINode>(Op0))
2864       if (Instruction *NV = FoldOpIntoPhi(I))
2865         return NV;
2866   }
2867
2868   if (Value *Op0v = dyn_castFNegVal(Op0, Context))     // -X * -Y = X*Y
2869     if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
2870       return BinaryOperator::CreateFMul(Op0v, Op1v);
2871
2872   return Changed ? &I : 0;
2873 }
2874
2875 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2876 /// instruction.
2877 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2878   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2879   
2880   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2881   int NonNullOperand = -1;
2882   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2883     if (ST->isNullValue())
2884       NonNullOperand = 2;
2885   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2886   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2887     if (ST->isNullValue())
2888       NonNullOperand = 1;
2889   
2890   if (NonNullOperand == -1)
2891     return false;
2892   
2893   Value *SelectCond = SI->getOperand(0);
2894   
2895   // Change the div/rem to use 'Y' instead of the select.
2896   I.setOperand(1, SI->getOperand(NonNullOperand));
2897   
2898   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2899   // problem.  However, the select, or the condition of the select may have
2900   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2901   // propagate the known value for the select into other uses of it, and
2902   // propagate a known value of the condition into its other users.
2903   
2904   // If the select and condition only have a single use, don't bother with this,
2905   // early exit.
2906   if (SI->use_empty() && SelectCond->hasOneUse())
2907     return true;
2908   
2909   // Scan the current block backward, looking for other uses of SI.
2910   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2911   
2912   while (BBI != BBFront) {
2913     --BBI;
2914     // If we found a call to a function, we can't assume it will return, so
2915     // information from below it cannot be propagated above it.
2916     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2917       break;
2918     
2919     // Replace uses of the select or its condition with the known values.
2920     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2921          I != E; ++I) {
2922       if (*I == SI) {
2923         *I = SI->getOperand(NonNullOperand);
2924         AddToWorkList(BBI);
2925       } else if (*I == SelectCond) {
2926         *I = NonNullOperand == 1 ? Context->getConstantIntTrue() :
2927                                    Context->getConstantIntFalse();
2928         AddToWorkList(BBI);
2929       }
2930     }
2931     
2932     // If we past the instruction, quit looking for it.
2933     if (&*BBI == SI)
2934       SI = 0;
2935     if (&*BBI == SelectCond)
2936       SelectCond = 0;
2937     
2938     // If we ran out of things to eliminate, break out of the loop.
2939     if (SelectCond == 0 && SI == 0)
2940       break;
2941     
2942   }
2943   return true;
2944 }
2945
2946
2947 /// This function implements the transforms on div instructions that work
2948 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2949 /// used by the visitors to those instructions.
2950 /// @brief Transforms common to all three div instructions
2951 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2952   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2953
2954   // undef / X -> 0        for integer.
2955   // undef / X -> undef    for FP (the undef could be a snan).
2956   if (isa<UndefValue>(Op0)) {
2957     if (Op0->getType()->isFPOrFPVector())
2958       return ReplaceInstUsesWith(I, Op0);
2959     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2960   }
2961
2962   // X / undef -> undef
2963   if (isa<UndefValue>(Op1))
2964     return ReplaceInstUsesWith(I, Op1);
2965
2966   return 0;
2967 }
2968
2969 /// This function implements the transforms common to both integer division
2970 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2971 /// division instructions.
2972 /// @brief Common integer divide transforms
2973 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2974   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2975
2976   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2977   if (Op0 == Op1) {
2978     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2979       Constant *CI = Context->getConstantInt(Ty->getElementType(), 1);
2980       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2981       return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
2982     }
2983
2984     Constant *CI = Context->getConstantInt(I.getType(), 1);
2985     return ReplaceInstUsesWith(I, CI);
2986   }
2987   
2988   if (Instruction *Common = commonDivTransforms(I))
2989     return Common;
2990   
2991   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2992   // This does not apply for fdiv.
2993   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2994     return &I;
2995
2996   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2997     // div X, 1 == X
2998     if (RHS->equalsInt(1))
2999       return ReplaceInstUsesWith(I, Op0);
3000
3001     // (X / C1) / C2  -> X / (C1*C2)
3002     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3003       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3004         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3005           if (MultiplyOverflows(RHS, LHSRHS,
3006                                 I.getOpcode()==Instruction::SDiv, Context))
3007             return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3008           else 
3009             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
3010                                       Context->getConstantExprMul(RHS, LHSRHS));
3011         }
3012
3013     if (!RHS->isZero()) { // avoid X udiv 0
3014       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3015         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3016           return R;
3017       if (isa<PHINode>(Op0))
3018         if (Instruction *NV = FoldOpIntoPhi(I))
3019           return NV;
3020     }
3021   }
3022
3023   // 0 / X == 0, we don't need to preserve faults!
3024   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3025     if (LHS->equalsInt(0))
3026       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3027
3028   // It can't be division by zero, hence it must be division by one.
3029   if (I.getType() == Type::Int1Ty)
3030     return ReplaceInstUsesWith(I, Op0);
3031
3032   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3033     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3034       // div X, 1 == X
3035       if (X->isOne())
3036         return ReplaceInstUsesWith(I, Op0);
3037   }
3038
3039   return 0;
3040 }
3041
3042 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3043   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3044
3045   // Handle the integer div common cases
3046   if (Instruction *Common = commonIDivTransforms(I))
3047     return Common;
3048
3049   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3050     // X udiv C^2 -> X >> C
3051     // Check to see if this is an unsigned division with an exact power of 2,
3052     // if so, convert to a right shift.
3053     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3054       return BinaryOperator::CreateLShr(Op0, 
3055             Context->getConstantInt(Op0->getType(), C->getValue().logBase2()));
3056
3057     // X udiv C, where C >= signbit
3058     if (C->getValue().isNegative()) {
3059       Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3060                                                     ICmpInst::ICMP_ULT, Op0, C),
3061                                       I);
3062       return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3063                                 Context->getConstantInt(I.getType(), 1));
3064     }
3065   }
3066
3067   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3068   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3069     if (RHSI->getOpcode() == Instruction::Shl &&
3070         isa<ConstantInt>(RHSI->getOperand(0))) {
3071       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3072       if (C1.isPowerOf2()) {
3073         Value *N = RHSI->getOperand(1);
3074         const Type *NTy = N->getType();
3075         if (uint32_t C2 = C1.logBase2()) {
3076           Constant *C2V = Context->getConstantInt(NTy, C2);
3077           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3078         }
3079         return BinaryOperator::CreateLShr(Op0, N);
3080       }
3081     }
3082   }
3083   
3084   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3085   // where C1&C2 are powers of two.
3086   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3087     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3088       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3089         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3090         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3091           // Compute the shift amounts
3092           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3093           // Construct the "on true" case of the select
3094           Constant *TC = Context->getConstantInt(Op0->getType(), TSA);
3095           Instruction *TSI = BinaryOperator::CreateLShr(
3096                                                  Op0, TC, SI->getName()+".t");
3097           TSI = InsertNewInstBefore(TSI, I);
3098   
3099           // Construct the "on false" case of the select
3100           Constant *FC = Context->getConstantInt(Op0->getType(), FSA); 
3101           Instruction *FSI = BinaryOperator::CreateLShr(
3102                                                  Op0, FC, SI->getName()+".f");
3103           FSI = InsertNewInstBefore(FSI, I);
3104
3105           // construct the select instruction and return it.
3106           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3107         }
3108       }
3109   return 0;
3110 }
3111
3112 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3113   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3114
3115   // Handle the integer div common cases
3116   if (Instruction *Common = commonIDivTransforms(I))
3117     return Common;
3118
3119   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3120     // sdiv X, -1 == -X
3121     if (RHS->isAllOnesValue())
3122       return BinaryOperator::CreateNeg(*Context, Op0);
3123   }
3124
3125   // If the sign bits of both operands are zero (i.e. we can prove they are
3126   // unsigned inputs), turn this into a udiv.
3127   if (I.getType()->isInteger()) {
3128     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3129     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3130       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3131       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3132     }
3133   }      
3134   
3135   return 0;
3136 }
3137
3138 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3139   return commonDivTransforms(I);
3140 }
3141
3142 /// This function implements the transforms on rem instructions that work
3143 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3144 /// is used by the visitors to those instructions.
3145 /// @brief Transforms common to all three rem instructions
3146 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3147   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3148
3149   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3150     if (I.getType()->isFPOrFPVector())
3151       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3152     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3153   }
3154   if (isa<UndefValue>(Op1))
3155     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3156
3157   // Handle cases involving: rem X, (select Cond, Y, Z)
3158   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3159     return &I;
3160
3161   return 0;
3162 }
3163
3164 /// This function implements the transforms common to both integer remainder
3165 /// instructions (urem and srem). It is called by the visitors to those integer
3166 /// remainder instructions.
3167 /// @brief Common integer remainder transforms
3168 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3169   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3170
3171   if (Instruction *common = commonRemTransforms(I))
3172     return common;
3173
3174   // 0 % X == 0 for integer, we don't need to preserve faults!
3175   if (Constant *LHS = dyn_cast<Constant>(Op0))
3176     if (LHS->isNullValue())
3177       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3178
3179   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3180     // X % 0 == undef, we don't need to preserve faults!
3181     if (RHS->equalsInt(0))
3182       return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
3183     
3184     if (RHS->equalsInt(1))  // X % 1 == 0
3185       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3186
3187     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3188       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3189         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3190           return R;
3191       } else if (isa<PHINode>(Op0I)) {
3192         if (Instruction *NV = FoldOpIntoPhi(I))
3193           return NV;
3194       }
3195
3196       // See if we can fold away this rem instruction.
3197       if (SimplifyDemandedInstructionBits(I))
3198         return &I;
3199     }
3200   }
3201
3202   return 0;
3203 }
3204
3205 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3206   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3207
3208   if (Instruction *common = commonIRemTransforms(I))
3209     return common;
3210   
3211   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3212     // X urem C^2 -> X and C
3213     // Check to see if this is an unsigned remainder with an exact power of 2,
3214     // if so, convert to a bitwise and.
3215     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3216       if (C->getValue().isPowerOf2())
3217         return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
3218   }
3219
3220   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3221     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3222     if (RHSI->getOpcode() == Instruction::Shl &&
3223         isa<ConstantInt>(RHSI->getOperand(0))) {
3224       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3225         Constant *N1 = Context->getAllOnesValue(I.getType());
3226         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3227                                                                    "tmp"), I);
3228         return BinaryOperator::CreateAnd(Op0, Add);
3229       }
3230     }
3231   }
3232
3233   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3234   // where C1&C2 are powers of two.
3235   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3236     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3237       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3238         // STO == 0 and SFO == 0 handled above.
3239         if ((STO->getValue().isPowerOf2()) && 
3240             (SFO->getValue().isPowerOf2())) {
3241           Value *TrueAnd = InsertNewInstBefore(
3242             BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3243                                       SI->getName()+".t"), I);
3244           Value *FalseAnd = InsertNewInstBefore(
3245             BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3246                                       SI->getName()+".f"), I);
3247           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3248         }
3249       }
3250   }
3251   
3252   return 0;
3253 }
3254
3255 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3256   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3257
3258   // Handle the integer rem common cases
3259   if (Instruction *common = commonIRemTransforms(I))
3260     return common;
3261   
3262   if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
3263     if (!isa<Constant>(RHSNeg) ||
3264         (isa<ConstantInt>(RHSNeg) &&
3265          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3266       // X % -Y -> X % Y
3267       AddUsesToWorkList(I);
3268       I.setOperand(1, RHSNeg);
3269       return &I;
3270     }
3271
3272   // If the sign bits of both operands are zero (i.e. we can prove they are
3273   // unsigned inputs), turn this into a urem.
3274   if (I.getType()->isInteger()) {
3275     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3276     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3277       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3278       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3279     }
3280   }
3281
3282   // If it's a constant vector, flip any negative values positive.
3283   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3284     unsigned VWidth = RHSV->getNumOperands();
3285
3286     bool hasNegative = false;
3287     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3288       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3289         if (RHS->getValue().isNegative())
3290           hasNegative = true;
3291
3292     if (hasNegative) {
3293       std::vector<Constant *> Elts(VWidth);
3294       for (unsigned i = 0; i != VWidth; ++i) {
3295         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3296           if (RHS->getValue().isNegative())
3297             Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
3298           else
3299             Elts[i] = RHS;
3300         }
3301       }
3302
3303       Constant *NewRHSV = Context->getConstantVector(Elts);
3304       if (NewRHSV != RHSV) {
3305         AddUsesToWorkList(I);
3306         I.setOperand(1, NewRHSV);
3307         return &I;
3308       }
3309     }
3310   }
3311
3312   return 0;
3313 }
3314
3315 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3316   return commonRemTransforms(I);
3317 }
3318
3319 // isOneBitSet - Return true if there is exactly one bit set in the specified
3320 // constant.
3321 static bool isOneBitSet(const ConstantInt *CI) {
3322   return CI->getValue().isPowerOf2();
3323 }
3324
3325 // isHighOnes - Return true if the constant is of the form 1+0+.
3326 // This is the same as lowones(~X).
3327 static bool isHighOnes(const ConstantInt *CI) {
3328   return (~CI->getValue() + 1).isPowerOf2();
3329 }
3330
3331 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3332 /// are carefully arranged to allow folding of expressions such as:
3333 ///
3334 ///      (A < B) | (A > B) --> (A != B)
3335 ///
3336 /// Note that this is only valid if the first and second predicates have the
3337 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3338 ///
3339 /// Three bits are used to represent the condition, as follows:
3340 ///   0  A > B
3341 ///   1  A == B
3342 ///   2  A < B
3343 ///
3344 /// <=>  Value  Definition
3345 /// 000     0   Always false
3346 /// 001     1   A >  B
3347 /// 010     2   A == B
3348 /// 011     3   A >= B
3349 /// 100     4   A <  B
3350 /// 101     5   A != B
3351 /// 110     6   A <= B
3352 /// 111     7   Always true
3353 ///  
3354 static unsigned getICmpCode(const ICmpInst *ICI) {
3355   switch (ICI->getPredicate()) {
3356     // False -> 0
3357   case ICmpInst::ICMP_UGT: return 1;  // 001
3358   case ICmpInst::ICMP_SGT: return 1;  // 001
3359   case ICmpInst::ICMP_EQ:  return 2;  // 010
3360   case ICmpInst::ICMP_UGE: return 3;  // 011
3361   case ICmpInst::ICMP_SGE: return 3;  // 011
3362   case ICmpInst::ICMP_ULT: return 4;  // 100
3363   case ICmpInst::ICMP_SLT: return 4;  // 100
3364   case ICmpInst::ICMP_NE:  return 5;  // 101
3365   case ICmpInst::ICMP_ULE: return 6;  // 110
3366   case ICmpInst::ICMP_SLE: return 6;  // 110
3367     // True -> 7
3368   default:
3369     LLVM_UNREACHABLE("Invalid ICmp predicate!");
3370     return 0;
3371   }
3372 }
3373
3374 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3375 /// predicate into a three bit mask. It also returns whether it is an ordered
3376 /// predicate by reference.
3377 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3378   isOrdered = false;
3379   switch (CC) {
3380   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3381   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3382   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3383   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3384   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3385   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3386   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3387   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3388   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3389   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3390   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3391   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3392   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3393   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3394     // True -> 7
3395   default:
3396     // Not expecting FCMP_FALSE and FCMP_TRUE;
3397     LLVM_UNREACHABLE("Unexpected FCmp predicate!");
3398     return 0;
3399   }
3400 }
3401
3402 /// getICmpValue - This is the complement of getICmpCode, which turns an
3403 /// opcode and two operands into either a constant true or false, or a brand 
3404 /// new ICmp instruction. The sign is passed in to determine which kind
3405 /// of predicate to use in the new icmp instruction.
3406 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3407                            LLVMContext *Context) {
3408   switch (code) {
3409   default: LLVM_UNREACHABLE("Illegal ICmp code!");
3410   case  0: return Context->getConstantIntFalse();
3411   case  1: 
3412     if (sign)
3413       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
3414     else
3415       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3416   case  2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ,  LHS, RHS);
3417   case  3: 
3418     if (sign)
3419       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
3420     else
3421       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
3422   case  4: 
3423     if (sign)
3424       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
3425     else
3426       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3427   case  5: return new ICmpInst(*Context, ICmpInst::ICMP_NE,  LHS, RHS);
3428   case  6: 
3429     if (sign)
3430       return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
3431     else
3432       return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
3433   case  7: return Context->getConstantIntTrue();
3434   }
3435 }
3436
3437 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3438 /// opcode and two operands into either a FCmp instruction. isordered is passed
3439 /// in to determine which kind of predicate to use in the new fcmp instruction.
3440 static Value *getFCmpValue(bool isordered, unsigned code,
3441                            Value *LHS, Value *RHS, LLVMContext *Context) {
3442   switch (code) {
3443   default: LLVM_UNREACHABLE("Illegal FCmp code!");
3444   case  0:
3445     if (isordered)
3446       return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
3447     else
3448       return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
3449   case  1: 
3450     if (isordered)
3451       return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
3452     else
3453       return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
3454   case  2: 
3455     if (isordered)
3456       return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
3457     else
3458       return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
3459   case  3: 
3460     if (isordered)
3461       return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
3462     else
3463       return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
3464   case  4: 
3465     if (isordered)
3466       return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
3467     else
3468       return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
3469   case  5: 
3470     if (isordered)
3471       return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
3472     else
3473       return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
3474   case  6: 
3475     if (isordered)
3476       return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
3477     else
3478       return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
3479   case  7: return Context->getConstantIntTrue();
3480   }
3481 }
3482
3483 /// PredicatesFoldable - Return true if both predicates match sign or if at
3484 /// least one of them is an equality comparison (which is signless).
3485 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3486   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3487          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3488          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3489 }
3490
3491 namespace { 
3492 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3493 struct FoldICmpLogical {
3494   InstCombiner &IC;
3495   Value *LHS, *RHS;
3496   ICmpInst::Predicate pred;
3497   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3498     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3499       pred(ICI->getPredicate()) {}
3500   bool shouldApply(Value *V) const {
3501     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3502       if (PredicatesFoldable(pred, ICI->getPredicate()))
3503         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3504                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3505     return false;
3506   }
3507   Instruction *apply(Instruction &Log) const {
3508     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3509     if (ICI->getOperand(0) != LHS) {
3510       assert(ICI->getOperand(1) == LHS);
3511       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3512     }
3513
3514     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3515     unsigned LHSCode = getICmpCode(ICI);
3516     unsigned RHSCode = getICmpCode(RHSICI);
3517     unsigned Code;
3518     switch (Log.getOpcode()) {
3519     case Instruction::And: Code = LHSCode & RHSCode; break;
3520     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3521     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3522     default: LLVM_UNREACHABLE("Illegal logical opcode!"); return 0;
3523     }
3524
3525     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3526                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3527       
3528     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3529     if (Instruction *I = dyn_cast<Instruction>(RV))
3530       return I;
3531     // Otherwise, it's a constant boolean value...
3532     return IC.ReplaceInstUsesWith(Log, RV);
3533   }
3534 };
3535 } // end anonymous namespace
3536
3537 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3538 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3539 // guaranteed to be a binary operator.
3540 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3541                                     ConstantInt *OpRHS,
3542                                     ConstantInt *AndRHS,
3543                                     BinaryOperator &TheAnd) {
3544   Value *X = Op->getOperand(0);
3545   Constant *Together = 0;
3546   if (!Op->isShift())
3547     Together = Context->getConstantExprAnd(AndRHS, OpRHS);
3548
3549   switch (Op->getOpcode()) {
3550   case Instruction::Xor:
3551     if (Op->hasOneUse()) {
3552       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3553       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3554       InsertNewInstBefore(And, TheAnd);
3555       And->takeName(Op);
3556       return BinaryOperator::CreateXor(And, Together);
3557     }
3558     break;
3559   case Instruction::Or:
3560     if (Together == AndRHS) // (X | C) & C --> C
3561       return ReplaceInstUsesWith(TheAnd, AndRHS);
3562
3563     if (Op->hasOneUse() && Together != OpRHS) {
3564       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3565       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3566       InsertNewInstBefore(Or, TheAnd);
3567       Or->takeName(Op);
3568       return BinaryOperator::CreateAnd(Or, AndRHS);
3569     }
3570     break;
3571   case Instruction::Add:
3572     if (Op->hasOneUse()) {
3573       // Adding a one to a single bit bit-field should be turned into an XOR
3574       // of the bit.  First thing to check is to see if this AND is with a
3575       // single bit constant.
3576       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3577
3578       // If there is only one bit set...
3579       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3580         // Ok, at this point, we know that we are masking the result of the
3581         // ADD down to exactly one bit.  If the constant we are adding has
3582         // no bits set below this bit, then we can eliminate the ADD.
3583         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3584
3585         // Check to see if any bits below the one bit set in AndRHSV are set.
3586         if ((AddRHS & (AndRHSV-1)) == 0) {
3587           // If not, the only thing that can effect the output of the AND is
3588           // the bit specified by AndRHSV.  If that bit is set, the effect of
3589           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3590           // no effect.
3591           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3592             TheAnd.setOperand(0, X);
3593             return &TheAnd;
3594           } else {
3595             // Pull the XOR out of the AND.
3596             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3597             InsertNewInstBefore(NewAnd, TheAnd);
3598             NewAnd->takeName(Op);
3599             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3600           }
3601         }
3602       }
3603     }
3604     break;
3605
3606   case Instruction::Shl: {
3607     // We know that the AND will not produce any of the bits shifted in, so if
3608     // the anded constant includes them, clear them now!
3609     //
3610     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3611     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3612     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3613     ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShlMask);
3614
3615     if (CI->getValue() == ShlMask) { 
3616     // Masking out bits that the shift already masks
3617       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3618     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3619       TheAnd.setOperand(1, CI);
3620       return &TheAnd;
3621     }
3622     break;
3623   }
3624   case Instruction::LShr:
3625   {
3626     // We know that the AND will not produce any of the bits shifted in, so if
3627     // the anded constant includes them, clear them now!  This only applies to
3628     // unsigned shifts, because a signed shr may bring in set bits!
3629     //
3630     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3631     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3632     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3633     ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3634
3635     if (CI->getValue() == ShrMask) {   
3636     // Masking out bits that the shift already masks.
3637       return ReplaceInstUsesWith(TheAnd, Op);
3638     } else if (CI != AndRHS) {
3639       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3640       return &TheAnd;
3641     }
3642     break;
3643   }
3644   case Instruction::AShr:
3645     // Signed shr.
3646     // See if this is shifting in some sign extension, then masking it out
3647     // with an and.
3648     if (Op->hasOneUse()) {
3649       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3650       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3651       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3652       Constant *C = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3653       if (C == AndRHS) {          // Masking out bits shifted in.
3654         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3655         // Make the argument unsigned.
3656         Value *ShVal = Op->getOperand(0);
3657         ShVal = InsertNewInstBefore(
3658             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3659                                    Op->getName()), TheAnd);
3660         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3661       }
3662     }
3663     break;
3664   }
3665   return 0;
3666 }
3667
3668
3669 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3670 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3671 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3672 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3673 /// insert new instructions.
3674 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3675                                            bool isSigned, bool Inside, 
3676                                            Instruction &IB) {
3677   assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ? 
3678             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3679          "Lo is not <= Hi in range emission code!");
3680     
3681   if (Inside) {
3682     if (Lo == Hi)  // Trivially false.
3683       return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
3684
3685     // V >= Min && V < Hi --> V < Hi
3686     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3687       ICmpInst::Predicate pred = (isSigned ? 
3688         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3689       return new ICmpInst(*Context, pred, V, Hi);
3690     }
3691
3692     // Emit V-Lo <u Hi-Lo
3693     Constant *NegLo = Context->getConstantExprNeg(Lo);
3694     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3695     InsertNewInstBefore(Add, IB);
3696     Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
3697     return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
3698   }
3699
3700   if (Lo == Hi)  // Trivially true.
3701     return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
3702
3703   // V < Min || V >= Hi -> V > Hi-1
3704   Hi = SubOne(cast<ConstantInt>(Hi), Context);
3705   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3706     ICmpInst::Predicate pred = (isSigned ? 
3707         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3708     return new ICmpInst(*Context, pred, V, Hi);
3709   }
3710
3711   // Emit V-Lo >u Hi-1-Lo
3712   // Note that Hi has already had one subtracted from it, above.
3713   ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
3714   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3715   InsertNewInstBefore(Add, IB);
3716   Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
3717   return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
3718 }
3719
3720 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3721 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3722 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3723 // not, since all 1s are not contiguous.
3724 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3725   const APInt& V = Val->getValue();
3726   uint32_t BitWidth = Val->getType()->getBitWidth();
3727   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3728
3729   // look for the first zero bit after the run of ones
3730   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3731   // look for the first non-zero bit
3732   ME = V.getActiveBits(); 
3733   return true;
3734 }
3735
3736 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3737 /// where isSub determines whether the operator is a sub.  If we can fold one of
3738 /// the following xforms:
3739 /// 
3740 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3741 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3742 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3743 ///
3744 /// return (A +/- B).
3745 ///
3746 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3747                                         ConstantInt *Mask, bool isSub,
3748                                         Instruction &I) {
3749   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3750   if (!LHSI || LHSI->getNumOperands() != 2 ||
3751       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3752
3753   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3754
3755   switch (LHSI->getOpcode()) {
3756   default: return 0;
3757   case Instruction::And:
3758     if (Context->getConstantExprAnd(N, Mask) == Mask) {
3759       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3760       if ((Mask->getValue().countLeadingZeros() + 
3761            Mask->getValue().countPopulation()) == 
3762           Mask->getValue().getBitWidth())
3763         break;
3764
3765       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3766       // part, we don't need any explicit masks to take them out of A.  If that
3767       // is all N is, ignore it.
3768       uint32_t MB = 0, ME = 0;
3769       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3770         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3771         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3772         if (MaskedValueIsZero(RHS, Mask))
3773           break;
3774       }
3775     }
3776     return 0;
3777   case Instruction::Or:
3778   case Instruction::Xor:
3779     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3780     if ((Mask->getValue().countLeadingZeros() + 
3781          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3782         && Context->getConstantExprAnd(N, Mask)->isNullValue())
3783       break;
3784     return 0;
3785   }
3786   
3787   Instruction *New;
3788   if (isSub)
3789     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3790   else
3791     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3792   return InsertNewInstBefore(New, I);
3793 }
3794
3795 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3796 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3797                                           ICmpInst *LHS, ICmpInst *RHS) {
3798   Value *Val, *Val2;
3799   ConstantInt *LHSCst, *RHSCst;
3800   ICmpInst::Predicate LHSCC, RHSCC;
3801   
3802   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3803   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3804                          m_ConstantInt(LHSCst)), *Context) ||
3805       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3806                          m_ConstantInt(RHSCst)), *Context))
3807     return 0;
3808   
3809   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3810   // where C is a power of 2
3811   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3812       LHSCst->getValue().isPowerOf2()) {
3813     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3814     InsertNewInstBefore(NewOr, I);
3815     return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
3816   }
3817   
3818   // From here on, we only handle:
3819   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3820   if (Val != Val2) return 0;
3821   
3822   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3823   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3824       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3825       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3826       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3827     return 0;
3828   
3829   // We can't fold (ugt x, C) & (sgt x, C2).
3830   if (!PredicatesFoldable(LHSCC, RHSCC))
3831     return 0;
3832     
3833   // Ensure that the larger constant is on the RHS.
3834   bool ShouldSwap;
3835   if (ICmpInst::isSignedPredicate(LHSCC) ||
3836       (ICmpInst::isEquality(LHSCC) && 
3837        ICmpInst::isSignedPredicate(RHSCC)))
3838     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3839   else
3840     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3841     
3842   if (ShouldSwap) {
3843     std::swap(LHS, RHS);
3844     std::swap(LHSCst, RHSCst);
3845     std::swap(LHSCC, RHSCC);
3846   }
3847
3848   // At this point, we know we have have two icmp instructions
3849   // comparing a value against two constants and and'ing the result
3850   // together.  Because of the above check, we know that we only have
3851   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3852   // (from the FoldICmpLogical check above), that the two constants 
3853   // are not equal and that the larger constant is on the RHS
3854   assert(LHSCst != RHSCst && "Compares not folded above?");
3855
3856   switch (LHSCC) {
3857   default: LLVM_UNREACHABLE("Unknown integer condition code!");
3858   case ICmpInst::ICMP_EQ:
3859     switch (RHSCC) {
3860     default: LLVM_UNREACHABLE("Unknown integer condition code!");
3861     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3862     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3863     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3864       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3865     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3866     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3867     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3868       return ReplaceInstUsesWith(I, LHS);
3869     }
3870   case ICmpInst::ICMP_NE:
3871     switch (RHSCC) {
3872     default: LLVM_UNREACHABLE("Unknown integer condition code!");
3873     case ICmpInst::ICMP_ULT:
3874       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
3875         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
3876       break;                        // (X != 13 & X u< 15) -> no change
3877     case ICmpInst::ICMP_SLT:
3878       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
3879         return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
3880       break;                        // (X != 13 & X s< 15) -> no change
3881     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3882     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3883     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3884       return ReplaceInstUsesWith(I, RHS);
3885     case ICmpInst::ICMP_NE:
3886       if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3887         Constant *AddCST = Context->getConstantExprNeg(LHSCst);
3888         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3889                                                      Val->getName()+".off");
3890         InsertNewInstBefore(Add, I);
3891         return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
3892                             Context->getConstantInt(Add->getType(), 1));
3893       }
3894       break;                        // (X != 13 & X != 15) -> no change
3895     }
3896     break;
3897   case ICmpInst::ICMP_ULT:
3898     switch (RHSCC) {
3899     default: LLVM_UNREACHABLE("Unknown integer condition code!");
3900     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3901     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3902       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3903     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3904       break;
3905     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3906     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3907       return ReplaceInstUsesWith(I, LHS);
3908     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3909       break;
3910     }
3911     break;
3912   case ICmpInst::ICMP_SLT:
3913     switch (RHSCC) {
3914     default: LLVM_UNREACHABLE("Unknown integer condition code!");
3915     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3916     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3917       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3918     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3919       break;
3920     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3921     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3922       return ReplaceInstUsesWith(I, LHS);
3923     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3924       break;
3925     }
3926     break;
3927   case ICmpInst::ICMP_UGT:
3928     switch (RHSCC) {
3929     default: LLVM_UNREACHABLE("Unknown integer condition code!");
3930     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3931     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3932       return ReplaceInstUsesWith(I, RHS);
3933     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3934       break;
3935     case ICmpInst::ICMP_NE:
3936       if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
3937         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3938       break;                        // (X u> 13 & X != 15) -> no change
3939     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3940       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3941                              RHSCst, false, true, I);
3942     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3943       break;
3944     }
3945     break;
3946   case ICmpInst::ICMP_SGT:
3947     switch (RHSCC) {
3948     default: LLVM_UNREACHABLE("Unknown integer condition code!");
3949     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3950     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3951       return ReplaceInstUsesWith(I, RHS);
3952     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3953       break;
3954     case ICmpInst::ICMP_NE:
3955       if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
3956         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3957       break;                        // (X s> 13 & X != 15) -> no change
3958     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3959       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3960                              RHSCst, true, true, I);
3961     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3962       break;
3963     }
3964     break;
3965   }
3966  
3967   return 0;
3968 }
3969
3970
3971 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3972   bool Changed = SimplifyCommutative(I);
3973   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3974
3975   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3976     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3977
3978   // and X, X = X
3979   if (Op0 == Op1)
3980     return ReplaceInstUsesWith(I, Op1);
3981
3982   // See if we can simplify any instructions used by the instruction whose sole 
3983   // purpose is to compute bits we don't care about.
3984   if (SimplifyDemandedInstructionBits(I))
3985     return &I;
3986   if (isa<VectorType>(I.getType())) {
3987     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3988       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3989         return ReplaceInstUsesWith(I, I.getOperand(0));
3990     } else if (isa<ConstantAggregateZero>(Op1)) {
3991       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3992     }
3993   }
3994
3995   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3996     const APInt& AndRHSMask = AndRHS->getValue();
3997     APInt NotAndRHS(~AndRHSMask);
3998
3999     // Optimize a variety of ((val OP C1) & C2) combinations...
4000     if (isa<BinaryOperator>(Op0)) {
4001       Instruction *Op0I = cast<Instruction>(Op0);
4002       Value *Op0LHS = Op0I->getOperand(0);
4003       Value *Op0RHS = Op0I->getOperand(1);
4004       switch (Op0I->getOpcode()) {
4005       case Instruction::Xor:
4006       case Instruction::Or:
4007         // If the mask is only needed on one incoming arm, push it up.
4008         if (Op0I->hasOneUse()) {
4009           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4010             // Not masking anything out for the LHS, move to RHS.
4011             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
4012                                                    Op0RHS->getName()+".masked");
4013             InsertNewInstBefore(NewRHS, I);
4014             return BinaryOperator::Create(
4015                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4016           }
4017           if (!isa<Constant>(Op0RHS) &&
4018               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4019             // Not masking anything out for the RHS, move to LHS.
4020             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
4021                                                    Op0LHS->getName()+".masked");
4022             InsertNewInstBefore(NewLHS, I);
4023             return BinaryOperator::Create(
4024                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4025           }
4026         }
4027
4028         break;
4029       case Instruction::Add:
4030         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4031         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4032         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4033         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4034           return BinaryOperator::CreateAnd(V, AndRHS);
4035         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4036           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4037         break;
4038
4039       case Instruction::Sub:
4040         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4041         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4042         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4043         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4044           return BinaryOperator::CreateAnd(V, AndRHS);
4045
4046         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4047         // has 1's for all bits that the subtraction with A might affect.
4048         if (Op0I->hasOneUse()) {
4049           uint32_t BitWidth = AndRHSMask.getBitWidth();
4050           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4051           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4052
4053           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4054           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4055               MaskedValueIsZero(Op0LHS, Mask)) {
4056             Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
4057             InsertNewInstBefore(NewNeg, I);
4058             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4059           }
4060         }
4061         break;
4062
4063       case Instruction::Shl:
4064       case Instruction::LShr:
4065         // (1 << x) & 1 --> zext(x == 0)
4066         // (1 >> x) & 1 --> zext(x == 0)
4067         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4068           Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4069                                     Op0RHS, Context->getNullValue(I.getType()));
4070           InsertNewInstBefore(NewICmp, I);
4071           return new ZExtInst(NewICmp, I.getType());
4072         }
4073         break;
4074       }
4075
4076       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4077         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4078           return Res;
4079     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4080       // If this is an integer truncation or change from signed-to-unsigned, and
4081       // if the source is an and/or with immediate, transform it.  This
4082       // frequently occurs for bitfield accesses.
4083       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4084         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4085             CastOp->getNumOperands() == 2)
4086           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4087             if (CastOp->getOpcode() == Instruction::And) {
4088               // Change: and (cast (and X, C1) to T), C2
4089               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4090               // This will fold the two constants together, which may allow 
4091               // other simplifications.
4092               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4093                 CastOp->getOperand(0), I.getType(), 
4094                 CastOp->getName()+".shrunk");
4095               NewCast = InsertNewInstBefore(NewCast, I);
4096               // trunc_or_bitcast(C1)&C2
4097               Constant *C3 =
4098                       Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4099               C3 = Context->getConstantExprAnd(C3, AndRHS);
4100               return BinaryOperator::CreateAnd(NewCast, C3);
4101             } else if (CastOp->getOpcode() == Instruction::Or) {
4102               // Change: and (cast (or X, C1) to T), C2
4103               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4104               Constant *C3 =
4105                       Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4106               if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4107                 // trunc(C1)&C2
4108                 return ReplaceInstUsesWith(I, AndRHS);
4109             }
4110           }
4111       }
4112     }
4113
4114     // Try to fold constant and into select arguments.
4115     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4116       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4117         return R;
4118     if (isa<PHINode>(Op0))
4119       if (Instruction *NV = FoldOpIntoPhi(I))
4120         return NV;
4121   }
4122
4123   Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4124   Value *Op1NotVal = dyn_castNotVal(Op1, Context);
4125
4126   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4127     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
4128
4129   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4130   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4131     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4132                                                I.getName()+".demorgan");
4133     InsertNewInstBefore(Or, I);
4134     return BinaryOperator::CreateNot(*Context, Or);
4135   }
4136   
4137   {
4138     Value *A = 0, *B = 0, *C = 0, *D = 0;
4139     if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
4140       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4141         return ReplaceInstUsesWith(I, Op1);
4142     
4143       // (A|B) & ~(A&B) -> A^B
4144       if (match(Op1, 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 (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
4151       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4152         return ReplaceInstUsesWith(I, Op0);
4153
4154       // ~(A&B) & (A|B) -> A^B
4155       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4156         if ((A == C && B == D) || (A == D && B == C))
4157           return BinaryOperator::CreateXor(A, B);
4158       }
4159     }
4160     
4161     if (Op0->hasOneUse() &&
4162         match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4163       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4164         I.swapOperands();     // Simplify below
4165         std::swap(Op0, Op1);
4166       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4167         cast<BinaryOperator>(Op0)->swapOperands();
4168         I.swapOperands();     // Simplify below
4169         std::swap(Op0, Op1);
4170       }
4171     }
4172
4173     if (Op1->hasOneUse() &&
4174         match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4175       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4176         cast<BinaryOperator>(Op1)->swapOperands();
4177         std::swap(A, B);
4178       }
4179       if (A == Op0) {                                // A&(A^B) -> A & ~B
4180         Instruction *NotB = BinaryOperator::CreateNot(*Context, B, "tmp");
4181         InsertNewInstBefore(NotB, I);
4182         return BinaryOperator::CreateAnd(A, NotB);
4183       }
4184     }
4185
4186     // (A&((~A)|B)) -> A&B
4187     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4188         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
4189       return BinaryOperator::CreateAnd(A, Op1);
4190     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4191         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
4192       return BinaryOperator::CreateAnd(A, Op0);
4193   }
4194   
4195   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4196     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4197     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4198       return R;
4199
4200     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4201       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4202         return Res;
4203   }
4204
4205   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4206   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4207     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4208       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4209         const Type *SrcTy = Op0C->getOperand(0)->getType();
4210         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4211             // Only do this if the casts both really cause code to be generated.
4212             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4213                               I.getType(), TD) &&
4214             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4215                               I.getType(), TD)) {
4216           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4217                                                          Op1C->getOperand(0),
4218                                                          I.getName());
4219           InsertNewInstBefore(NewOp, I);
4220           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4221         }
4222       }
4223     
4224   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4225   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4226     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4227       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4228           SI0->getOperand(1) == SI1->getOperand(1) &&
4229           (SI0->hasOneUse() || SI1->hasOneUse())) {
4230         Instruction *NewOp =
4231           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4232                                                         SI1->getOperand(0),
4233                                                         SI0->getName()), I);
4234         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4235                                       SI1->getOperand(1));
4236       }
4237   }
4238
4239   // If and'ing two fcmp, try combine them into one.
4240   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4241     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4242       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4243           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4244         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4245         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4246           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4247             // If either of the constants are nans, then the whole thing returns
4248             // false.
4249             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4250               return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4251             return new FCmpInst(*Context, FCmpInst::FCMP_ORD, 
4252                                 LHS->getOperand(0), RHS->getOperand(0));
4253           }
4254       } else {
4255         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4256         FCmpInst::Predicate Op0CC, Op1CC;
4257         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4258                   m_Value(Op0RHS)), *Context) &&
4259             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4260                   m_Value(Op1RHS)), *Context)) {
4261           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4262             // Swap RHS operands to match LHS.
4263             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4264             std::swap(Op1LHS, Op1RHS);
4265           }
4266           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4267             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4268             if (Op0CC == Op1CC)
4269               return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4270                                   Op0LHS, Op0RHS);
4271             else if (Op0CC == FCmpInst::FCMP_FALSE ||
4272                      Op1CC == FCmpInst::FCMP_FALSE)
4273               return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4274             else if (Op0CC == FCmpInst::FCMP_TRUE)
4275               return ReplaceInstUsesWith(I, Op1);
4276             else if (Op1CC == FCmpInst::FCMP_TRUE)
4277               return ReplaceInstUsesWith(I, Op0);
4278             bool Op0Ordered;
4279             bool Op1Ordered;
4280             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4281             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4282             if (Op1Pred == 0) {
4283               std::swap(Op0, Op1);
4284               std::swap(Op0Pred, Op1Pred);
4285               std::swap(Op0Ordered, Op1Ordered);
4286             }
4287             if (Op0Pred == 0) {
4288               // uno && ueq -> uno && (uno || eq) -> ueq
4289               // ord && olt -> ord && (ord && lt) -> olt
4290               if (Op0Ordered == Op1Ordered)
4291                 return ReplaceInstUsesWith(I, Op1);
4292               // uno && oeq -> uno && (ord && eq) -> false
4293               // uno && ord -> false
4294               if (!Op0Ordered)
4295                 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4296               // ord && ueq -> ord && (uno || eq) -> oeq
4297               return cast<Instruction>(getFCmpValue(true, Op1Pred,
4298                                                     Op0LHS, Op0RHS, Context));
4299             }
4300           }
4301         }
4302       }
4303     }
4304   }
4305
4306   return Changed ? &I : 0;
4307 }
4308
4309 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4310 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4311 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4312 /// the expression came from the corresponding "byte swapped" byte in some other
4313 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4314 /// we know that the expression deposits the low byte of %X into the high byte
4315 /// of the bswap result and that all other bytes are zero.  This expression is
4316 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4317 /// match.
4318 ///
4319 /// This function returns true if the match was unsuccessful and false if so.
4320 /// On entry to the function the "OverallLeftShift" is a signed integer value
4321 /// indicating the number of bytes that the subexpression is later shifted.  For
4322 /// example, if the expression is later right shifted by 16 bits, the
4323 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4324 /// byte of ByteValues is actually being set.
4325 ///
4326 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4327 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4328 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4329 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4330 /// always in the local (OverallLeftShift) coordinate space.
4331 ///
4332 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4333                               SmallVector<Value*, 8> &ByteValues) {
4334   if (Instruction *I = dyn_cast<Instruction>(V)) {
4335     // If this is an or instruction, it may be an inner node of the bswap.
4336     if (I->getOpcode() == Instruction::Or) {
4337       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4338                                ByteValues) ||
4339              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4340                                ByteValues);
4341     }
4342   
4343     // If this is a logical shift by a constant multiple of 8, recurse with
4344     // OverallLeftShift and ByteMask adjusted.
4345     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4346       unsigned ShAmt = 
4347         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4348       // Ensure the shift amount is defined and of a byte value.
4349       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4350         return true;
4351
4352       unsigned ByteShift = ShAmt >> 3;
4353       if (I->getOpcode() == Instruction::Shl) {
4354         // X << 2 -> collect(X, +2)
4355         OverallLeftShift += ByteShift;
4356         ByteMask >>= ByteShift;
4357       } else {
4358         // X >>u 2 -> collect(X, -2)
4359         OverallLeftShift -= ByteShift;
4360         ByteMask <<= ByteShift;
4361         ByteMask &= (~0U >> (32-ByteValues.size()));
4362       }
4363
4364       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4365       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4366
4367       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4368                                ByteValues);
4369     }
4370
4371     // If this is a logical 'and' with a mask that clears bytes, clear the
4372     // corresponding bytes in ByteMask.
4373     if (I->getOpcode() == Instruction::And &&
4374         isa<ConstantInt>(I->getOperand(1))) {
4375       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4376       unsigned NumBytes = ByteValues.size();
4377       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4378       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4379       
4380       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4381         // If this byte is masked out by a later operation, we don't care what
4382         // the and mask is.
4383         if ((ByteMask & (1 << i)) == 0)
4384           continue;
4385         
4386         // If the AndMask is all zeros for this byte, clear the bit.
4387         APInt MaskB = AndMask & Byte;
4388         if (MaskB == 0) {
4389           ByteMask &= ~(1U << i);
4390           continue;
4391         }
4392         
4393         // If the AndMask is not all ones for this byte, it's not a bytezap.
4394         if (MaskB != Byte)
4395           return true;
4396
4397         // Otherwise, this byte is kept.
4398       }
4399
4400       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4401                                ByteValues);
4402     }
4403   }
4404   
4405   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4406   // the input value to the bswap.  Some observations: 1) if more than one byte
4407   // is demanded from this input, then it could not be successfully assembled
4408   // into a byteswap.  At least one of the two bytes would not be aligned with
4409   // their ultimate destination.
4410   if (!isPowerOf2_32(ByteMask)) return true;
4411   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4412   
4413   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4414   // is demanded, it needs to go into byte 0 of the result.  This means that the
4415   // byte needs to be shifted until it lands in the right byte bucket.  The
4416   // shift amount depends on the position: if the byte is coming from the high
4417   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4418   // low part, it must be shifted left.
4419   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4420   if (InputByteNo < ByteValues.size()/2) {
4421     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4422       return true;
4423   } else {
4424     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4425       return true;
4426   }
4427   
4428   // If the destination byte value is already defined, the values are or'd
4429   // together, which isn't a bswap (unless it's an or of the same bits).
4430   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4431     return true;
4432   ByteValues[DestByteNo] = V;
4433   return false;
4434 }
4435
4436 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4437 /// If so, insert the new bswap intrinsic and return it.
4438 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4439   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4440   if (!ITy || ITy->getBitWidth() % 16 || 
4441       // ByteMask only allows up to 32-byte values.
4442       ITy->getBitWidth() > 32*8) 
4443     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4444   
4445   /// ByteValues - For each byte of the result, we keep track of which value
4446   /// defines each byte.
4447   SmallVector<Value*, 8> ByteValues;
4448   ByteValues.resize(ITy->getBitWidth()/8);
4449     
4450   // Try to find all the pieces corresponding to the bswap.
4451   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4452   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4453     return 0;
4454   
4455   // Check to see if all of the bytes come from the same value.
4456   Value *V = ByteValues[0];
4457   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4458   
4459   // Check to make sure that all of the bytes come from the same value.
4460   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4461     if (ByteValues[i] != V)
4462       return 0;
4463   const Type *Tys[] = { ITy };
4464   Module *M = I.getParent()->getParent()->getParent();
4465   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4466   return CallInst::Create(F, V);
4467 }
4468
4469 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4470 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4471 /// we can simplify this expression to "cond ? C : D or B".
4472 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4473                                          Value *C, Value *D,
4474                                          LLVMContext *Context) {
4475   // If A is not a select of -1/0, this cannot match.
4476   Value *Cond = 0;
4477   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
4478     return 0;
4479
4480   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4481   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4482     return SelectInst::Create(Cond, C, B);
4483   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4484     return SelectInst::Create(Cond, C, B);
4485   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4486   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4487     return SelectInst::Create(Cond, C, D);
4488   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4489     return SelectInst::Create(Cond, C, D);
4490   return 0;
4491 }
4492
4493 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4494 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4495                                          ICmpInst *LHS, ICmpInst *RHS) {
4496   Value *Val, *Val2;
4497   ConstantInt *LHSCst, *RHSCst;
4498   ICmpInst::Predicate LHSCC, RHSCC;
4499   
4500   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4501   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4502              m_ConstantInt(LHSCst)), *Context) ||
4503       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4504              m_ConstantInt(RHSCst)), *Context))
4505     return 0;
4506   
4507   // From here on, we only handle:
4508   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4509   if (Val != Val2) return 0;
4510   
4511   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4512   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4513       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4514       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4515       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4516     return 0;
4517   
4518   // We can't fold (ugt x, C) | (sgt x, C2).
4519   if (!PredicatesFoldable(LHSCC, RHSCC))
4520     return 0;
4521   
4522   // Ensure that the larger constant is on the RHS.
4523   bool ShouldSwap;
4524   if (ICmpInst::isSignedPredicate(LHSCC) ||
4525       (ICmpInst::isEquality(LHSCC) && 
4526        ICmpInst::isSignedPredicate(RHSCC)))
4527     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4528   else
4529     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4530   
4531   if (ShouldSwap) {
4532     std::swap(LHS, RHS);
4533     std::swap(LHSCst, RHSCst);
4534     std::swap(LHSCC, RHSCC);
4535   }
4536   
4537   // At this point, we know we have have two icmp instructions
4538   // comparing a value against two constants and or'ing the result
4539   // together.  Because of the above check, we know that we only have
4540   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4541   // FoldICmpLogical check above), that the two constants are not
4542   // equal.
4543   assert(LHSCst != RHSCst && "Compares not folded above?");
4544
4545   switch (LHSCC) {
4546   default: LLVM_UNREACHABLE("Unknown integer condition code!");
4547   case ICmpInst::ICMP_EQ:
4548     switch (RHSCC) {
4549     default: LLVM_UNREACHABLE("Unknown integer condition code!");
4550     case ICmpInst::ICMP_EQ:
4551       if (LHSCst == SubOne(RHSCst, Context)) {
4552         // (X == 13 | X == 14) -> X-13 <u 2
4553         Constant *AddCST = Context->getConstantExprNeg(LHSCst);
4554         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4555                                                      Val->getName()+".off");
4556         InsertNewInstBefore(Add, I);
4557         AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
4558         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
4559       }
4560       break;                         // (X == 13 | X == 15) -> no change
4561     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4562     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4563       break;
4564     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4565     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4566     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4567       return ReplaceInstUsesWith(I, RHS);
4568     }
4569     break;
4570   case ICmpInst::ICMP_NE:
4571     switch (RHSCC) {
4572     default: LLVM_UNREACHABLE("Unknown integer condition code!");
4573     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4574     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4575     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4576       return ReplaceInstUsesWith(I, LHS);
4577     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4578     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4579     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4580       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4581     }
4582     break;
4583   case ICmpInst::ICMP_ULT:
4584     switch (RHSCC) {
4585     default: LLVM_UNREACHABLE("Unknown integer condition code!");
4586     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4587       break;
4588     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4589       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4590       // this can cause overflow.
4591       if (RHSCst->isMaxValue(false))
4592         return ReplaceInstUsesWith(I, LHS);
4593       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4594                              false, false, I);
4595     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4596       break;
4597     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4598     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4599       return ReplaceInstUsesWith(I, RHS);
4600     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4601       break;
4602     }
4603     break;
4604   case ICmpInst::ICMP_SLT:
4605     switch (RHSCC) {
4606     default: LLVM_UNREACHABLE("Unknown integer condition code!");
4607     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4608       break;
4609     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4610       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4611       // this can cause overflow.
4612       if (RHSCst->isMaxValue(true))
4613         return ReplaceInstUsesWith(I, LHS);
4614       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4615                              true, false, I);
4616     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4617       break;
4618     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4619     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4620       return ReplaceInstUsesWith(I, RHS);
4621     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4622       break;
4623     }
4624     break;
4625   case ICmpInst::ICMP_UGT:
4626     switch (RHSCC) {
4627     default: LLVM_UNREACHABLE("Unknown integer condition code!");
4628     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4629     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4630       return ReplaceInstUsesWith(I, LHS);
4631     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4632       break;
4633     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4634     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4635       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4636     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4637       break;
4638     }
4639     break;
4640   case ICmpInst::ICMP_SGT:
4641     switch (RHSCC) {
4642     default: LLVM_UNREACHABLE("Unknown integer condition code!");
4643     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4644     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4645       return ReplaceInstUsesWith(I, LHS);
4646     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4647       break;
4648     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4649     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4650       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4651     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4652       break;
4653     }
4654     break;
4655   }
4656   return 0;
4657 }
4658
4659 /// FoldOrWithConstants - This helper function folds:
4660 ///
4661 ///     ((A | B) & C1) | (B & C2)
4662 ///
4663 /// into:
4664 /// 
4665 ///     (A & C1) | B
4666 ///
4667 /// when the XOR of the two constants is "all ones" (-1).
4668 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4669                                                Value *A, Value *B, Value *C) {
4670   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4671   if (!CI1) return 0;
4672
4673   Value *V1 = 0;
4674   ConstantInt *CI2 = 0;
4675   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
4676
4677   APInt Xor = CI1->getValue() ^ CI2->getValue();
4678   if (!Xor.isAllOnesValue()) return 0;
4679
4680   if (V1 == A || V1 == B) {
4681     Instruction *NewOp =
4682       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4683     return BinaryOperator::CreateOr(NewOp, V1);
4684   }
4685
4686   return 0;
4687 }
4688
4689 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4690   bool Changed = SimplifyCommutative(I);
4691   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4692
4693   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4694     return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4695
4696   // or X, X = X
4697   if (Op0 == Op1)
4698     return ReplaceInstUsesWith(I, Op0);
4699
4700   // See if we can simplify any instructions used by the instruction whose sole 
4701   // purpose is to compute bits we don't care about.
4702   if (SimplifyDemandedInstructionBits(I))
4703     return &I;
4704   if (isa<VectorType>(I.getType())) {
4705     if (isa<ConstantAggregateZero>(Op1)) {
4706       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4707     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4708       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4709         return ReplaceInstUsesWith(I, I.getOperand(1));
4710     }
4711   }
4712
4713   // or X, -1 == -1
4714   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4715     ConstantInt *C1 = 0; Value *X = 0;
4716     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4717     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) && 
4718         isOnlyUse(Op0)) {
4719       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4720       InsertNewInstBefore(Or, I);
4721       Or->takeName(Op0);
4722       return BinaryOperator::CreateAnd(Or, 
4723                Context->getConstantInt(RHS->getValue() | C1->getValue()));
4724     }
4725
4726     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4727     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) && 
4728         isOnlyUse(Op0)) {
4729       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4730       InsertNewInstBefore(Or, I);
4731       Or->takeName(Op0);
4732       return BinaryOperator::CreateXor(Or,
4733                  Context->getConstantInt(C1->getValue() & ~RHS->getValue()));
4734     }
4735
4736     // Try to fold constant and into select arguments.
4737     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4738       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4739         return R;
4740     if (isa<PHINode>(Op0))
4741       if (Instruction *NV = FoldOpIntoPhi(I))
4742         return NV;
4743   }
4744
4745   Value *A = 0, *B = 0;
4746   ConstantInt *C1 = 0, *C2 = 0;
4747
4748   if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
4749     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4750       return ReplaceInstUsesWith(I, Op1);
4751   if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
4752     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4753       return ReplaceInstUsesWith(I, Op0);
4754
4755   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4756   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4757   if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4758       match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4759       (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4760        match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
4761     if (Instruction *BSwap = MatchBSwap(I))
4762       return BSwap;
4763   }
4764   
4765   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4766   if (Op0->hasOneUse() &&
4767       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4768       MaskedValueIsZero(Op1, C1->getValue())) {
4769     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4770     InsertNewInstBefore(NOr, I);
4771     NOr->takeName(Op0);
4772     return BinaryOperator::CreateXor(NOr, C1);
4773   }
4774
4775   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4776   if (Op1->hasOneUse() &&
4777       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4778       MaskedValueIsZero(Op0, C1->getValue())) {
4779     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4780     InsertNewInstBefore(NOr, I);
4781     NOr->takeName(Op0);
4782     return BinaryOperator::CreateXor(NOr, C1);
4783   }
4784
4785   // (A & C)|(B & D)
4786   Value *C = 0, *D = 0;
4787   if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4788       match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
4789     Value *V1 = 0, *V2 = 0, *V3 = 0;
4790     C1 = dyn_cast<ConstantInt>(C);
4791     C2 = dyn_cast<ConstantInt>(D);
4792     if (C1 && C2) {  // (A & C1)|(B & C2)
4793       // If we have: ((V + N) & C1) | (V & C2)
4794       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4795       // replace with V+N.
4796       if (C1->getValue() == ~C2->getValue()) {
4797         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4798             match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4799           // Add commutes, try both ways.
4800           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4801             return ReplaceInstUsesWith(I, A);
4802           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4803             return ReplaceInstUsesWith(I, A);
4804         }
4805         // Or commutes, try both ways.
4806         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4807             match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4808           // Add commutes, try both ways.
4809           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4810             return ReplaceInstUsesWith(I, B);
4811           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4812             return ReplaceInstUsesWith(I, B);
4813         }
4814       }
4815       V1 = 0; V2 = 0; V3 = 0;
4816     }
4817     
4818     // Check to see if we have any common things being and'ed.  If so, find the
4819     // terms for V1 & (V2|V3).
4820     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4821       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4822         V1 = A, V2 = C, V3 = D;
4823       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4824         V1 = A, V2 = B, V3 = C;
4825       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4826         V1 = C, V2 = A, V3 = D;
4827       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4828         V1 = C, V2 = A, V3 = B;
4829       
4830       if (V1) {
4831         Value *Or =
4832           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4833         return BinaryOperator::CreateAnd(V1, Or);
4834       }
4835     }
4836
4837     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4838     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4839       return Match;
4840     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4841       return Match;
4842     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4843       return Match;
4844     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4845       return Match;
4846
4847     // ((A&~B)|(~A&B)) -> A^B
4848     if ((match(C, m_Not(m_Specific(D)), *Context) &&
4849          match(B, m_Not(m_Specific(A)), *Context)))
4850       return BinaryOperator::CreateXor(A, D);
4851     // ((~B&A)|(~A&B)) -> A^B
4852     if ((match(A, m_Not(m_Specific(D)), *Context) &&
4853          match(B, m_Not(m_Specific(C)), *Context)))
4854       return BinaryOperator::CreateXor(C, D);
4855     // ((A&~B)|(B&~A)) -> A^B
4856     if ((match(C, m_Not(m_Specific(B)), *Context) &&
4857          match(D, m_Not(m_Specific(A)), *Context)))
4858       return BinaryOperator::CreateXor(A, B);
4859     // ((~B&A)|(B&~A)) -> A^B
4860     if ((match(A, m_Not(m_Specific(B)), *Context) &&
4861          match(D, m_Not(m_Specific(C)), *Context)))
4862       return BinaryOperator::CreateXor(C, B);
4863   }
4864   
4865   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4866   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4867     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4868       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4869           SI0->getOperand(1) == SI1->getOperand(1) &&
4870           (SI0->hasOneUse() || SI1->hasOneUse())) {
4871         Instruction *NewOp =
4872         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4873                                                      SI1->getOperand(0),
4874                                                      SI0->getName()), I);
4875         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4876                                       SI1->getOperand(1));
4877       }
4878   }
4879
4880   // ((A|B)&1)|(B&-2) -> (A&1) | B
4881   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4882       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4883     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4884     if (Ret) return Ret;
4885   }
4886   // (B&-2)|((A|B)&1) -> (A&1) | B
4887   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4888       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4889     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4890     if (Ret) return Ret;
4891   }
4892
4893   if (match(Op0, m_Not(m_Value(A)), *Context)) {   // ~A | Op1
4894     if (A == Op1)   // ~A | A == -1
4895       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4896   } else {
4897     A = 0;
4898   }
4899   // Note, A is still live here!
4900   if (match(Op1, m_Not(m_Value(B)), *Context)) {   // Op0 | ~B
4901     if (Op0 == B)
4902       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4903
4904     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4905     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4906       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4907                                               I.getName()+".demorgan"), I);
4908       return BinaryOperator::CreateNot(*Context, And);
4909     }
4910   }
4911
4912   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4913   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4914     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4915       return R;
4916
4917     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4918       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4919         return Res;
4920   }
4921     
4922   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4923   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4924     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4925       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4926         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4927             !isa<ICmpInst>(Op1C->getOperand(0))) {
4928           const Type *SrcTy = Op0C->getOperand(0)->getType();
4929           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4930               // Only do this if the casts both really cause code to be
4931               // generated.
4932               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4933                                 I.getType(), TD) &&
4934               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4935                                 I.getType(), TD)) {
4936             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4937                                                           Op1C->getOperand(0),
4938                                                           I.getName());
4939             InsertNewInstBefore(NewOp, I);
4940             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4941           }
4942         }
4943       }
4944   }
4945   
4946     
4947   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4948   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4949     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4950       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4951           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4952           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4953         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4954           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4955             // If either of the constants are nans, then the whole thing returns
4956             // true.
4957             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4958               return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4959             
4960             // Otherwise, no need to compare the two constants, compare the
4961             // rest.
4962             return new FCmpInst(*Context, FCmpInst::FCMP_UNO, 
4963                                 LHS->getOperand(0), RHS->getOperand(0));
4964           }
4965       } else {
4966         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4967         FCmpInst::Predicate Op0CC, Op1CC;
4968         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4969                   m_Value(Op0RHS)), *Context) &&
4970             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4971                   m_Value(Op1RHS)), *Context)) {
4972           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4973             // Swap RHS operands to match LHS.
4974             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4975             std::swap(Op1LHS, Op1RHS);
4976           }
4977           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4978             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4979             if (Op0CC == Op1CC)
4980               return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4981                                   Op0LHS, Op0RHS);
4982             else if (Op0CC == FCmpInst::FCMP_TRUE ||
4983                      Op1CC == FCmpInst::FCMP_TRUE)
4984               return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4985             else if (Op0CC == FCmpInst::FCMP_FALSE)
4986               return ReplaceInstUsesWith(I, Op1);
4987             else if (Op1CC == FCmpInst::FCMP_FALSE)
4988               return ReplaceInstUsesWith(I, Op0);
4989             bool Op0Ordered;
4990             bool Op1Ordered;
4991             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4992             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4993             if (Op0Ordered == Op1Ordered) {
4994               // If both are ordered or unordered, return a new fcmp with
4995               // or'ed predicates.
4996               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4997                                        Op0LHS, Op0RHS, Context);
4998               if (Instruction *I = dyn_cast<Instruction>(RV))
4999                 return I;
5000               // Otherwise, it's a constant boolean value...
5001               return ReplaceInstUsesWith(I, RV);
5002             }
5003           }
5004         }
5005       }
5006     }
5007   }
5008
5009   return Changed ? &I : 0;
5010 }
5011
5012 namespace {
5013
5014 // XorSelf - Implements: X ^ X --> 0
5015 struct XorSelf {
5016   Value *RHS;
5017   XorSelf(Value *rhs) : RHS(rhs) {}
5018   bool shouldApply(Value *LHS) const { return LHS == RHS; }
5019   Instruction *apply(BinaryOperator &Xor) const {
5020     return &Xor;
5021   }
5022 };
5023
5024 }
5025
5026 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5027   bool Changed = SimplifyCommutative(I);
5028   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5029
5030   if (isa<UndefValue>(Op1)) {
5031     if (isa<UndefValue>(Op0))
5032       // Handle undef ^ undef -> 0 special case. This is a common
5033       // idiom (misuse).
5034       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5035     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5036   }
5037
5038   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5039   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
5040     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5041     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5042   }
5043   
5044   // See if we can simplify any instructions used by the instruction whose sole 
5045   // purpose is to compute bits we don't care about.
5046   if (SimplifyDemandedInstructionBits(I))
5047     return &I;
5048   if (isa<VectorType>(I.getType()))
5049     if (isa<ConstantAggregateZero>(Op1))
5050       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5051
5052   // Is this a ~ operation?
5053   if (Value *NotOp = dyn_castNotVal(&I, Context)) {
5054     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5055     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5056     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5057       if (Op0I->getOpcode() == Instruction::And || 
5058           Op0I->getOpcode() == Instruction::Or) {
5059         if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5060         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
5061           Instruction *NotY =
5062             BinaryOperator::CreateNot(*Context, Op0I->getOperand(1),
5063                                       Op0I->getOperand(1)->getName()+".not");
5064           InsertNewInstBefore(NotY, I);
5065           if (Op0I->getOpcode() == Instruction::And)
5066             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5067           else
5068             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5069         }
5070       }
5071     }
5072   }
5073   
5074   
5075   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5076     if (RHS == Context->getConstantIntTrue() && Op0->hasOneUse()) {
5077       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5078       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5079         return new ICmpInst(*Context, ICI->getInversePredicate(),
5080                             ICI->getOperand(0), ICI->getOperand(1));
5081
5082       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5083         return new FCmpInst(*Context, FCI->getInversePredicate(),
5084                             FCI->getOperand(0), FCI->getOperand(1));
5085     }
5086
5087     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5088     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5089       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5090         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5091           Instruction::CastOps Opcode = Op0C->getOpcode();
5092           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5093             if (RHS == Context->getConstantExprCast(Opcode, 
5094                                              Context->getConstantIntTrue(),
5095                                              Op0C->getDestTy())) {
5096               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5097                                      *Context,
5098                                      CI->getOpcode(), CI->getInversePredicate(),
5099                                      CI->getOperand(0), CI->getOperand(1)), I);
5100               NewCI->takeName(CI);
5101               return CastInst::Create(Opcode, NewCI, Op0C->getType());
5102             }
5103           }
5104         }
5105       }
5106     }
5107
5108     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5109       // ~(c-X) == X-c-1 == X+(-c-1)
5110       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5111         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5112           Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5113           Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
5114                                       Context->getConstantInt(I.getType(), 1));
5115           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5116         }
5117           
5118       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5119         if (Op0I->getOpcode() == Instruction::Add) {
5120           // ~(X-c) --> (-c-1)-X
5121           if (RHS->isAllOnesValue()) {
5122             Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
5123             return BinaryOperator::CreateSub(
5124                            Context->getConstantExprSub(NegOp0CI,
5125                                       Context->getConstantInt(I.getType(), 1)),
5126                                       Op0I->getOperand(0));
5127           } else if (RHS->getValue().isSignBit()) {
5128             // (X + C) ^ signbit -> (X + C + signbit)
5129             Constant *C =
5130                    Context->getConstantInt(RHS->getValue() + Op0CI->getValue());
5131             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5132
5133           }
5134         } else if (Op0I->getOpcode() == Instruction::Or) {
5135           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5136           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5137             Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
5138             // Anything in both C1 and C2 is known to be zero, remove it from
5139             // NewRHS.
5140             Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5141             NewRHS = Context->getConstantExprAnd(NewRHS, 
5142                                        Context->getConstantExprNot(CommonBits));
5143             AddToWorkList(Op0I);
5144             I.setOperand(0, Op0I->getOperand(0));
5145             I.setOperand(1, NewRHS);
5146             return &I;
5147           }
5148         }
5149       }
5150     }
5151
5152     // Try to fold constant and into select arguments.
5153     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5154       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5155         return R;
5156     if (isa<PHINode>(Op0))
5157       if (Instruction *NV = FoldOpIntoPhi(I))
5158         return NV;
5159   }
5160
5161   if (Value *X = dyn_castNotVal(Op0, Context))   // ~A ^ A == -1
5162     if (X == Op1)
5163       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5164
5165   if (Value *X = dyn_castNotVal(Op1, Context))   // A ^ ~A == -1
5166     if (X == Op0)
5167       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5168
5169   
5170   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5171   if (Op1I) {
5172     Value *A, *B;
5173     if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
5174       if (A == Op0) {              // B^(B|A) == (A|B)^B
5175         Op1I->swapOperands();
5176         I.swapOperands();
5177         std::swap(Op0, Op1);
5178       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5179         I.swapOperands();     // Simplified below.
5180         std::swap(Op0, Op1);
5181       }
5182     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
5183       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5184     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
5185       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5186     } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) && 
5187                Op1I->hasOneUse()){
5188       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5189         Op1I->swapOperands();
5190         std::swap(A, B);
5191       }
5192       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5193         I.swapOperands();     // Simplified below.
5194         std::swap(Op0, Op1);
5195       }
5196     }
5197   }
5198   
5199   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5200   if (Op0I) {
5201     Value *A, *B;
5202     if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5203         Op0I->hasOneUse()) {
5204       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5205         std::swap(A, B);
5206       if (B == Op1) {                                // (A|B)^B == A & ~B
5207         Instruction *NotB =
5208           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, 
5209                                                         Op1, "tmp"), I);
5210         return BinaryOperator::CreateAnd(A, NotB);
5211       }
5212     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
5213       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5214     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
5215       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5216     } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) && 
5217                Op0I->hasOneUse()){
5218       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5219         std::swap(A, B);
5220       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5221           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5222         Instruction *N =
5223           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, A, "tmp"), I);
5224         return BinaryOperator::CreateAnd(N, Op1);
5225       }
5226     }
5227   }
5228   
5229   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5230   if (Op0I && Op1I && Op0I->isShift() && 
5231       Op0I->getOpcode() == Op1I->getOpcode() && 
5232       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5233       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5234     Instruction *NewOp =
5235       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5236                                                     Op1I->getOperand(0),
5237                                                     Op0I->getName()), I);
5238     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5239                                   Op1I->getOperand(1));
5240   }
5241     
5242   if (Op0I && Op1I) {
5243     Value *A, *B, *C, *D;
5244     // (A & B)^(A | B) -> A ^ B
5245     if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5246         match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
5247       if ((A == C && B == D) || (A == D && B == C)) 
5248         return BinaryOperator::CreateXor(A, B);
5249     }
5250     // (A | B)^(A & B) -> A ^ B
5251     if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5252         match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5253       if ((A == C && B == D) || (A == D && B == C)) 
5254         return BinaryOperator::CreateXor(A, B);
5255     }
5256     
5257     // (A & B)^(C & D)
5258     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5259         match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5260         match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5261       // (X & Y)^(X & Y) -> (Y^Z) & X
5262       Value *X = 0, *Y = 0, *Z = 0;
5263       if (A == C)
5264         X = A, Y = B, Z = D;
5265       else if (A == D)
5266         X = A, Y = B, Z = C;
5267       else if (B == C)
5268         X = B, Y = A, Z = D;
5269       else if (B == D)
5270         X = B, Y = A, Z = C;
5271       
5272       if (X) {
5273         Instruction *NewOp =
5274         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5275         return BinaryOperator::CreateAnd(NewOp, X);
5276       }
5277     }
5278   }
5279     
5280   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5281   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5282     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
5283       return R;
5284
5285   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5286   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5287     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5288       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5289         const Type *SrcTy = Op0C->getOperand(0)->getType();
5290         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5291             // Only do this if the casts both really cause code to be generated.
5292             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5293                               I.getType(), TD) &&
5294             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5295                               I.getType(), TD)) {
5296           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5297                                                          Op1C->getOperand(0),
5298                                                          I.getName());
5299           InsertNewInstBefore(NewOp, I);
5300           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5301         }
5302       }
5303   }
5304
5305   return Changed ? &I : 0;
5306 }
5307
5308 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5309                                    LLVMContext *Context) {
5310   return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
5311 }
5312
5313 static bool HasAddOverflow(ConstantInt *Result,
5314                            ConstantInt *In1, ConstantInt *In2,
5315                            bool IsSigned) {
5316   if (IsSigned)
5317     if (In2->getValue().isNegative())
5318       return Result->getValue().sgt(In1->getValue());
5319     else
5320       return Result->getValue().slt(In1->getValue());
5321   else
5322     return Result->getValue().ult(In1->getValue());
5323 }
5324
5325 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5326 /// overflowed for this type.
5327 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5328                             Constant *In2, LLVMContext *Context,
5329                             bool IsSigned = false) {
5330   Result = Context->getConstantExprAdd(In1, In2);
5331
5332   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5333     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5334       Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5335       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5336                          ExtractElement(In1, Idx, Context),
5337                          ExtractElement(In2, Idx, Context),
5338                          IsSigned))
5339         return true;
5340     }
5341     return false;
5342   }
5343
5344   return HasAddOverflow(cast<ConstantInt>(Result),
5345                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5346                         IsSigned);
5347 }
5348
5349 static bool HasSubOverflow(ConstantInt *Result,
5350                            ConstantInt *In1, ConstantInt *In2,
5351                            bool IsSigned) {
5352   if (IsSigned)
5353     if (In2->getValue().isNegative())
5354       return Result->getValue().slt(In1->getValue());
5355     else
5356       return Result->getValue().sgt(In1->getValue());
5357   else
5358     return Result->getValue().ugt(In1->getValue());
5359 }
5360
5361 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5362 /// overflowed for this type.
5363 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5364                             Constant *In2, LLVMContext *Context,
5365                             bool IsSigned = false) {
5366   Result = Context->getConstantExprSub(In1, In2);
5367
5368   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5369     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5370       Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5371       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5372                          ExtractElement(In1, Idx, Context),
5373                          ExtractElement(In2, Idx, Context),
5374                          IsSigned))
5375         return true;
5376     }
5377     return false;
5378   }
5379
5380   return HasSubOverflow(cast<ConstantInt>(Result),
5381                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5382                         IsSigned);
5383 }
5384
5385 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5386 /// code necessary to compute the offset from the base pointer (without adding
5387 /// in the base pointer).  Return the result as a signed integer of intptr size.
5388 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5389   TargetData &TD = IC.getTargetData();
5390   gep_type_iterator GTI = gep_type_begin(GEP);
5391   const Type *IntPtrTy = TD.getIntPtrType();
5392   LLVMContext *Context = IC.getContext();
5393   Value *Result = Context->getNullValue(IntPtrTy);
5394
5395   // Build a mask for high order bits.
5396   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5397   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5398
5399   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5400        ++i, ++GTI) {
5401     Value *Op = *i;
5402     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5403     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5404       if (OpC->isZero()) continue;
5405       
5406       // Handle a struct index, which adds its field offset to the pointer.
5407       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5408         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5409         
5410         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5411           Result = 
5412              Context->getConstantInt(RC->getValue() + APInt(IntPtrWidth, Size));
5413         else
5414           Result = IC.InsertNewInstBefore(
5415                    BinaryOperator::CreateAdd(Result,
5416                                         Context->getConstantInt(IntPtrTy, Size),
5417                                              GEP->getName()+".offs"), I);
5418         continue;
5419       }
5420       
5421       Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5422       Constant *OC =
5423               Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5424       Scale = Context->getConstantExprMul(OC, Scale);
5425       if (Constant *RC = dyn_cast<Constant>(Result))
5426         Result = Context->getConstantExprAdd(RC, Scale);
5427       else {
5428         // Emit an add instruction.
5429         Result = IC.InsertNewInstBefore(
5430            BinaryOperator::CreateAdd(Result, Scale,
5431                                      GEP->getName()+".offs"), I);
5432       }
5433       continue;
5434     }
5435     // Convert to correct type.
5436     if (Op->getType() != IntPtrTy) {
5437       if (Constant *OpC = dyn_cast<Constant>(Op))
5438         Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
5439       else
5440         Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5441                                                                 true,
5442                                                       Op->getName()+".c"), I);
5443     }
5444     if (Size != 1) {
5445       Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5446       if (Constant *OpC = dyn_cast<Constant>(Op))
5447         Op = Context->getConstantExprMul(OpC, Scale);
5448       else    // We'll let instcombine(mul) convert this to a shl if possible.
5449         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5450                                                   GEP->getName()+".idx"), I);
5451     }
5452
5453     // Emit an add instruction.
5454     if (isa<Constant>(Op) && isa<Constant>(Result))
5455       Result = Context->getConstantExprAdd(cast<Constant>(Op),
5456                                     cast<Constant>(Result));
5457     else
5458       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5459                                                   GEP->getName()+".offs"), I);
5460   }
5461   return Result;
5462 }
5463
5464
5465 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5466 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
5467 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
5468 /// complex, and scales are involved.  The above expression would also be legal
5469 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
5470 /// later form is less amenable to optimization though, and we are allowed to
5471 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5472 ///
5473 /// If we can't emit an optimized form for this expression, this returns null.
5474 /// 
5475 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5476                                           InstCombiner &IC) {
5477   TargetData &TD = IC.getTargetData();
5478   gep_type_iterator GTI = gep_type_begin(GEP);
5479
5480   // Check to see if this gep only has a single variable index.  If so, and if
5481   // any constant indices are a multiple of its scale, then we can compute this
5482   // in terms of the scale of the variable index.  For example, if the GEP
5483   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5484   // because the expression will cross zero at the same point.
5485   unsigned i, e = GEP->getNumOperands();
5486   int64_t Offset = 0;
5487   for (i = 1; i != e; ++i, ++GTI) {
5488     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5489       // Compute the aggregate offset of constant indices.
5490       if (CI->isZero()) continue;
5491
5492       // Handle a struct index, which adds its field offset to the pointer.
5493       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5494         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5495       } else {
5496         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5497         Offset += Size*CI->getSExtValue();
5498       }
5499     } else {
5500       // Found our variable index.
5501       break;
5502     }
5503   }
5504   
5505   // If there are no variable indices, we must have a constant offset, just
5506   // evaluate it the general way.
5507   if (i == e) return 0;
5508   
5509   Value *VariableIdx = GEP->getOperand(i);
5510   // Determine the scale factor of the variable element.  For example, this is
5511   // 4 if the variable index is into an array of i32.
5512   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5513   
5514   // Verify that there are no other variable indices.  If so, emit the hard way.
5515   for (++i, ++GTI; i != e; ++i, ++GTI) {
5516     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5517     if (!CI) return 0;
5518    
5519     // Compute the aggregate offset of constant indices.
5520     if (CI->isZero()) continue;
5521     
5522     // Handle a struct index, which adds its field offset to the pointer.
5523     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5524       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5525     } else {
5526       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5527       Offset += Size*CI->getSExtValue();
5528     }
5529   }
5530   
5531   // Okay, we know we have a single variable index, which must be a
5532   // pointer/array/vector index.  If there is no offset, life is simple, return
5533   // the index.
5534   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5535   if (Offset == 0) {
5536     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5537     // we don't need to bother extending: the extension won't affect where the
5538     // computation crosses zero.
5539     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5540       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5541                                   VariableIdx->getNameStart(), &I);
5542     return VariableIdx;
5543   }
5544   
5545   // Otherwise, there is an index.  The computation we will do will be modulo
5546   // the pointer size, so get it.
5547   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5548   
5549   Offset &= PtrSizeMask;
5550   VariableScale &= PtrSizeMask;
5551
5552   // To do this transformation, any constant index must be a multiple of the
5553   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5554   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5555   // multiple of the variable scale.
5556   int64_t NewOffs = Offset / (int64_t)VariableScale;
5557   if (Offset != NewOffs*(int64_t)VariableScale)
5558     return 0;
5559
5560   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5561   const Type *IntPtrTy = TD.getIntPtrType();
5562   if (VariableIdx->getType() != IntPtrTy)
5563     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5564                                               true /*SExt*/, 
5565                                               VariableIdx->getNameStart(), &I);
5566   Constant *OffsetVal = IC.getContext()->getConstantInt(IntPtrTy, NewOffs);
5567   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5568 }
5569
5570
5571 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5572 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5573 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5574                                        ICmpInst::Predicate Cond,
5575                                        Instruction &I) {
5576   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5577
5578   // Look through bitcasts.
5579   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5580     RHS = BCI->getOperand(0);
5581
5582   Value *PtrBase = GEPLHS->getOperand(0);
5583   if (PtrBase == RHS) {
5584     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5585     // This transformation (ignoring the base and scales) is valid because we
5586     // know pointers can't overflow.  See if we can output an optimized form.
5587     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5588     
5589     // If not, synthesize the offset the hard way.
5590     if (Offset == 0)
5591       Offset = EmitGEPOffset(GEPLHS, I, *this);
5592     return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
5593                         Context->getNullValue(Offset->getType()));
5594   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5595     // If the base pointers are different, but the indices are the same, just
5596     // compare the base pointer.
5597     if (PtrBase != GEPRHS->getOperand(0)) {
5598       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5599       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5600                         GEPRHS->getOperand(0)->getType();
5601       if (IndicesTheSame)
5602         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5603           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5604             IndicesTheSame = false;
5605             break;
5606           }
5607
5608       // If all indices are the same, just compare the base pointers.
5609       if (IndicesTheSame)
5610         return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), 
5611                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5612
5613       // Otherwise, the base pointers are different and the indices are
5614       // different, bail out.
5615       return 0;
5616     }
5617
5618     // If one of the GEPs has all zero indices, recurse.
5619     bool AllZeros = true;
5620     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5621       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5622           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5623         AllZeros = false;
5624         break;
5625       }
5626     if (AllZeros)
5627       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5628                           ICmpInst::getSwappedPredicate(Cond), I);
5629
5630     // If the other GEP has all zero indices, recurse.
5631     AllZeros = true;
5632     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5633       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5634           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5635         AllZeros = false;
5636         break;
5637       }
5638     if (AllZeros)
5639       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5640
5641     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5642       // If the GEPs only differ by one index, compare it.
5643       unsigned NumDifferences = 0;  // Keep track of # differences.
5644       unsigned DiffOperand = 0;     // The operand that differs.
5645       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5646         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5647           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5648                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5649             // Irreconcilable differences.
5650             NumDifferences = 2;
5651             break;
5652           } else {
5653             if (NumDifferences++) break;
5654             DiffOperand = i;
5655           }
5656         }
5657
5658       if (NumDifferences == 0)   // SAME GEP?
5659         return ReplaceInstUsesWith(I, // No comparison is needed here.
5660                                    Context->getConstantInt(Type::Int1Ty,
5661                                              ICmpInst::isTrueWhenEqual(Cond)));
5662
5663       else if (NumDifferences == 1) {
5664         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5665         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5666         // Make sure we do a signed comparison here.
5667         return new ICmpInst(*Context,
5668                             ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5669       }
5670     }
5671
5672     // Only lower this if the icmp is the only user of the GEP or if we expect
5673     // the result to fold to a constant!
5674     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5675         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5676       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5677       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5678       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5679       return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
5680     }
5681   }
5682   return 0;
5683 }
5684
5685 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5686 ///
5687 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5688                                                 Instruction *LHSI,
5689                                                 Constant *RHSC) {
5690   if (!isa<ConstantFP>(RHSC)) return 0;
5691   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5692   
5693   // Get the width of the mantissa.  We don't want to hack on conversions that
5694   // might lose information from the integer, e.g. "i64 -> float"
5695   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5696   if (MantissaWidth == -1) return 0;  // Unknown.
5697   
5698   // Check to see that the input is converted from an integer type that is small
5699   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5700   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5701   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5702   
5703   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5704   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5705   if (LHSUnsigned)
5706     ++InputSize;
5707   
5708   // If the conversion would lose info, don't hack on this.
5709   if ((int)InputSize > MantissaWidth)
5710     return 0;
5711   
5712   // Otherwise, we can potentially simplify the comparison.  We know that it
5713   // will always come through as an integer value and we know the constant is
5714   // not a NAN (it would have been previously simplified).
5715   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5716   
5717   ICmpInst::Predicate Pred;
5718   switch (I.getPredicate()) {
5719   default: LLVM_UNREACHABLE("Unexpected predicate!");
5720   case FCmpInst::FCMP_UEQ:
5721   case FCmpInst::FCMP_OEQ:
5722     Pred = ICmpInst::ICMP_EQ;
5723     break;
5724   case FCmpInst::FCMP_UGT:
5725   case FCmpInst::FCMP_OGT:
5726     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5727     break;
5728   case FCmpInst::FCMP_UGE:
5729   case FCmpInst::FCMP_OGE:
5730     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5731     break;
5732   case FCmpInst::FCMP_ULT:
5733   case FCmpInst::FCMP_OLT:
5734     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5735     break;
5736   case FCmpInst::FCMP_ULE:
5737   case FCmpInst::FCMP_OLE:
5738     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5739     break;
5740   case FCmpInst::FCMP_UNE:
5741   case FCmpInst::FCMP_ONE:
5742     Pred = ICmpInst::ICMP_NE;
5743     break;
5744   case FCmpInst::FCMP_ORD:
5745     return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5746   case FCmpInst::FCMP_UNO:
5747     return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5748   }
5749   
5750   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5751   
5752   // Now we know that the APFloat is a normal number, zero or inf.
5753   
5754   // See if the FP constant is too large for the integer.  For example,
5755   // comparing an i8 to 300.0.
5756   unsigned IntWidth = IntTy->getScalarSizeInBits();
5757   
5758   if (!LHSUnsigned) {
5759     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5760     // and large values.
5761     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5762     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5763                           APFloat::rmNearestTiesToEven);
5764     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5765       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5766           Pred == ICmpInst::ICMP_SLE)
5767         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5768       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5769     }
5770   } else {
5771     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5772     // +INF and large values.
5773     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5774     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5775                           APFloat::rmNearestTiesToEven);
5776     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5777       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5778           Pred == ICmpInst::ICMP_ULE)
5779         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5780       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5781     }
5782   }
5783   
5784   if (!LHSUnsigned) {
5785     // See if the RHS value is < SignedMin.
5786     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5787     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5788                           APFloat::rmNearestTiesToEven);
5789     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5790       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5791           Pred == ICmpInst::ICMP_SGE)
5792         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5793       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5794     }
5795   }
5796
5797   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5798   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5799   // casting the FP value to the integer value and back, checking for equality.
5800   // Don't do this for zero, because -0.0 is not fractional.
5801   Constant *RHSInt = LHSUnsigned
5802     ? Context->getConstantExprFPToUI(RHSC, IntTy)
5803     : Context->getConstantExprFPToSI(RHSC, IntTy);
5804   if (!RHS.isZero()) {
5805     bool Equal = LHSUnsigned
5806       ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5807       : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
5808     if (!Equal) {
5809       // If we had a comparison against a fractional value, we have to adjust
5810       // the compare predicate and sometimes the value.  RHSC is rounded towards
5811       // zero at this point.
5812       switch (Pred) {
5813       default: LLVM_UNREACHABLE("Unexpected integer comparison!");
5814       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5815         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5816       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5817         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5818       case ICmpInst::ICMP_ULE:
5819         // (float)int <= 4.4   --> int <= 4
5820         // (float)int <= -4.4  --> false
5821         if (RHS.isNegative())
5822           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5823         break;
5824       case ICmpInst::ICMP_SLE:
5825         // (float)int <= 4.4   --> int <= 4
5826         // (float)int <= -4.4  --> int < -4
5827         if (RHS.isNegative())
5828           Pred = ICmpInst::ICMP_SLT;
5829         break;
5830       case ICmpInst::ICMP_ULT:
5831         // (float)int < -4.4   --> false
5832         // (float)int < 4.4    --> int <= 4
5833         if (RHS.isNegative())
5834           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5835         Pred = ICmpInst::ICMP_ULE;
5836         break;
5837       case ICmpInst::ICMP_SLT:
5838         // (float)int < -4.4   --> int < -4
5839         // (float)int < 4.4    --> int <= 4
5840         if (!RHS.isNegative())
5841           Pred = ICmpInst::ICMP_SLE;
5842         break;
5843       case ICmpInst::ICMP_UGT:
5844         // (float)int > 4.4    --> int > 4
5845         // (float)int > -4.4   --> true
5846         if (RHS.isNegative())
5847           return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5848         break;
5849       case ICmpInst::ICMP_SGT:
5850         // (float)int > 4.4    --> int > 4
5851         // (float)int > -4.4   --> int >= -4
5852         if (RHS.isNegative())
5853           Pred = ICmpInst::ICMP_SGE;
5854         break;
5855       case ICmpInst::ICMP_UGE:
5856         // (float)int >= -4.4   --> true
5857         // (float)int >= 4.4    --> int > 4
5858         if (!RHS.isNegative())
5859           return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5860         Pred = ICmpInst::ICMP_UGT;
5861         break;
5862       case ICmpInst::ICMP_SGE:
5863         // (float)int >= -4.4   --> int >= -4
5864         // (float)int >= 4.4    --> int > 4
5865         if (!RHS.isNegative())
5866           Pred = ICmpInst::ICMP_SGT;
5867         break;
5868       }
5869     }
5870   }
5871
5872   // Lower this FP comparison into an appropriate integer version of the
5873   // comparison.
5874   return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
5875 }
5876
5877 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5878   bool Changed = SimplifyCompare(I);
5879   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5880
5881   // Fold trivial predicates.
5882   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5883     return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5884   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5885     return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5886   
5887   // Simplify 'fcmp pred X, X'
5888   if (Op0 == Op1) {
5889     switch (I.getPredicate()) {
5890     default: LLVM_UNREACHABLE("Unknown predicate!");
5891     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5892     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5893     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5894       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5895     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5896     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5897     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5898       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5899       
5900     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5901     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5902     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5903     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5904       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5905       I.setPredicate(FCmpInst::FCMP_UNO);
5906       I.setOperand(1, Context->getNullValue(Op0->getType()));
5907       return &I;
5908       
5909     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5910     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5911     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5912     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5913       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5914       I.setPredicate(FCmpInst::FCMP_ORD);
5915       I.setOperand(1, Context->getNullValue(Op0->getType()));
5916       return &I;
5917     }
5918   }
5919     
5920   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5921     return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5922
5923   // Handle fcmp with constant RHS
5924   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5925     // If the constant is a nan, see if we can fold the comparison based on it.
5926     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5927       if (CFP->getValueAPF().isNaN()) {
5928         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5929           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5930         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5931                "Comparison must be either ordered or unordered!");
5932         // True if unordered.
5933         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5934       }
5935     }
5936     
5937     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5938       switch (LHSI->getOpcode()) {
5939       case Instruction::PHI:
5940         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5941         // block.  If in the same block, we're encouraging jump threading.  If
5942         // not, we are just pessimizing the code by making an i1 phi.
5943         if (LHSI->getParent() == I.getParent())
5944           if (Instruction *NV = FoldOpIntoPhi(I))
5945             return NV;
5946         break;
5947       case Instruction::SIToFP:
5948       case Instruction::UIToFP:
5949         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5950           return NV;
5951         break;
5952       case Instruction::Select:
5953         // If either operand of the select is a constant, we can fold the
5954         // comparison into the select arms, which will cause one to be
5955         // constant folded and the select turned into a bitwise or.
5956         Value *Op1 = 0, *Op2 = 0;
5957         if (LHSI->hasOneUse()) {
5958           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5959             // Fold the known value into the constant operand.
5960             Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5961             // Insert a new FCmp of the other select operand.
5962             Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5963                                                       LHSI->getOperand(2), RHSC,
5964                                                       I.getName()), I);
5965           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5966             // Fold the known value into the constant operand.
5967             Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5968             // Insert a new FCmp of the other select operand.
5969             Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5970                                                       LHSI->getOperand(1), RHSC,
5971                                                       I.getName()), I);
5972           }
5973         }
5974
5975         if (Op1)
5976           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5977         break;
5978       }
5979   }
5980
5981   return Changed ? &I : 0;
5982 }
5983
5984 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5985   bool Changed = SimplifyCompare(I);
5986   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5987   const Type *Ty = Op0->getType();
5988
5989   // icmp X, X
5990   if (Op0 == Op1)
5991     return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty, 
5992                                                    I.isTrueWhenEqual()));
5993
5994   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5995     return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5996   
5997   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5998   // addresses never equal each other!  We already know that Op0 != Op1.
5999   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
6000        isa<ConstantPointerNull>(Op0)) &&
6001       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
6002        isa<ConstantPointerNull>(Op1)))
6003     return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty, 
6004                                                    !I.isTrueWhenEqual()));
6005
6006   // icmp's with boolean values can always be turned into bitwise operations
6007   if (Ty == Type::Int1Ty) {
6008     switch (I.getPredicate()) {
6009     default: LLVM_UNREACHABLE("Invalid icmp instruction!");
6010     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
6011       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
6012       InsertNewInstBefore(Xor, I);
6013       return BinaryOperator::CreateNot(*Context, Xor);
6014     }
6015     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
6016       return BinaryOperator::CreateXor(Op0, Op1);
6017
6018     case ICmpInst::ICMP_UGT:
6019       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
6020       // FALL THROUGH
6021     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
6022       Instruction *Not = BinaryOperator::CreateNot(*Context,
6023                                                    Op0, I.getName()+"tmp");
6024       InsertNewInstBefore(Not, I);
6025       return BinaryOperator::CreateAnd(Not, Op1);
6026     }
6027     case ICmpInst::ICMP_SGT:
6028       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
6029       // FALL THROUGH
6030     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
6031       Instruction *Not = BinaryOperator::CreateNot(*Context, 
6032                                                    Op1, I.getName()+"tmp");
6033       InsertNewInstBefore(Not, I);
6034       return BinaryOperator::CreateAnd(Not, Op0);
6035     }
6036     case ICmpInst::ICMP_UGE:
6037       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6038       // FALL THROUGH
6039     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6040       Instruction *Not = BinaryOperator::CreateNot(*Context,
6041                                                    Op0, I.getName()+"tmp");
6042       InsertNewInstBefore(Not, I);
6043       return BinaryOperator::CreateOr(Not, Op1);
6044     }
6045     case ICmpInst::ICMP_SGE:
6046       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6047       // FALL THROUGH
6048     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6049       Instruction *Not = BinaryOperator::CreateNot(*Context,
6050                                                    Op1, I.getName()+"tmp");
6051       InsertNewInstBefore(Not, I);
6052       return BinaryOperator::CreateOr(Not, Op0);
6053     }
6054     }
6055   }
6056
6057   unsigned BitWidth = 0;
6058   if (TD)
6059     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6060   else if (Ty->isIntOrIntVector())
6061     BitWidth = Ty->getScalarSizeInBits();
6062
6063   bool isSignBit = false;
6064
6065   // See if we are doing a comparison with a constant.
6066   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6067     Value *A = 0, *B = 0;
6068     
6069     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6070     if (I.isEquality() && CI->isNullValue() &&
6071         match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
6072       // (icmp cond A B) if cond is equality
6073       return new ICmpInst(*Context, I.getPredicate(), A, B);
6074     }
6075     
6076     // If we have an icmp le or icmp ge instruction, turn it into the
6077     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6078     // them being folded in the code below.
6079     switch (I.getPredicate()) {
6080     default: break;
6081     case ICmpInst::ICMP_ULE:
6082       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
6083         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6084       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6085                           AddOne(CI, Context));
6086     case ICmpInst::ICMP_SLE:
6087       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
6088         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6089       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6090                           AddOne(CI, Context));
6091     case ICmpInst::ICMP_UGE:
6092       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
6093         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6094       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6095                           SubOne(CI, Context));
6096     case ICmpInst::ICMP_SGE:
6097       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
6098         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6099       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6100                           SubOne(CI, Context));
6101     }
6102     
6103     // If this comparison is a normal comparison, it demands all
6104     // bits, if it is a sign bit comparison, it only demands the sign bit.
6105     bool UnusedBit;
6106     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6107   }
6108
6109   // See if we can fold the comparison based on range information we can get
6110   // by checking whether bits are known to be zero or one in the input.
6111   if (BitWidth != 0) {
6112     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6113     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6114
6115     if (SimplifyDemandedBits(I.getOperandUse(0),
6116                              isSignBit ? APInt::getSignBit(BitWidth)
6117                                        : APInt::getAllOnesValue(BitWidth),
6118                              Op0KnownZero, Op0KnownOne, 0))
6119       return &I;
6120     if (SimplifyDemandedBits(I.getOperandUse(1),
6121                              APInt::getAllOnesValue(BitWidth),
6122                              Op1KnownZero, Op1KnownOne, 0))
6123       return &I;
6124
6125     // Given the known and unknown bits, compute a range that the LHS could be
6126     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6127     // EQ and NE we use unsigned values.
6128     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6129     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6130     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6131       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6132                                              Op0Min, Op0Max);
6133       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6134                                              Op1Min, Op1Max);
6135     } else {
6136       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6137                                                Op0Min, Op0Max);
6138       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6139                                                Op1Min, Op1Max);
6140     }
6141
6142     // If Min and Max are known to be the same, then SimplifyDemandedBits
6143     // figured out that the LHS is a constant.  Just constant fold this now so
6144     // that code below can assume that Min != Max.
6145     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6146       return new ICmpInst(*Context, I.getPredicate(),
6147                           Context->getConstantInt(Op0Min), Op1);
6148     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6149       return new ICmpInst(*Context, I.getPredicate(), Op0, 
6150                           Context->getConstantInt(Op1Min));
6151
6152     // Based on the range information we know about the LHS, see if we can
6153     // simplify this comparison.  For example, (x&4) < 8  is always true.
6154     switch (I.getPredicate()) {
6155     default: LLVM_UNREACHABLE("Unknown icmp opcode!");
6156     case ICmpInst::ICMP_EQ:
6157       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6158         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6159       break;
6160     case ICmpInst::ICMP_NE:
6161       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6162         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6163       break;
6164     case ICmpInst::ICMP_ULT:
6165       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6166         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6167       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6168         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6169       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6170         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6171       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6172         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6173           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6174                               SubOne(CI, Context));
6175
6176         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6177         if (CI->isMinValue(true))
6178           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6179                            Context->getAllOnesValue(Op0->getType()));
6180       }
6181       break;
6182     case ICmpInst::ICMP_UGT:
6183       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6184         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6185       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6186         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6187
6188       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6189         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6190       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6191         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6192           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6193                               AddOne(CI, Context));
6194
6195         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6196         if (CI->isMaxValue(true))
6197           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6198                               Context->getNullValue(Op0->getType()));
6199       }
6200       break;
6201     case ICmpInst::ICMP_SLT:
6202       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6203         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6204       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6205         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6206       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6207         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6208       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6209         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6210           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6211                               SubOne(CI, Context));
6212       }
6213       break;
6214     case ICmpInst::ICMP_SGT:
6215       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6216         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6217       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6218         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6219
6220       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6221         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6222       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6223         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6224           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6225                               AddOne(CI, Context));
6226       }
6227       break;
6228     case ICmpInst::ICMP_SGE:
6229       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6230       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6231         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6232       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6233         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6234       break;
6235     case ICmpInst::ICMP_SLE:
6236       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6237       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6238         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6239       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6240         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6241       break;
6242     case ICmpInst::ICMP_UGE:
6243       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6244       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6245         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6246       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6247         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6248       break;
6249     case ICmpInst::ICMP_ULE:
6250       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6251       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6252         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6253       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6254         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6255       break;
6256     }
6257
6258     // Turn a signed comparison into an unsigned one if both operands
6259     // are known to have the same sign.
6260     if (I.isSignedPredicate() &&
6261         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6262          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6263       return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
6264   }
6265
6266   // Test if the ICmpInst instruction is used exclusively by a select as
6267   // part of a minimum or maximum operation. If so, refrain from doing
6268   // any other folding. This helps out other analyses which understand
6269   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6270   // and CodeGen. And in this case, at least one of the comparison
6271   // operands has at least one user besides the compare (the select),
6272   // which would often largely negate the benefit of folding anyway.
6273   if (I.hasOneUse())
6274     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6275       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6276           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6277         return 0;
6278
6279   // See if we are doing a comparison between a constant and an instruction that
6280   // can be folded into the comparison.
6281   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6282     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6283     // instruction, see if that instruction also has constants so that the 
6284     // instruction can be folded into the icmp 
6285     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6286       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6287         return Res;
6288   }
6289
6290   // Handle icmp with constant (but not simple integer constant) RHS
6291   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6292     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6293       switch (LHSI->getOpcode()) {
6294       case Instruction::GetElementPtr:
6295         if (RHSC->isNullValue()) {
6296           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6297           bool isAllZeros = true;
6298           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6299             if (!isa<Constant>(LHSI->getOperand(i)) ||
6300                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6301               isAllZeros = false;
6302               break;
6303             }
6304           if (isAllZeros)
6305             return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
6306                     Context->getNullValue(LHSI->getOperand(0)->getType()));
6307         }
6308         break;
6309
6310       case Instruction::PHI:
6311         // Only fold icmp into the PHI if the phi and fcmp are in the same
6312         // block.  If in the same block, we're encouraging jump threading.  If
6313         // not, we are just pessimizing the code by making an i1 phi.
6314         if (LHSI->getParent() == I.getParent())
6315           if (Instruction *NV = FoldOpIntoPhi(I))
6316             return NV;
6317         break;
6318       case Instruction::Select: {
6319         // If either operand of the select is a constant, we can fold the
6320         // comparison into the select arms, which will cause one to be
6321         // constant folded and the select turned into a bitwise or.
6322         Value *Op1 = 0, *Op2 = 0;
6323         if (LHSI->hasOneUse()) {
6324           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6325             // Fold the known value into the constant operand.
6326             Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6327             // Insert a new ICmp of the other select operand.
6328             Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6329                                                    LHSI->getOperand(2), RHSC,
6330                                                    I.getName()), I);
6331           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6332             // Fold the known value into the constant operand.
6333             Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6334             // Insert a new ICmp of the other select operand.
6335             Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6336                                                    LHSI->getOperand(1), RHSC,
6337                                                    I.getName()), I);
6338           }
6339         }
6340
6341         if (Op1)
6342           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6343         break;
6344       }
6345       case Instruction::Malloc:
6346         // If we have (malloc != null), and if the malloc has a single use, we
6347         // can assume it is successful and remove the malloc.
6348         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6349           AddToWorkList(LHSI);
6350           return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
6351                                                          !I.isTrueWhenEqual()));
6352         }
6353         break;
6354       }
6355   }
6356
6357   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6358   if (User *GEP = dyn_castGetElementPtr(Op0))
6359     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6360       return NI;
6361   if (User *GEP = dyn_castGetElementPtr(Op1))
6362     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6363                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6364       return NI;
6365
6366   // Test to see if the operands of the icmp are casted versions of other
6367   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6368   // now.
6369   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6370     if (isa<PointerType>(Op0->getType()) && 
6371         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6372       // We keep moving the cast from the left operand over to the right
6373       // operand, where it can often be eliminated completely.
6374       Op0 = CI->getOperand(0);
6375
6376       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6377       // so eliminate it as well.
6378       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6379         Op1 = CI2->getOperand(0);
6380
6381       // If Op1 is a constant, we can fold the cast into the constant.
6382       if (Op0->getType() != Op1->getType()) {
6383         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6384           Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
6385         } else {
6386           // Otherwise, cast the RHS right before the icmp
6387           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6388         }
6389       }
6390       return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
6391     }
6392   }
6393   
6394   if (isa<CastInst>(Op0)) {
6395     // Handle the special case of: icmp (cast bool to X), <cst>
6396     // This comes up when you have code like
6397     //   int X = A < B;
6398     //   if (X) ...
6399     // For generality, we handle any zero-extension of any operand comparison
6400     // with a constant or another cast from the same type.
6401     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6402       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6403         return R;
6404   }
6405   
6406   // See if it's the same type of instruction on the left and right.
6407   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6408     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6409       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6410           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6411         switch (Op0I->getOpcode()) {
6412         default: break;
6413         case Instruction::Add:
6414         case Instruction::Sub:
6415         case Instruction::Xor:
6416           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6417             return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
6418                                 Op1I->getOperand(0));
6419           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6420           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6421             if (CI->getValue().isSignBit()) {
6422               ICmpInst::Predicate Pred = I.isSignedPredicate()
6423                                              ? I.getUnsignedPredicate()
6424                                              : I.getSignedPredicate();
6425               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6426                                   Op1I->getOperand(0));
6427             }
6428             
6429             if (CI->getValue().isMaxSignedValue()) {
6430               ICmpInst::Predicate Pred = I.isSignedPredicate()
6431                                              ? I.getUnsignedPredicate()
6432                                              : I.getSignedPredicate();
6433               Pred = I.getSwappedPredicate(Pred);
6434               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6435                                   Op1I->getOperand(0));
6436             }
6437           }
6438           break;
6439         case Instruction::Mul:
6440           if (!I.isEquality())
6441             break;
6442
6443           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6444             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6445             // Mask = -1 >> count-trailing-zeros(Cst).
6446             if (!CI->isZero() && !CI->isOne()) {
6447               const APInt &AP = CI->getValue();
6448               ConstantInt *Mask = Context->getConstantInt(
6449                                       APInt::getLowBitsSet(AP.getBitWidth(),
6450                                                            AP.getBitWidth() -
6451                                                       AP.countTrailingZeros()));
6452               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6453                                                             Mask);
6454               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6455                                                             Mask);
6456               InsertNewInstBefore(And1, I);
6457               InsertNewInstBefore(And2, I);
6458               return new ICmpInst(*Context, I.getPredicate(), And1, And2);
6459             }
6460           }
6461           break;
6462         }
6463       }
6464     }
6465   }
6466   
6467   // ~x < ~y --> y < x
6468   { Value *A, *B;
6469     if (match(Op0, m_Not(m_Value(A)), *Context) &&
6470         match(Op1, m_Not(m_Value(B)), *Context))
6471       return new ICmpInst(*Context, I.getPredicate(), B, A);
6472   }
6473   
6474   if (I.isEquality()) {
6475     Value *A, *B, *C, *D;
6476     
6477     // -x == -y --> x == y
6478     if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6479         match(Op1, m_Neg(m_Value(B)), *Context))
6480       return new ICmpInst(*Context, I.getPredicate(), A, B);
6481     
6482     if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
6483       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6484         Value *OtherVal = A == Op1 ? B : A;
6485         return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6486                             Context->getNullValue(A->getType()));
6487       }
6488
6489       if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
6490         // A^c1 == C^c2 --> A == C^(c1^c2)
6491         ConstantInt *C1, *C2;
6492         if (match(B, m_ConstantInt(C1), *Context) &&
6493             match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
6494           Constant *NC = 
6495                        Context->getConstantInt(C1->getValue() ^ C2->getValue());
6496           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6497           return new ICmpInst(*Context, I.getPredicate(), A,
6498                               InsertNewInstBefore(Xor, I));
6499         }
6500         
6501         // A^B == A^D -> B == D
6502         if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6503         if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6504         if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6505         if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
6506       }
6507     }
6508     
6509     if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
6510         (A == Op0 || B == Op0)) {
6511       // A == (A^B)  ->  B == 0
6512       Value *OtherVal = A == Op0 ? B : A;
6513       return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6514                           Context->getNullValue(A->getType()));
6515     }
6516
6517     // (A-B) == A  ->  B == 0
6518     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
6519       return new ICmpInst(*Context, I.getPredicate(), B, 
6520                           Context->getNullValue(B->getType()));
6521
6522     // A == (A-B)  ->  B == 0
6523     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
6524       return new ICmpInst(*Context, I.getPredicate(), B,
6525                           Context->getNullValue(B->getType()));
6526     
6527     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6528     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6529         match(Op0, m_And(m_Value(A), m_Value(B)), *Context) && 
6530         match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
6531       Value *X = 0, *Y = 0, *Z = 0;
6532       
6533       if (A == C) {
6534         X = B; Y = D; Z = A;
6535       } else if (A == D) {
6536         X = B; Y = C; Z = A;
6537       } else if (B == C) {
6538         X = A; Y = D; Z = B;
6539       } else if (B == D) {
6540         X = A; Y = C; Z = B;
6541       }
6542       
6543       if (X) {   // Build (X^Y) & Z
6544         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6545         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6546         I.setOperand(0, Op1);
6547         I.setOperand(1, Context->getNullValue(Op1->getType()));
6548         return &I;
6549       }
6550     }
6551   }
6552   return Changed ? &I : 0;
6553 }
6554
6555
6556 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6557 /// and CmpRHS are both known to be integer constants.
6558 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6559                                           ConstantInt *DivRHS) {
6560   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6561   const APInt &CmpRHSV = CmpRHS->getValue();
6562   
6563   // FIXME: If the operand types don't match the type of the divide 
6564   // then don't attempt this transform. The code below doesn't have the
6565   // logic to deal with a signed divide and an unsigned compare (and
6566   // vice versa). This is because (x /s C1) <s C2  produces different 
6567   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6568   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6569   // work. :(  The if statement below tests that condition and bails 
6570   // if it finds it. 
6571   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6572   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6573     return 0;
6574   if (DivRHS->isZero())
6575     return 0; // The ProdOV computation fails on divide by zero.
6576   if (DivIsSigned && DivRHS->isAllOnesValue())
6577     return 0; // The overflow computation also screws up here
6578   if (DivRHS->isOne())
6579     return 0; // Not worth bothering, and eliminates some funny cases
6580               // with INT_MIN.
6581
6582   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6583   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6584   // C2 (CI). By solving for X we can turn this into a range check 
6585   // instead of computing a divide. 
6586   Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
6587
6588   // Determine if the product overflows by seeing if the product is
6589   // not equal to the divide. Make sure we do the same kind of divide
6590   // as in the LHS instruction that we're folding. 
6591   bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6592                  Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
6593
6594   // Get the ICmp opcode
6595   ICmpInst::Predicate Pred = ICI.getPredicate();
6596
6597   // Figure out the interval that is being checked.  For example, a comparison
6598   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6599   // Compute this interval based on the constants involved and the signedness of
6600   // the compare/divide.  This computes a half-open interval, keeping track of
6601   // whether either value in the interval overflows.  After analysis each
6602   // overflow variable is set to 0 if it's corresponding bound variable is valid
6603   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6604   int LoOverflow = 0, HiOverflow = 0;
6605   Constant *LoBound = 0, *HiBound = 0;
6606   
6607   if (!DivIsSigned) {  // udiv
6608     // e.g. X/5 op 3  --> [15, 20)
6609     LoBound = Prod;
6610     HiOverflow = LoOverflow = ProdOV;
6611     if (!HiOverflow)
6612       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6613   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6614     if (CmpRHSV == 0) {       // (X / pos) op 0
6615       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6616       LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS, 
6617                                                                     Context)));
6618       HiBound = DivRHS;
6619     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6620       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6621       HiOverflow = LoOverflow = ProdOV;
6622       if (!HiOverflow)
6623         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6624     } else {                       // (X / pos) op neg
6625       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6626       HiBound = AddOne(Prod, Context);
6627       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6628       if (!LoOverflow) {
6629         ConstantInt* DivNeg =
6630                          cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6631         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6632                                      true) ? -1 : 0;
6633        }
6634     }
6635   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6636     if (CmpRHSV == 0) {       // (X / neg) op 0
6637       // e.g. X/-5 op 0  --> [-4, 5)
6638       LoBound = AddOne(DivRHS, Context);
6639       HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6640       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6641         HiOverflow = 1;            // [INTMIN+1, overflow)
6642         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6643       }
6644     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6645       // e.g. X/-5 op 3  --> [-19, -14)
6646       HiBound = AddOne(Prod, Context);
6647       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6648       if (!LoOverflow)
6649         LoOverflow = AddWithOverflow(LoBound, HiBound,
6650                                      DivRHS, Context, true) ? -1 : 0;
6651     } else {                       // (X / neg) op neg
6652       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6653       LoOverflow = HiOverflow = ProdOV;
6654       if (!HiOverflow)
6655         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6656     }
6657     
6658     // Dividing by a negative swaps the condition.  LT <-> GT
6659     Pred = ICmpInst::getSwappedPredicate(Pred);
6660   }
6661
6662   Value *X = DivI->getOperand(0);
6663   switch (Pred) {
6664   default: LLVM_UNREACHABLE("Unhandled icmp opcode!");
6665   case ICmpInst::ICMP_EQ:
6666     if (LoOverflow && HiOverflow)
6667       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6668     else if (HiOverflow)
6669       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6670                           ICmpInst::ICMP_UGE, X, LoBound);
6671     else if (LoOverflow)
6672       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6673                           ICmpInst::ICMP_ULT, X, HiBound);
6674     else
6675       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6676   case ICmpInst::ICMP_NE:
6677     if (LoOverflow && HiOverflow)
6678       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6679     else if (HiOverflow)
6680       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6681                           ICmpInst::ICMP_ULT, X, LoBound);
6682     else if (LoOverflow)
6683       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6684                           ICmpInst::ICMP_UGE, X, HiBound);
6685     else
6686       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6687   case ICmpInst::ICMP_ULT:
6688   case ICmpInst::ICMP_SLT:
6689     if (LoOverflow == +1)   // Low bound is greater than input range.
6690       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6691     if (LoOverflow == -1)   // Low bound is less than input range.
6692       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6693     return new ICmpInst(*Context, Pred, X, LoBound);
6694   case ICmpInst::ICMP_UGT:
6695   case ICmpInst::ICMP_SGT:
6696     if (HiOverflow == +1)       // High bound greater than input range.
6697       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6698     else if (HiOverflow == -1)  // High bound less than input range.
6699       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6700     if (Pred == ICmpInst::ICMP_UGT)
6701       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
6702     else
6703       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
6704   }
6705 }
6706
6707
6708 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6709 ///
6710 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6711                                                           Instruction *LHSI,
6712                                                           ConstantInt *RHS) {
6713   const APInt &RHSV = RHS->getValue();
6714   
6715   switch (LHSI->getOpcode()) {
6716   case Instruction::Trunc:
6717     if (ICI.isEquality() && LHSI->hasOneUse()) {
6718       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6719       // of the high bits truncated out of x are known.
6720       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6721              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6722       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6723       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6724       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6725       
6726       // If all the high bits are known, we can do this xform.
6727       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6728         // Pull in the high bits from known-ones set.
6729         APInt NewRHS(RHS->getValue());
6730         NewRHS.zext(SrcBits);
6731         NewRHS |= KnownOne;
6732         return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
6733                             Context->getConstantInt(NewRHS));
6734       }
6735     }
6736     break;
6737       
6738   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6739     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6740       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6741       // fold the xor.
6742       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6743           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6744         Value *CompareVal = LHSI->getOperand(0);
6745         
6746         // If the sign bit of the XorCST is not set, there is no change to
6747         // the operation, just stop using the Xor.
6748         if (!XorCST->getValue().isNegative()) {
6749           ICI.setOperand(0, CompareVal);
6750           AddToWorkList(LHSI);
6751           return &ICI;
6752         }
6753         
6754         // Was the old condition true if the operand is positive?
6755         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6756         
6757         // If so, the new one isn't.
6758         isTrueIfPositive ^= true;
6759         
6760         if (isTrueIfPositive)
6761           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
6762                               SubOne(RHS, Context));
6763         else
6764           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
6765                               AddOne(RHS, Context));
6766       }
6767
6768       if (LHSI->hasOneUse()) {
6769         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6770         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6771           const APInt &SignBit = XorCST->getValue();
6772           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6773                                          ? ICI.getUnsignedPredicate()
6774                                          : ICI.getSignedPredicate();
6775           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6776                               Context->getConstantInt(RHSV ^ SignBit));
6777         }
6778
6779         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6780         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6781           const APInt &NotSignBit = XorCST->getValue();
6782           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6783                                          ? ICI.getUnsignedPredicate()
6784                                          : ICI.getSignedPredicate();
6785           Pred = ICI.getSwappedPredicate(Pred);
6786           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6787                               Context->getConstantInt(RHSV ^ NotSignBit));
6788         }
6789       }
6790     }
6791     break;
6792   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6793     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6794         LHSI->getOperand(0)->hasOneUse()) {
6795       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6796       
6797       // If the LHS is an AND of a truncating cast, we can widen the
6798       // and/compare to be the input width without changing the value
6799       // produced, eliminating a cast.
6800       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6801         // We can do this transformation if either the AND constant does not
6802         // have its sign bit set or if it is an equality comparison. 
6803         // Extending a relational comparison when we're checking the sign
6804         // bit would not work.
6805         if (Cast->hasOneUse() &&
6806             (ICI.isEquality() ||
6807              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6808           uint32_t BitWidth = 
6809             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6810           APInt NewCST = AndCST->getValue();
6811           NewCST.zext(BitWidth);
6812           APInt NewCI = RHSV;
6813           NewCI.zext(BitWidth);
6814           Instruction *NewAnd = 
6815             BinaryOperator::CreateAnd(Cast->getOperand(0),
6816                                Context->getConstantInt(NewCST),LHSI->getName());
6817           InsertNewInstBefore(NewAnd, ICI);
6818           return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
6819                               Context->getConstantInt(NewCI));
6820         }
6821       }
6822       
6823       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6824       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6825       // happens a LOT in code produced by the C front-end, for bitfield
6826       // access.
6827       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6828       if (Shift && !Shift->isShift())
6829         Shift = 0;
6830       
6831       ConstantInt *ShAmt;
6832       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6833       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6834       const Type *AndTy = AndCST->getType();          // Type of the and.
6835       
6836       // We can fold this as long as we can't shift unknown bits
6837       // into the mask.  This can only happen with signed shift
6838       // rights, as they sign-extend.
6839       if (ShAmt) {
6840         bool CanFold = Shift->isLogicalShift();
6841         if (!CanFold) {
6842           // To test for the bad case of the signed shr, see if any
6843           // of the bits shifted in could be tested after the mask.
6844           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6845           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6846           
6847           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6848           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6849                AndCST->getValue()) == 0)
6850             CanFold = true;
6851         }
6852         
6853         if (CanFold) {
6854           Constant *NewCst;
6855           if (Shift->getOpcode() == Instruction::Shl)
6856             NewCst = Context->getConstantExprLShr(RHS, ShAmt);
6857           else
6858             NewCst = Context->getConstantExprShl(RHS, ShAmt);
6859           
6860           // Check to see if we are shifting out any of the bits being
6861           // compared.
6862           if (Context->getConstantExpr(Shift->getOpcode(),
6863                                        NewCst, ShAmt) != RHS) {
6864             // If we shifted bits out, the fold is not going to work out.
6865             // As a special case, check to see if this means that the
6866             // result is always true or false now.
6867             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6868               return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6869             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6870               return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6871           } else {
6872             ICI.setOperand(1, NewCst);
6873             Constant *NewAndCST;
6874             if (Shift->getOpcode() == Instruction::Shl)
6875               NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
6876             else
6877               NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
6878             LHSI->setOperand(1, NewAndCST);
6879             LHSI->setOperand(0, Shift->getOperand(0));
6880             AddToWorkList(Shift); // Shift is dead.
6881             AddUsesToWorkList(ICI);
6882             return &ICI;
6883           }
6884         }
6885       }
6886       
6887       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6888       // preferable because it allows the C<<Y expression to be hoisted out
6889       // of a loop if Y is invariant and X is not.
6890       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6891           ICI.isEquality() && !Shift->isArithmeticShift() &&
6892           !isa<Constant>(Shift->getOperand(0))) {
6893         // Compute C << Y.
6894         Value *NS;
6895         if (Shift->getOpcode() == Instruction::LShr) {
6896           NS = BinaryOperator::CreateShl(AndCST, 
6897                                          Shift->getOperand(1), "tmp");
6898         } else {
6899           // Insert a logical shift.
6900           NS = BinaryOperator::CreateLShr(AndCST,
6901                                           Shift->getOperand(1), "tmp");
6902         }
6903         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6904         
6905         // Compute X & (C << Y).
6906         Instruction *NewAnd = 
6907           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6908         InsertNewInstBefore(NewAnd, ICI);
6909         
6910         ICI.setOperand(0, NewAnd);
6911         return &ICI;
6912       }
6913     }
6914     break;
6915     
6916   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6917     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6918     if (!ShAmt) break;
6919     
6920     uint32_t TypeBits = RHSV.getBitWidth();
6921     
6922     // Check that the shift amount is in range.  If not, don't perform
6923     // undefined shifts.  When the shift is visited it will be
6924     // simplified.
6925     if (ShAmt->uge(TypeBits))
6926       break;
6927     
6928     if (ICI.isEquality()) {
6929       // If we are comparing against bits always shifted out, the
6930       // comparison cannot succeed.
6931       Constant *Comp =
6932         Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6933                                                                  ShAmt);
6934       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6935         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6936         Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
6937         return ReplaceInstUsesWith(ICI, Cst);
6938       }
6939       
6940       if (LHSI->hasOneUse()) {
6941         // Otherwise strength reduce the shift into an and.
6942         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6943         Constant *Mask =
6944           Context->getConstantInt(APInt::getLowBitsSet(TypeBits, 
6945                                                        TypeBits-ShAmtVal));
6946         
6947         Instruction *AndI =
6948           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6949                                     Mask, LHSI->getName()+".mask");
6950         Value *And = InsertNewInstBefore(AndI, ICI);
6951         return new ICmpInst(*Context, ICI.getPredicate(), And,
6952                             Context->getConstantInt(RHSV.lshr(ShAmtVal)));
6953       }
6954     }
6955     
6956     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6957     bool TrueIfSigned = false;
6958     if (LHSI->hasOneUse() &&
6959         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6960       // (X << 31) <s 0  --> (X&1) != 0
6961       Constant *Mask = Context->getConstantInt(APInt(TypeBits, 1) <<
6962                                            (TypeBits-ShAmt->getZExtValue()-1));
6963       Instruction *AndI =
6964         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6965                                   Mask, LHSI->getName()+".mask");
6966       Value *And = InsertNewInstBefore(AndI, ICI);
6967       
6968       return new ICmpInst(*Context,
6969                           TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6970                           And, Context->getNullValue(And->getType()));
6971     }
6972     break;
6973   }
6974     
6975   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6976   case Instruction::AShr: {
6977     // Only handle equality comparisons of shift-by-constant.
6978     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6979     if (!ShAmt || !ICI.isEquality()) break;
6980
6981     // Check that the shift amount is in range.  If not, don't perform
6982     // undefined shifts.  When the shift is visited it will be
6983     // simplified.
6984     uint32_t TypeBits = RHSV.getBitWidth();
6985     if (ShAmt->uge(TypeBits))
6986       break;
6987     
6988     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6989       
6990     // If we are comparing against bits always shifted out, the
6991     // comparison cannot succeed.
6992     APInt Comp = RHSV << ShAmtVal;
6993     if (LHSI->getOpcode() == Instruction::LShr)
6994       Comp = Comp.lshr(ShAmtVal);
6995     else
6996       Comp = Comp.ashr(ShAmtVal);
6997     
6998     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6999       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7000       Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
7001       return ReplaceInstUsesWith(ICI, Cst);
7002     }
7003     
7004     // Otherwise, check to see if the bits shifted out are known to be zero.
7005     // If so, we can compare against the unshifted value:
7006     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
7007     if (LHSI->hasOneUse() &&
7008         MaskedValueIsZero(LHSI->getOperand(0), 
7009                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
7010       return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
7011                           Context->getConstantExprShl(RHS, ShAmt));
7012     }
7013       
7014     if (LHSI->hasOneUse()) {
7015       // Otherwise strength reduce the shift into an and.
7016       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
7017       Constant *Mask = Context->getConstantInt(Val);
7018       
7019       Instruction *AndI =
7020         BinaryOperator::CreateAnd(LHSI->getOperand(0),
7021                                   Mask, LHSI->getName()+".mask");
7022       Value *And = InsertNewInstBefore(AndI, ICI);
7023       return new ICmpInst(*Context, ICI.getPredicate(), And,
7024                           Context->getConstantExprShl(RHS, ShAmt));
7025     }
7026     break;
7027   }
7028     
7029   case Instruction::SDiv:
7030   case Instruction::UDiv:
7031     // Fold: icmp pred ([us]div X, C1), C2 -> range test
7032     // Fold this div into the comparison, producing a range check. 
7033     // Determine, based on the divide type, what the range is being 
7034     // checked.  If there is an overflow on the low or high side, remember 
7035     // it, otherwise compute the range [low, hi) bounding the new value.
7036     // See: InsertRangeTest above for the kinds of replacements possible.
7037     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7038       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7039                                           DivRHS))
7040         return R;
7041     break;
7042
7043   case Instruction::Add:
7044     // Fold: icmp pred (add, X, C1), C2
7045
7046     if (!ICI.isEquality()) {
7047       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7048       if (!LHSC) break;
7049       const APInt &LHSV = LHSC->getValue();
7050
7051       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7052                             .subtract(LHSV);
7053
7054       if (ICI.isSignedPredicate()) {
7055         if (CR.getLower().isSignBit()) {
7056           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7057                               Context->getConstantInt(CR.getUpper()));
7058         } else if (CR.getUpper().isSignBit()) {
7059           return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7060                               Context->getConstantInt(CR.getLower()));
7061         }
7062       } else {
7063         if (CR.getLower().isMinValue()) {
7064           return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7065                               Context->getConstantInt(CR.getUpper()));
7066         } else if (CR.getUpper().isMinValue()) {
7067           return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7068                               Context->getConstantInt(CR.getLower()));
7069         }
7070       }
7071     }
7072     break;
7073   }
7074   
7075   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7076   if (ICI.isEquality()) {
7077     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7078     
7079     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7080     // the second operand is a constant, simplify a bit.
7081     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7082       switch (BO->getOpcode()) {
7083       case Instruction::SRem:
7084         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7085         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7086           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7087           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7088             Instruction *NewRem =
7089               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
7090                                          BO->getName());
7091             InsertNewInstBefore(NewRem, ICI);
7092             return new ICmpInst(*Context, ICI.getPredicate(), NewRem, 
7093                                 Context->getNullValue(BO->getType()));
7094           }
7095         }
7096         break;
7097       case Instruction::Add:
7098         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7099         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7100           if (BO->hasOneUse())
7101             return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7102                                 Context->getConstantExprSub(RHS, BOp1C));
7103         } else if (RHSV == 0) {
7104           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7105           // efficiently invertible, or if the add has just this one use.
7106           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7107           
7108           if (Value *NegVal = dyn_castNegVal(BOp1, Context))
7109             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
7110           else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
7111             return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
7112           else if (BO->hasOneUse()) {
7113             Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
7114             InsertNewInstBefore(Neg, ICI);
7115             Neg->takeName(BO);
7116             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
7117           }
7118         }
7119         break;
7120       case Instruction::Xor:
7121         // For the xor case, we can xor two constants together, eliminating
7122         // the explicit xor.
7123         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7124           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0), 
7125                               Context->getConstantExprXor(RHS, BOC));
7126         
7127         // FALLTHROUGH
7128       case Instruction::Sub:
7129         // Replace (([sub|xor] A, B) != 0) with (A != B)
7130         if (RHSV == 0)
7131           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7132                               BO->getOperand(1));
7133         break;
7134         
7135       case Instruction::Or:
7136         // If bits are being or'd in that are not present in the constant we
7137         // are comparing against, then the comparison could never succeed!
7138         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7139           Constant *NotCI = Context->getConstantExprNot(RHS);
7140           if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7141             return ReplaceInstUsesWith(ICI,
7142                                        Context->getConstantInt(Type::Int1Ty, 
7143                                        isICMP_NE));
7144         }
7145         break;
7146         
7147       case Instruction::And:
7148         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7149           // If bits are being compared against that are and'd out, then the
7150           // comparison can never succeed!
7151           if ((RHSV & ~BOC->getValue()) != 0)
7152             return ReplaceInstUsesWith(ICI,
7153                                        Context->getConstantInt(Type::Int1Ty,
7154                                        isICMP_NE));
7155           
7156           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7157           if (RHS == BOC && RHSV.isPowerOf2())
7158             return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
7159                                 ICmpInst::ICMP_NE, LHSI,
7160                                 Context->getNullValue(RHS->getType()));
7161           
7162           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7163           if (BOC->getValue().isSignBit()) {
7164             Value *X = BO->getOperand(0);
7165             Constant *Zero = Context->getNullValue(X->getType());
7166             ICmpInst::Predicate pred = isICMP_NE ? 
7167               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7168             return new ICmpInst(*Context, pred, X, Zero);
7169           }
7170           
7171           // ((X & ~7) == 0) --> X < 8
7172           if (RHSV == 0 && isHighOnes(BOC)) {
7173             Value *X = BO->getOperand(0);
7174             Constant *NegX = Context->getConstantExprNeg(BOC);
7175             ICmpInst::Predicate pred = isICMP_NE ? 
7176               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7177             return new ICmpInst(*Context, pred, X, NegX);
7178           }
7179         }
7180       default: break;
7181       }
7182     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7183       // Handle icmp {eq|ne} <intrinsic>, intcst.
7184       if (II->getIntrinsicID() == Intrinsic::bswap) {
7185         AddToWorkList(II);
7186         ICI.setOperand(0, II->getOperand(1));
7187         ICI.setOperand(1, Context->getConstantInt(RHSV.byteSwap()));
7188         return &ICI;
7189       }
7190     }
7191   }
7192   return 0;
7193 }
7194
7195 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7196 /// We only handle extending casts so far.
7197 ///
7198 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7199   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7200   Value *LHSCIOp        = LHSCI->getOperand(0);
7201   const Type *SrcTy     = LHSCIOp->getType();
7202   const Type *DestTy    = LHSCI->getType();
7203   Value *RHSCIOp;
7204
7205   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7206   // integer type is the same size as the pointer type.
7207   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7208       getTargetData().getPointerSizeInBits() == 
7209          cast<IntegerType>(DestTy)->getBitWidth()) {
7210     Value *RHSOp = 0;
7211     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7212       RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
7213     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7214       RHSOp = RHSC->getOperand(0);
7215       // If the pointer types don't match, insert a bitcast.
7216       if (LHSCIOp->getType() != RHSOp->getType())
7217         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
7218     }
7219
7220     if (RHSOp)
7221       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
7222   }
7223   
7224   // The code below only handles extension cast instructions, so far.
7225   // Enforce this.
7226   if (LHSCI->getOpcode() != Instruction::ZExt &&
7227       LHSCI->getOpcode() != Instruction::SExt)
7228     return 0;
7229
7230   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7231   bool isSignedCmp = ICI.isSignedPredicate();
7232
7233   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7234     // Not an extension from the same type?
7235     RHSCIOp = CI->getOperand(0);
7236     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7237       return 0;
7238     
7239     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7240     // and the other is a zext), then we can't handle this.
7241     if (CI->getOpcode() != LHSCI->getOpcode())
7242       return 0;
7243
7244     // Deal with equality cases early.
7245     if (ICI.isEquality())
7246       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7247
7248     // A signed comparison of sign extended values simplifies into a
7249     // signed comparison.
7250     if (isSignedCmp && isSignedExt)
7251       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7252
7253     // The other three cases all fold into an unsigned comparison.
7254     return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7255   }
7256
7257   // If we aren't dealing with a constant on the RHS, exit early
7258   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7259   if (!CI)
7260     return 0;
7261
7262   // Compute the constant that would happen if we truncated to SrcTy then
7263   // reextended to DestTy.
7264   Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7265   Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7266                                                 Res1, DestTy);
7267
7268   // If the re-extended constant didn't change...
7269   if (Res2 == CI) {
7270     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7271     // For example, we might have:
7272     //    %A = sext i16 %X to i32
7273     //    %B = icmp ugt i32 %A, 1330
7274     // It is incorrect to transform this into 
7275     //    %B = icmp ugt i16 %X, 1330
7276     // because %A may have negative value. 
7277     //
7278     // However, we allow this when the compare is EQ/NE, because they are
7279     // signless.
7280     if (isSignedExt == isSignedCmp || ICI.isEquality())
7281       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
7282     return 0;
7283   }
7284
7285   // The re-extended constant changed so the constant cannot be represented 
7286   // in the shorter type. Consequently, we cannot emit a simple comparison.
7287
7288   // First, handle some easy cases. We know the result cannot be equal at this
7289   // point so handle the ICI.isEquality() cases
7290   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7291     return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
7292   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7293     return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
7294
7295   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7296   // should have been folded away previously and not enter in here.
7297   Value *Result;
7298   if (isSignedCmp) {
7299     // We're performing a signed comparison.
7300     if (cast<ConstantInt>(CI)->getValue().isNegative())
7301       Result = Context->getConstantIntFalse();          // X < (small) --> false
7302     else
7303       Result = Context->getConstantIntTrue();           // X < (large) --> true
7304   } else {
7305     // We're performing an unsigned comparison.
7306     if (isSignedExt) {
7307       // We're performing an unsigned comp with a sign extended value.
7308       // This is true if the input is >= 0. [aka >s -1]
7309       Constant *NegOne = Context->getAllOnesValue(SrcTy);
7310       Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT, 
7311                                    LHSCIOp, NegOne, ICI.getName()), ICI);
7312     } else {
7313       // Unsigned extend & unsigned compare -> always true.
7314       Result = Context->getConstantIntTrue();
7315     }
7316   }
7317
7318   // Finally, return the value computed.
7319   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7320       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7321     return ReplaceInstUsesWith(ICI, Result);
7322
7323   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7324           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7325          "ICmp should be folded!");
7326   if (Constant *CI = dyn_cast<Constant>(Result))
7327     return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
7328   return BinaryOperator::CreateNot(*Context, Result);
7329 }
7330
7331 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7332   return commonShiftTransforms(I);
7333 }
7334
7335 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7336   return commonShiftTransforms(I);
7337 }
7338
7339 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7340   if (Instruction *R = commonShiftTransforms(I))
7341     return R;
7342   
7343   Value *Op0 = I.getOperand(0);
7344   
7345   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7346   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7347     if (CSI->isAllOnesValue())
7348       return ReplaceInstUsesWith(I, CSI);
7349
7350   // See if we can turn a signed shr into an unsigned shr.
7351   if (MaskedValueIsZero(Op0,
7352                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7353     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7354
7355   // Arithmetic shifting an all-sign-bit value is a no-op.
7356   unsigned NumSignBits = ComputeNumSignBits(Op0);
7357   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7358     return ReplaceInstUsesWith(I, Op0);
7359
7360   return 0;
7361 }
7362
7363 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7364   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7365   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7366
7367   // shl X, 0 == X and shr X, 0 == X
7368   // shl 0, X == 0 and shr 0, X == 0
7369   if (Op1 == Context->getNullValue(Op1->getType()) ||
7370       Op0 == Context->getNullValue(Op0->getType()))
7371     return ReplaceInstUsesWith(I, Op0);
7372   
7373   if (isa<UndefValue>(Op0)) {            
7374     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7375       return ReplaceInstUsesWith(I, Op0);
7376     else                                    // undef << X -> 0, undef >>u X -> 0
7377       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7378   }
7379   if (isa<UndefValue>(Op1)) {
7380     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7381       return ReplaceInstUsesWith(I, Op0);          
7382     else                                     // X << undef, X >>u undef -> 0
7383       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7384   }
7385
7386   // See if we can fold away this shift.
7387   if (SimplifyDemandedInstructionBits(I))
7388     return &I;
7389
7390   // Try to fold constant and into select arguments.
7391   if (isa<Constant>(Op0))
7392     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7393       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7394         return R;
7395
7396   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7397     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7398       return Res;
7399   return 0;
7400 }
7401
7402 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7403                                                BinaryOperator &I) {
7404   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7405
7406   // See if we can simplify any instructions used by the instruction whose sole 
7407   // purpose is to compute bits we don't care about.
7408   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7409   
7410   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7411   // a signed shift.
7412   //
7413   if (Op1->uge(TypeBits)) {
7414     if (I.getOpcode() != Instruction::AShr)
7415       return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
7416     else {
7417       I.setOperand(1, Context->getConstantInt(I.getType(), TypeBits-1));
7418       return &I;
7419     }
7420   }
7421   
7422   // ((X*C1) << C2) == (X * (C1 << C2))
7423   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7424     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7425       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7426         return BinaryOperator::CreateMul(BO->getOperand(0),
7427                                         Context->getConstantExprShl(BOOp, Op1));
7428   
7429   // Try to fold constant and into select arguments.
7430   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7431     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7432       return R;
7433   if (isa<PHINode>(Op0))
7434     if (Instruction *NV = FoldOpIntoPhi(I))
7435       return NV;
7436   
7437   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7438   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7439     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7440     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7441     // place.  Don't try to do this transformation in this case.  Also, we
7442     // require that the input operand is a shift-by-constant so that we have
7443     // confidence that the shifts will get folded together.  We could do this
7444     // xform in more cases, but it is unlikely to be profitable.
7445     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7446         isa<ConstantInt>(TrOp->getOperand(1))) {
7447       // Okay, we'll do this xform.  Make the shift of shift.
7448       Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
7449       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7450                                                 I.getName());
7451       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7452
7453       // For logical shifts, the truncation has the effect of making the high
7454       // part of the register be zeros.  Emulate this by inserting an AND to
7455       // clear the top bits as needed.  This 'and' will usually be zapped by
7456       // other xforms later if dead.
7457       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7458       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7459       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7460       
7461       // The mask we constructed says what the trunc would do if occurring
7462       // between the shifts.  We want to know the effect *after* the second
7463       // shift.  We know that it is a logical shift by a constant, so adjust the
7464       // mask as appropriate.
7465       if (I.getOpcode() == Instruction::Shl)
7466         MaskV <<= Op1->getZExtValue();
7467       else {
7468         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7469         MaskV = MaskV.lshr(Op1->getZExtValue());
7470       }
7471
7472       Instruction *And =
7473         BinaryOperator::CreateAnd(NSh, Context->getConstantInt(MaskV), 
7474                                   TI->getName());
7475       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7476
7477       // Return the value truncated to the interesting size.
7478       return new TruncInst(And, I.getType());
7479     }
7480   }
7481   
7482   if (Op0->hasOneUse()) {
7483     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7484       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7485       Value *V1, *V2;
7486       ConstantInt *CC;
7487       switch (Op0BO->getOpcode()) {
7488         default: break;
7489         case Instruction::Add:
7490         case Instruction::And:
7491         case Instruction::Or:
7492         case Instruction::Xor: {
7493           // These operators commute.
7494           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7495           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7496               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7497                     m_Specific(Op1)), *Context)){
7498             Instruction *YS = BinaryOperator::CreateShl(
7499                                             Op0BO->getOperand(0), Op1,
7500                                             Op0BO->getName());
7501             InsertNewInstBefore(YS, I); // (Y << C)
7502             Instruction *X = 
7503               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7504                                      Op0BO->getOperand(1)->getName());
7505             InsertNewInstBefore(X, I);  // (X + (Y << C))
7506             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7507             return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7508                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7509           }
7510           
7511           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7512           Value *Op0BOOp1 = Op0BO->getOperand(1);
7513           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7514               match(Op0BOOp1, 
7515                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7516                           m_ConstantInt(CC)), *Context) &&
7517               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7518             Instruction *YS = BinaryOperator::CreateShl(
7519                                                      Op0BO->getOperand(0), Op1,
7520                                                      Op0BO->getName());
7521             InsertNewInstBefore(YS, I); // (Y << C)
7522             Instruction *XM =
7523               BinaryOperator::CreateAnd(V1,
7524                                         Context->getConstantExprShl(CC, Op1),
7525                                         V1->getName()+".mask");
7526             InsertNewInstBefore(XM, I); // X & (CC << C)
7527             
7528             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7529           }
7530         }
7531           
7532         // FALL THROUGH.
7533         case Instruction::Sub: {
7534           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7535           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7536               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7537                     m_Specific(Op1)), *Context)){
7538             Instruction *YS = BinaryOperator::CreateShl(
7539                                                      Op0BO->getOperand(1), Op1,
7540                                                      Op0BO->getName());
7541             InsertNewInstBefore(YS, I); // (Y << C)
7542             Instruction *X =
7543               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7544                                      Op0BO->getOperand(0)->getName());
7545             InsertNewInstBefore(X, I);  // (X + (Y << C))
7546             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7547             return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7548                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7549           }
7550           
7551           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7552           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7553               match(Op0BO->getOperand(0),
7554                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7555                           m_ConstantInt(CC)), *Context) && V2 == Op1 &&
7556               cast<BinaryOperator>(Op0BO->getOperand(0))
7557                   ->getOperand(0)->hasOneUse()) {
7558             Instruction *YS = BinaryOperator::CreateShl(
7559                                                      Op0BO->getOperand(1), Op1,
7560                                                      Op0BO->getName());
7561             InsertNewInstBefore(YS, I); // (Y << C)
7562             Instruction *XM =
7563               BinaryOperator::CreateAnd(V1, 
7564                                         Context->getConstantExprShl(CC, Op1),
7565                                         V1->getName()+".mask");
7566             InsertNewInstBefore(XM, I); // X & (CC << C)
7567             
7568             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7569           }
7570           
7571           break;
7572         }
7573       }
7574       
7575       
7576       // If the operand is an bitwise operator with a constant RHS, and the
7577       // shift is the only use, we can pull it out of the shift.
7578       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7579         bool isValid = true;     // Valid only for And, Or, Xor
7580         bool highBitSet = false; // Transform if high bit of constant set?
7581         
7582         switch (Op0BO->getOpcode()) {
7583           default: isValid = false; break;   // Do not perform transform!
7584           case Instruction::Add:
7585             isValid = isLeftShift;
7586             break;
7587           case Instruction::Or:
7588           case Instruction::Xor:
7589             highBitSet = false;
7590             break;
7591           case Instruction::And:
7592             highBitSet = true;
7593             break;
7594         }
7595         
7596         // If this is a signed shift right, and the high bit is modified
7597         // by the logical operation, do not perform the transformation.
7598         // The highBitSet boolean indicates the value of the high bit of
7599         // the constant which would cause it to be modified for this
7600         // operation.
7601         //
7602         if (isValid && I.getOpcode() == Instruction::AShr)
7603           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7604         
7605         if (isValid) {
7606           Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
7607           
7608           Instruction *NewShift =
7609             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7610           InsertNewInstBefore(NewShift, I);
7611           NewShift->takeName(Op0BO);
7612           
7613           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7614                                         NewRHS);
7615         }
7616       }
7617     }
7618   }
7619   
7620   // Find out if this is a shift of a shift by a constant.
7621   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7622   if (ShiftOp && !ShiftOp->isShift())
7623     ShiftOp = 0;
7624   
7625   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7626     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7627     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7628     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7629     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7630     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7631     Value *X = ShiftOp->getOperand(0);
7632     
7633     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7634     
7635     const IntegerType *Ty = cast<IntegerType>(I.getType());
7636     
7637     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7638     if (I.getOpcode() == ShiftOp->getOpcode()) {
7639       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7640       // saturates.
7641       if (AmtSum >= TypeBits) {
7642         if (I.getOpcode() != Instruction::AShr)
7643           return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7644         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7645       }
7646       
7647       return BinaryOperator::Create(I.getOpcode(), X,
7648                                     Context->getConstantInt(Ty, AmtSum));
7649     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7650                I.getOpcode() == Instruction::AShr) {
7651       if (AmtSum >= TypeBits)
7652         return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7653       
7654       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7655       return BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, AmtSum));
7656     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7657                I.getOpcode() == Instruction::LShr) {
7658       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7659       if (AmtSum >= TypeBits)
7660         AmtSum = TypeBits-1;
7661       
7662       Instruction *Shift =
7663         BinaryOperator::CreateAShr(X, Context->getConstantInt(Ty, AmtSum));
7664       InsertNewInstBefore(Shift, I);
7665
7666       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7667       return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7668     }
7669     
7670     // Okay, if we get here, one shift must be left, and the other shift must be
7671     // right.  See if the amounts are equal.
7672     if (ShiftAmt1 == ShiftAmt2) {
7673       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7674       if (I.getOpcode() == Instruction::Shl) {
7675         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7676         return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7677       }
7678       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7679       if (I.getOpcode() == Instruction::LShr) {
7680         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7681         return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7682       }
7683       // We can simplify ((X << C) >>s C) into a trunc + sext.
7684       // NOTE: we could do this for any C, but that would make 'unusual' integer
7685       // types.  For now, just stick to ones well-supported by the code
7686       // generators.
7687       const Type *SExtType = 0;
7688       switch (Ty->getBitWidth() - ShiftAmt1) {
7689       case 1  :
7690       case 8  :
7691       case 16 :
7692       case 32 :
7693       case 64 :
7694       case 128:
7695         SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
7696         break;
7697       default: break;
7698       }
7699       if (SExtType) {
7700         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7701         InsertNewInstBefore(NewTrunc, I);
7702         return new SExtInst(NewTrunc, Ty);
7703       }
7704       // Otherwise, we can't handle it yet.
7705     } else if (ShiftAmt1 < ShiftAmt2) {
7706       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7707       
7708       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7709       if (I.getOpcode() == Instruction::Shl) {
7710         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7711                ShiftOp->getOpcode() == Instruction::AShr);
7712         Instruction *Shift =
7713           BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7714         InsertNewInstBefore(Shift, I);
7715         
7716         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7717         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7718       }
7719       
7720       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7721       if (I.getOpcode() == Instruction::LShr) {
7722         assert(ShiftOp->getOpcode() == Instruction::Shl);
7723         Instruction *Shift =
7724           BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, ShiftDiff));
7725         InsertNewInstBefore(Shift, I);
7726         
7727         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7728         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7729       }
7730       
7731       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7732     } else {
7733       assert(ShiftAmt2 < ShiftAmt1);
7734       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7735
7736       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7737       if (I.getOpcode() == Instruction::Shl) {
7738         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7739                ShiftOp->getOpcode() == Instruction::AShr);
7740         Instruction *Shift =
7741           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7742                                  Context->getConstantInt(Ty, ShiftDiff));
7743         InsertNewInstBefore(Shift, I);
7744         
7745         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7746         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7747       }
7748       
7749       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7750       if (I.getOpcode() == Instruction::LShr) {
7751         assert(ShiftOp->getOpcode() == Instruction::Shl);
7752         Instruction *Shift =
7753           BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7754         InsertNewInstBefore(Shift, I);
7755         
7756         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7757         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7758       }
7759       
7760       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7761     }
7762   }
7763   return 0;
7764 }
7765
7766
7767 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7768 /// expression.  If so, decompose it, returning some value X, such that Val is
7769 /// X*Scale+Offset.
7770 ///
7771 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7772                                         int &Offset, LLVMContext *Context) {
7773   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7774   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7775     Offset = CI->getZExtValue();
7776     Scale  = 0;
7777     return Context->getConstantInt(Type::Int32Ty, 0);
7778   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7779     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7780       if (I->getOpcode() == Instruction::Shl) {
7781         // This is a value scaled by '1 << the shift amt'.
7782         Scale = 1U << RHS->getZExtValue();
7783         Offset = 0;
7784         return I->getOperand(0);
7785       } else if (I->getOpcode() == Instruction::Mul) {
7786         // This value is scaled by 'RHS'.
7787         Scale = RHS->getZExtValue();
7788         Offset = 0;
7789         return I->getOperand(0);
7790       } else if (I->getOpcode() == Instruction::Add) {
7791         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7792         // where C1 is divisible by C2.
7793         unsigned SubScale;
7794         Value *SubVal = 
7795           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7796                                     Offset, Context);
7797         Offset += RHS->getZExtValue();
7798         Scale = SubScale;
7799         return SubVal;
7800       }
7801     }
7802   }
7803
7804   // Otherwise, we can't look past this.
7805   Scale = 1;
7806   Offset = 0;
7807   return Val;
7808 }
7809
7810
7811 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7812 /// try to eliminate the cast by moving the type information into the alloc.
7813 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7814                                                    AllocationInst &AI) {
7815   const PointerType *PTy = cast<PointerType>(CI.getType());
7816   
7817   // Remove any uses of AI that are dead.
7818   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7819   
7820   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7821     Instruction *User = cast<Instruction>(*UI++);
7822     if (isInstructionTriviallyDead(User)) {
7823       while (UI != E && *UI == User)
7824         ++UI; // If this instruction uses AI more than once, don't break UI.
7825       
7826       ++NumDeadInst;
7827       DOUT << "IC: DCE: " << *User;
7828       EraseInstFromFunction(*User);
7829     }
7830   }
7831   
7832   // Get the type really allocated and the type casted to.
7833   const Type *AllocElTy = AI.getAllocatedType();
7834   const Type *CastElTy = PTy->getElementType();
7835   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7836
7837   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7838   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7839   if (CastElTyAlign < AllocElTyAlign) return 0;
7840
7841   // If the allocation has multiple uses, only promote it if we are strictly
7842   // increasing the alignment of the resultant allocation.  If we keep it the
7843   // same, we open the door to infinite loops of various kinds.  (A reference
7844   // from a dbg.declare doesn't count as a use for this purpose.)
7845   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7846       CastElTyAlign == AllocElTyAlign) return 0;
7847
7848   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7849   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7850   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7851
7852   // See if we can satisfy the modulus by pulling a scale out of the array
7853   // size argument.
7854   unsigned ArraySizeScale;
7855   int ArrayOffset;
7856   Value *NumElements = // See if the array size is a decomposable linear expr.
7857     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7858                               ArrayOffset, Context);
7859  
7860   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7861   // do the xform.
7862   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7863       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7864
7865   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7866   Value *Amt = 0;
7867   if (Scale == 1) {
7868     Amt = NumElements;
7869   } else {
7870     // If the allocation size is constant, form a constant mul expression
7871     Amt = Context->getConstantInt(Type::Int32Ty, Scale);
7872     if (isa<ConstantInt>(NumElements))
7873       Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
7874                                  cast<ConstantInt>(Amt));
7875     // otherwise multiply the amount and the number of elements
7876     else {
7877       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7878       Amt = InsertNewInstBefore(Tmp, AI);
7879     }
7880   }
7881   
7882   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7883     Value *Off = Context->getConstantInt(Type::Int32Ty, Offset, true);
7884     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7885     Amt = InsertNewInstBefore(Tmp, AI);
7886   }
7887   
7888   AllocationInst *New;
7889   if (isa<MallocInst>(AI))
7890     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7891   else
7892     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7893   InsertNewInstBefore(New, AI);
7894   New->takeName(&AI);
7895   
7896   // If the allocation has one real use plus a dbg.declare, just remove the
7897   // declare.
7898   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7899     EraseInstFromFunction(*DI);
7900   }
7901   // If the allocation has multiple real uses, insert a cast and change all
7902   // things that used it to use the new cast.  This will also hack on CI, but it
7903   // will die soon.
7904   else if (!AI.hasOneUse()) {
7905     AddUsesToWorkList(AI);
7906     // New is the allocation instruction, pointer typed. AI is the original
7907     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7908     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7909     InsertNewInstBefore(NewCast, AI);
7910     AI.replaceAllUsesWith(NewCast);
7911   }
7912   return ReplaceInstUsesWith(CI, New);
7913 }
7914
7915 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7916 /// and return it as type Ty without inserting any new casts and without
7917 /// changing the computed value.  This is used by code that tries to decide
7918 /// whether promoting or shrinking integer operations to wider or smaller types
7919 /// will allow us to eliminate a truncate or extend.
7920 ///
7921 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7922 /// extension operation if Ty is larger.
7923 ///
7924 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7925 /// should return true if trunc(V) can be computed by computing V in the smaller
7926 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7927 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7928 /// efficiently truncated.
7929 ///
7930 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7931 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7932 /// the final result.
7933 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7934                                               unsigned CastOpc,
7935                                               int &NumCastsRemoved){
7936   // We can always evaluate constants in another type.
7937   if (isa<Constant>(V))
7938     return true;
7939   
7940   Instruction *I = dyn_cast<Instruction>(V);
7941   if (!I) return false;
7942   
7943   const Type *OrigTy = V->getType();
7944   
7945   // If this is an extension or truncate, we can often eliminate it.
7946   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7947     // If this is a cast from the destination type, we can trivially eliminate
7948     // it, and this will remove a cast overall.
7949     if (I->getOperand(0)->getType() == Ty) {
7950       // If the first operand is itself a cast, and is eliminable, do not count
7951       // this as an eliminable cast.  We would prefer to eliminate those two
7952       // casts first.
7953       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7954         ++NumCastsRemoved;
7955       return true;
7956     }
7957   }
7958
7959   // We can't extend or shrink something that has multiple uses: doing so would
7960   // require duplicating the instruction in general, which isn't profitable.
7961   if (!I->hasOneUse()) return false;
7962
7963   unsigned Opc = I->getOpcode();
7964   switch (Opc) {
7965   case Instruction::Add:
7966   case Instruction::Sub:
7967   case Instruction::Mul:
7968   case Instruction::And:
7969   case Instruction::Or:
7970   case Instruction::Xor:
7971     // These operators can all arbitrarily be extended or truncated.
7972     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7973                                       NumCastsRemoved) &&
7974            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7975                                       NumCastsRemoved);
7976
7977   case Instruction::Shl:
7978     // If we are truncating the result of this SHL, and if it's a shift of a
7979     // constant amount, we can always perform a SHL in a smaller type.
7980     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7981       uint32_t BitWidth = Ty->getScalarSizeInBits();
7982       if (BitWidth < OrigTy->getScalarSizeInBits() &&
7983           CI->getLimitedValue(BitWidth) < BitWidth)
7984         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7985                                           NumCastsRemoved);
7986     }
7987     break;
7988   case Instruction::LShr:
7989     // If this is a truncate of a logical shr, we can truncate it to a smaller
7990     // lshr iff we know that the bits we would otherwise be shifting in are
7991     // already zeros.
7992     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7993       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7994       uint32_t BitWidth = Ty->getScalarSizeInBits();
7995       if (BitWidth < OrigBitWidth &&
7996           MaskedValueIsZero(I->getOperand(0),
7997             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7998           CI->getLimitedValue(BitWidth) < BitWidth) {
7999         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8000                                           NumCastsRemoved);
8001       }
8002     }
8003     break;
8004   case Instruction::ZExt:
8005   case Instruction::SExt:
8006   case Instruction::Trunc:
8007     // If this is the same kind of case as our original (e.g. zext+zext), we
8008     // can safely replace it.  Note that replacing it does not reduce the number
8009     // of casts in the input.
8010     if (Opc == CastOpc)
8011       return true;
8012
8013     // sext (zext ty1), ty2 -> zext ty2
8014     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
8015       return true;
8016     break;
8017   case Instruction::Select: {
8018     SelectInst *SI = cast<SelectInst>(I);
8019     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8020                                       NumCastsRemoved) &&
8021            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8022                                       NumCastsRemoved);
8023   }
8024   case Instruction::PHI: {
8025     // We can change a phi if we can change all operands.
8026     PHINode *PN = cast<PHINode>(I);
8027     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8028       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8029                                       NumCastsRemoved))
8030         return false;
8031     return true;
8032   }
8033   default:
8034     // TODO: Can handle more cases here.
8035     break;
8036   }
8037   
8038   return false;
8039 }
8040
8041 /// EvaluateInDifferentType - Given an expression that 
8042 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8043 /// evaluate the expression.
8044 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
8045                                              bool isSigned) {
8046   if (Constant *C = dyn_cast<Constant>(V))
8047     return Context->getConstantExprIntegerCast(C, Ty,
8048                                                isSigned /*Sext or ZExt*/);
8049
8050   // Otherwise, it must be an instruction.
8051   Instruction *I = cast<Instruction>(V);
8052   Instruction *Res = 0;
8053   unsigned Opc = I->getOpcode();
8054   switch (Opc) {
8055   case Instruction::Add:
8056   case Instruction::Sub:
8057   case Instruction::Mul:
8058   case Instruction::And:
8059   case Instruction::Or:
8060   case Instruction::Xor:
8061   case Instruction::AShr:
8062   case Instruction::LShr:
8063   case Instruction::Shl: {
8064     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8065     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8066     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8067     break;
8068   }    
8069   case Instruction::Trunc:
8070   case Instruction::ZExt:
8071   case Instruction::SExt:
8072     // If the source type of the cast is the type we're trying for then we can
8073     // just return the source.  There's no need to insert it because it is not
8074     // new.
8075     if (I->getOperand(0)->getType() == Ty)
8076       return I->getOperand(0);
8077     
8078     // Otherwise, must be the same type of cast, so just reinsert a new one.
8079     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8080                            Ty);
8081     break;
8082   case Instruction::Select: {
8083     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8084     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8085     Res = SelectInst::Create(I->getOperand(0), True, False);
8086     break;
8087   }
8088   case Instruction::PHI: {
8089     PHINode *OPN = cast<PHINode>(I);
8090     PHINode *NPN = PHINode::Create(Ty);
8091     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8092       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8093       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8094     }
8095     Res = NPN;
8096     break;
8097   }
8098   default: 
8099     // TODO: Can handle more cases here.
8100     LLVM_UNREACHABLE("Unreachable!");
8101     break;
8102   }
8103   
8104   Res->takeName(I);
8105   return InsertNewInstBefore(Res, *I);
8106 }
8107
8108 /// @brief Implement the transforms common to all CastInst visitors.
8109 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8110   Value *Src = CI.getOperand(0);
8111
8112   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8113   // eliminate it now.
8114   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8115     if (Instruction::CastOps opc = 
8116         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8117       // The first cast (CSrc) is eliminable so we need to fix up or replace
8118       // the second cast (CI). CSrc will then have a good chance of being dead.
8119       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8120     }
8121   }
8122
8123   // If we are casting a select then fold the cast into the select
8124   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8125     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8126       return NV;
8127
8128   // If we are casting a PHI then fold the cast into the PHI
8129   if (isa<PHINode>(Src))
8130     if (Instruction *NV = FoldOpIntoPhi(CI))
8131       return NV;
8132   
8133   return 0;
8134 }
8135
8136 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8137 /// or not there is a sequence of GEP indices into the type that will land us at
8138 /// the specified offset.  If so, fill them into NewIndices and return the
8139 /// resultant element type, otherwise return null.
8140 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8141                                        SmallVectorImpl<Value*> &NewIndices,
8142                                        const TargetData *TD,
8143                                        LLVMContext *Context) {
8144   if (!Ty->isSized()) return 0;
8145   
8146   // Start with the index over the outer type.  Note that the type size
8147   // might be zero (even if the offset isn't zero) if the indexed type
8148   // is something like [0 x {int, int}]
8149   const Type *IntPtrTy = TD->getIntPtrType();
8150   int64_t FirstIdx = 0;
8151   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8152     FirstIdx = Offset/TySize;
8153     Offset -= FirstIdx*TySize;
8154     
8155     // Handle hosts where % returns negative instead of values [0..TySize).
8156     if (Offset < 0) {
8157       --FirstIdx;
8158       Offset += TySize;
8159       assert(Offset >= 0);
8160     }
8161     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8162   }
8163   
8164   NewIndices.push_back(Context->getConstantInt(IntPtrTy, FirstIdx));
8165     
8166   // Index into the types.  If we fail, set OrigBase to null.
8167   while (Offset) {
8168     // Indexing into tail padding between struct/array elements.
8169     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8170       return 0;
8171     
8172     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8173       const StructLayout *SL = TD->getStructLayout(STy);
8174       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8175              "Offset must stay within the indexed type");
8176       
8177       unsigned Elt = SL->getElementContainingOffset(Offset);
8178       NewIndices.push_back(Context->getConstantInt(Type::Int32Ty, Elt));
8179       
8180       Offset -= SL->getElementOffset(Elt);
8181       Ty = STy->getElementType(Elt);
8182     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8183       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8184       assert(EltSize && "Cannot index into a zero-sized array");
8185       NewIndices.push_back(Context->getConstantInt(IntPtrTy,Offset/EltSize));
8186       Offset %= EltSize;
8187       Ty = AT->getElementType();
8188     } else {
8189       // Otherwise, we can't index into the middle of this atomic type, bail.
8190       return 0;
8191     }
8192   }
8193   
8194   return Ty;
8195 }
8196
8197 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8198 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8199   Value *Src = CI.getOperand(0);
8200   
8201   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8202     // If casting the result of a getelementptr instruction with no offset, turn
8203     // this into a cast of the original pointer!
8204     if (GEP->hasAllZeroIndices()) {
8205       // Changing the cast operand is usually not a good idea but it is safe
8206       // here because the pointer operand is being replaced with another 
8207       // pointer operand so the opcode doesn't need to change.
8208       AddToWorkList(GEP);
8209       CI.setOperand(0, GEP->getOperand(0));
8210       return &CI;
8211     }
8212     
8213     // If the GEP has a single use, and the base pointer is a bitcast, and the
8214     // GEP computes a constant offset, see if we can convert these three
8215     // instructions into fewer.  This typically happens with unions and other
8216     // non-type-safe code.
8217     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8218       if (GEP->hasAllConstantIndices()) {
8219         // We are guaranteed to get a constant from EmitGEPOffset.
8220         ConstantInt *OffsetV =
8221                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8222         int64_t Offset = OffsetV->getSExtValue();
8223         
8224         // Get the base pointer input of the bitcast, and the type it points to.
8225         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8226         const Type *GEPIdxTy =
8227           cast<PointerType>(OrigBase->getType())->getElementType();
8228         SmallVector<Value*, 8> NewIndices;
8229         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8230           // If we were able to index down into an element, create the GEP
8231           // and bitcast the result.  This eliminates one bitcast, potentially
8232           // two.
8233           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
8234                                                         NewIndices.begin(),
8235                                                         NewIndices.end(), "");
8236           InsertNewInstBefore(NGEP, CI);
8237           NGEP->takeName(GEP);
8238           
8239           if (isa<BitCastInst>(CI))
8240             return new BitCastInst(NGEP, CI.getType());
8241           assert(isa<PtrToIntInst>(CI));
8242           return new PtrToIntInst(NGEP, CI.getType());
8243         }
8244       }      
8245     }
8246   }
8247     
8248   return commonCastTransforms(CI);
8249 }
8250
8251 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8252 /// type like i42.  We don't want to introduce operations on random non-legal
8253 /// integer types where they don't already exist in the code.  In the future,
8254 /// we should consider making this based off target-data, so that 32-bit targets
8255 /// won't get i64 operations etc.
8256 static bool isSafeIntegerType(const Type *Ty) {
8257   switch (Ty->getPrimitiveSizeInBits()) {
8258   case 8:
8259   case 16:
8260   case 32:
8261   case 64:
8262     return true;
8263   default: 
8264     return false;
8265   }
8266 }
8267
8268 /// commonIntCastTransforms - This function implements the common transforms
8269 /// for trunc, zext, and sext.
8270 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8271   if (Instruction *Result = commonCastTransforms(CI))
8272     return Result;
8273
8274   Value *Src = CI.getOperand(0);
8275   const Type *SrcTy = Src->getType();
8276   const Type *DestTy = CI.getType();
8277   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8278   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8279
8280   // See if we can simplify any instructions used by the LHS whose sole 
8281   // purpose is to compute bits we don't care about.
8282   if (SimplifyDemandedInstructionBits(CI))
8283     return &CI;
8284
8285   // If the source isn't an instruction or has more than one use then we
8286   // can't do anything more. 
8287   Instruction *SrcI = dyn_cast<Instruction>(Src);
8288   if (!SrcI || !Src->hasOneUse())
8289     return 0;
8290
8291   // Attempt to propagate the cast into the instruction for int->int casts.
8292   int NumCastsRemoved = 0;
8293   // Only do this if the dest type is a simple type, don't convert the
8294   // expression tree to something weird like i93 unless the source is also
8295   // strange.
8296   if ((isSafeIntegerType(DestTy->getScalarType()) ||
8297        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8298       CanEvaluateInDifferentType(SrcI, DestTy,
8299                                  CI.getOpcode(), NumCastsRemoved)) {
8300     // If this cast is a truncate, evaluting in a different type always
8301     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8302     // we need to do an AND to maintain the clear top-part of the computation,
8303     // so we require that the input have eliminated at least one cast.  If this
8304     // is a sign extension, we insert two new casts (to do the extension) so we
8305     // require that two casts have been eliminated.
8306     bool DoXForm = false;
8307     bool JustReplace = false;
8308     switch (CI.getOpcode()) {
8309     default:
8310       // All the others use floating point so we shouldn't actually 
8311       // get here because of the check above.
8312       LLVM_UNREACHABLE("Unknown cast type");
8313     case Instruction::Trunc:
8314       DoXForm = true;
8315       break;
8316     case Instruction::ZExt: {
8317       DoXForm = NumCastsRemoved >= 1;
8318       if (!DoXForm && 0) {
8319         // If it's unnecessary to issue an AND to clear the high bits, it's
8320         // always profitable to do this xform.
8321         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8322         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8323         if (MaskedValueIsZero(TryRes, Mask))
8324           return ReplaceInstUsesWith(CI, TryRes);
8325         
8326         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8327           if (TryI->use_empty())
8328             EraseInstFromFunction(*TryI);
8329       }
8330       break;
8331     }
8332     case Instruction::SExt: {
8333       DoXForm = NumCastsRemoved >= 2;
8334       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8335         // If we do not have to emit the truncate + sext pair, then it's always
8336         // profitable to do this xform.
8337         //
8338         // It's not safe to eliminate the trunc + sext pair if one of the
8339         // eliminated cast is a truncate. e.g.
8340         // t2 = trunc i32 t1 to i16
8341         // t3 = sext i16 t2 to i32
8342         // !=
8343         // i32 t1
8344         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8345         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8346         if (NumSignBits > (DestBitSize - SrcBitSize))
8347           return ReplaceInstUsesWith(CI, TryRes);
8348         
8349         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8350           if (TryI->use_empty())
8351             EraseInstFromFunction(*TryI);
8352       }
8353       break;
8354     }
8355     }
8356     
8357     if (DoXForm) {
8358       DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8359            << " cast: " << CI;
8360       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8361                                            CI.getOpcode() == Instruction::SExt);
8362       if (JustReplace)
8363         // Just replace this cast with the result.
8364         return ReplaceInstUsesWith(CI, Res);
8365
8366       assert(Res->getType() == DestTy);
8367       switch (CI.getOpcode()) {
8368       default: LLVM_UNREACHABLE("Unknown cast type!");
8369       case Instruction::Trunc:
8370         // Just replace this cast with the result.
8371         return ReplaceInstUsesWith(CI, Res);
8372       case Instruction::ZExt: {
8373         assert(SrcBitSize < DestBitSize && "Not a zext?");
8374
8375         // If the high bits are already zero, just replace this cast with the
8376         // result.
8377         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8378         if (MaskedValueIsZero(Res, Mask))
8379           return ReplaceInstUsesWith(CI, Res);
8380
8381         // We need to emit an AND to clear the high bits.
8382         Constant *C = Context->getConstantInt(APInt::getLowBitsSet(DestBitSize,
8383                                                             SrcBitSize));
8384         return BinaryOperator::CreateAnd(Res, C);
8385       }
8386       case Instruction::SExt: {
8387         // If the high bits are already filled with sign bit, just replace this
8388         // cast with the result.
8389         unsigned NumSignBits = ComputeNumSignBits(Res);
8390         if (NumSignBits > (DestBitSize - SrcBitSize))
8391           return ReplaceInstUsesWith(CI, Res);
8392
8393         // We need to emit a cast to truncate, then a cast to sext.
8394         return CastInst::Create(Instruction::SExt,
8395             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8396                              CI), DestTy);
8397       }
8398       }
8399     }
8400   }
8401   
8402   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8403   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8404
8405   switch (SrcI->getOpcode()) {
8406   case Instruction::Add:
8407   case Instruction::Mul:
8408   case Instruction::And:
8409   case Instruction::Or:
8410   case Instruction::Xor:
8411     // If we are discarding information, rewrite.
8412     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8413       // Don't insert two casts unless at least one can be eliminated.
8414       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8415           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8416         Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8417         Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8418         return BinaryOperator::Create(
8419             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8420       }
8421     }
8422
8423     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8424     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8425         SrcI->getOpcode() == Instruction::Xor &&
8426         Op1 == Context->getConstantIntTrue() &&
8427         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8428       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8429       return BinaryOperator::CreateXor(New,
8430                                       Context->getConstantInt(CI.getType(), 1));
8431     }
8432     break;
8433
8434   case Instruction::Shl: {
8435     // Canonicalize trunc inside shl, if we can.
8436     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8437     if (CI && DestBitSize < SrcBitSize &&
8438         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8439       Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8440       Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8441       return BinaryOperator::CreateShl(Op0c, Op1c);
8442     }
8443     break;
8444   }
8445   }
8446   return 0;
8447 }
8448
8449 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8450   if (Instruction *Result = commonIntCastTransforms(CI))
8451     return Result;
8452   
8453   Value *Src = CI.getOperand(0);
8454   const Type *Ty = CI.getType();
8455   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8456   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8457
8458   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8459   if (DestBitWidth == 1 &&
8460       isa<VectorType>(Ty) == isa<VectorType>(Src->getType())) {
8461     Constant *One = Context->getConstantInt(Src->getType(), 1);
8462     Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8463     Value *Zero = Context->getNullValue(Src->getType());
8464     return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
8465   }
8466
8467   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8468   ConstantInt *ShAmtV = 0;
8469   Value *ShiftOp = 0;
8470   if (Src->hasOneUse() &&
8471       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
8472     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8473     
8474     // Get a mask for the bits shifting in.
8475     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8476     if (MaskedValueIsZero(ShiftOp, Mask)) {
8477       if (ShAmt >= DestBitWidth)        // All zeros.
8478         return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
8479       
8480       // Okay, we can shrink this.  Truncate the input, then return a new
8481       // shift.
8482       Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8483       Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
8484       return BinaryOperator::CreateLShr(V1, V2);
8485     }
8486   }
8487   
8488   return 0;
8489 }
8490
8491 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8492 /// in order to eliminate the icmp.
8493 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8494                                              bool DoXform) {
8495   // If we are just checking for a icmp eq of a single bit and zext'ing it
8496   // to an integer, then shift the bit to the appropriate place and then
8497   // cast to integer to avoid the comparison.
8498   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8499     const APInt &Op1CV = Op1C->getValue();
8500       
8501     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8502     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8503     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8504         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8505       if (!DoXform) return ICI;
8506
8507       Value *In = ICI->getOperand(0);
8508       Value *Sh = Context->getConstantInt(In->getType(),
8509                                    In->getType()->getScalarSizeInBits()-1);
8510       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8511                                                         In->getName()+".lobit"),
8512                                CI);
8513       if (In->getType() != CI.getType())
8514         In = CastInst::CreateIntegerCast(In, CI.getType(),
8515                                          false/*ZExt*/, "tmp", &CI);
8516
8517       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8518         Constant *One = Context->getConstantInt(In->getType(), 1);
8519         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8520                                                          In->getName()+".not"),
8521                                  CI);
8522       }
8523
8524       return ReplaceInstUsesWith(CI, In);
8525     }
8526       
8527       
8528       
8529     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8530     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8531     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8532     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8533     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8534     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8535     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8536     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8537     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8538         // This only works for EQ and NE
8539         ICI->isEquality()) {
8540       // If Op1C some other power of two, convert:
8541       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8542       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8543       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8544       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8545         
8546       APInt KnownZeroMask(~KnownZero);
8547       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8548         if (!DoXform) return ICI;
8549
8550         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8551         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8552           // (X&4) == 2 --> false
8553           // (X&4) != 2 --> true
8554           Constant *Res = Context->getConstantInt(Type::Int1Ty, isNE);
8555           Res = Context->getConstantExprZExt(Res, CI.getType());
8556           return ReplaceInstUsesWith(CI, Res);
8557         }
8558           
8559         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8560         Value *In = ICI->getOperand(0);
8561         if (ShiftAmt) {
8562           // Perform a logical shr by shiftamt.
8563           // Insert the shift to put the result in the low bit.
8564           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8565                               Context->getConstantInt(In->getType(), ShiftAmt),
8566                                                    In->getName()+".lobit"), CI);
8567         }
8568           
8569         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8570           Constant *One = Context->getConstantInt(In->getType(), 1);
8571           In = BinaryOperator::CreateXor(In, One, "tmp");
8572           InsertNewInstBefore(cast<Instruction>(In), CI);
8573         }
8574           
8575         if (CI.getType() == In->getType())
8576           return ReplaceInstUsesWith(CI, In);
8577         else
8578           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8579       }
8580     }
8581   }
8582
8583   return 0;
8584 }
8585
8586 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8587   // If one of the common conversion will work ..
8588   if (Instruction *Result = commonIntCastTransforms(CI))
8589     return Result;
8590
8591   Value *Src = CI.getOperand(0);
8592
8593   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8594   // types and if the sizes are just right we can convert this into a logical
8595   // 'and' which will be much cheaper than the pair of casts.
8596   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8597     // Get the sizes of the types involved.  We know that the intermediate type
8598     // will be smaller than A or C, but don't know the relation between A and C.
8599     Value *A = CSrc->getOperand(0);
8600     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8601     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8602     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8603     // If we're actually extending zero bits, then if
8604     // SrcSize <  DstSize: zext(a & mask)
8605     // SrcSize == DstSize: a & mask
8606     // SrcSize  > DstSize: trunc(a) & mask
8607     if (SrcSize < DstSize) {
8608       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8609       Constant *AndConst = Context->getConstantInt(A->getType(), AndValue);
8610       Instruction *And =
8611         BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8612       InsertNewInstBefore(And, CI);
8613       return new ZExtInst(And, CI.getType());
8614     } else if (SrcSize == DstSize) {
8615       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8616       return BinaryOperator::CreateAnd(A, Context->getConstantInt(A->getType(),
8617                                                            AndValue));
8618     } else if (SrcSize > DstSize) {
8619       Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8620       InsertNewInstBefore(Trunc, CI);
8621       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8622       return BinaryOperator::CreateAnd(Trunc, 
8623                                        Context->getConstantInt(Trunc->getType(),
8624                                                                AndValue));
8625     }
8626   }
8627
8628   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8629     return transformZExtICmp(ICI, CI);
8630
8631   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8632   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8633     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8634     // of the (zext icmp) will be transformed.
8635     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8636     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8637     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8638         (transformZExtICmp(LHS, CI, false) ||
8639          transformZExtICmp(RHS, CI, false))) {
8640       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8641       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8642       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8643     }
8644   }
8645
8646   // zext(trunc(t) & C) -> (t & zext(C)).
8647   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8648     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8649       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8650         Value *TI0 = TI->getOperand(0);
8651         if (TI0->getType() == CI.getType())
8652           return
8653             BinaryOperator::CreateAnd(TI0,
8654                                 Context->getConstantExprZExt(C, CI.getType()));
8655       }
8656
8657   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8658   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8659     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8660       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8661         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8662             And->getOperand(1) == C)
8663           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8664             Value *TI0 = TI->getOperand(0);
8665             if (TI0->getType() == CI.getType()) {
8666               Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
8667               Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8668               InsertNewInstBefore(NewAnd, *And);
8669               return BinaryOperator::CreateXor(NewAnd, ZC);
8670             }
8671           }
8672
8673   return 0;
8674 }
8675
8676 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8677   if (Instruction *I = commonIntCastTransforms(CI))
8678     return I;
8679   
8680   Value *Src = CI.getOperand(0);
8681   
8682   // Canonicalize sign-extend from i1 to a select.
8683   if (Src->getType() == Type::Int1Ty)
8684     return SelectInst::Create(Src,
8685                               Context->getAllOnesValue(CI.getType()),
8686                               Context->getNullValue(CI.getType()));
8687
8688   // See if the value being truncated is already sign extended.  If so, just
8689   // eliminate the trunc/sext pair.
8690   if (getOpcode(Src) == Instruction::Trunc) {
8691     Value *Op = cast<User>(Src)->getOperand(0);
8692     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8693     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8694     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8695     unsigned NumSignBits = ComputeNumSignBits(Op);
8696
8697     if (OpBits == DestBits) {
8698       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8699       // bits, it is already ready.
8700       if (NumSignBits > DestBits-MidBits)
8701         return ReplaceInstUsesWith(CI, Op);
8702     } else if (OpBits < DestBits) {
8703       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8704       // bits, just sext from i32.
8705       if (NumSignBits > OpBits-MidBits)
8706         return new SExtInst(Op, CI.getType(), "tmp");
8707     } else {
8708       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8709       // bits, just truncate to i32.
8710       if (NumSignBits > OpBits-MidBits)
8711         return new TruncInst(Op, CI.getType(), "tmp");
8712     }
8713   }
8714
8715   // If the input is a shl/ashr pair of a same constant, then this is a sign
8716   // extension from a smaller value.  If we could trust arbitrary bitwidth
8717   // integers, we could turn this into a truncate to the smaller bit and then
8718   // use a sext for the whole extension.  Since we don't, look deeper and check
8719   // for a truncate.  If the source and dest are the same type, eliminate the
8720   // trunc and extend and just do shifts.  For example, turn:
8721   //   %a = trunc i32 %i to i8
8722   //   %b = shl i8 %a, 6
8723   //   %c = ashr i8 %b, 6
8724   //   %d = sext i8 %c to i32
8725   // into:
8726   //   %a = shl i32 %i, 30
8727   //   %d = ashr i32 %a, 30
8728   Value *A = 0;
8729   ConstantInt *BA = 0, *CA = 0;
8730   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8731                         m_ConstantInt(CA)), *Context) &&
8732       BA == CA && isa<TruncInst>(A)) {
8733     Value *I = cast<TruncInst>(A)->getOperand(0);
8734     if (I->getType() == CI.getType()) {
8735       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8736       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8737       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8738       Constant *ShAmtV = Context->getConstantInt(CI.getType(), ShAmt);
8739       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8740                                                         CI.getName()), CI);
8741       return BinaryOperator::CreateAShr(I, ShAmtV);
8742     }
8743   }
8744   
8745   return 0;
8746 }
8747
8748 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8749 /// in the specified FP type without changing its value.
8750 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8751                               LLVMContext *Context) {
8752   bool losesInfo;
8753   APFloat F = CFP->getValueAPF();
8754   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8755   if (!losesInfo)
8756     return Context->getConstantFP(F);
8757   return 0;
8758 }
8759
8760 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8761 /// through it until we get the source value.
8762 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8763   if (Instruction *I = dyn_cast<Instruction>(V))
8764     if (I->getOpcode() == Instruction::FPExt)
8765       return LookThroughFPExtensions(I->getOperand(0), Context);
8766   
8767   // If this value is a constant, return the constant in the smallest FP type
8768   // that can accurately represent it.  This allows us to turn
8769   // (float)((double)X+2.0) into x+2.0f.
8770   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8771     if (CFP->getType() == Type::PPC_FP128Ty)
8772       return V;  // No constant folding of this.
8773     // See if the value can be truncated to float and then reextended.
8774     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8775       return V;
8776     if (CFP->getType() == Type::DoubleTy)
8777       return V;  // Won't shrink.
8778     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8779       return V;
8780     // Don't try to shrink to various long double types.
8781   }
8782   
8783   return V;
8784 }
8785
8786 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8787   if (Instruction *I = commonCastTransforms(CI))
8788     return I;
8789   
8790   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8791   // smaller than the destination type, we can eliminate the truncate by doing
8792   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8793   // many builtins (sqrt, etc).
8794   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8795   if (OpI && OpI->hasOneUse()) {
8796     switch (OpI->getOpcode()) {
8797     default: break;
8798     case Instruction::FAdd:
8799     case Instruction::FSub:
8800     case Instruction::FMul:
8801     case Instruction::FDiv:
8802     case Instruction::FRem:
8803       const Type *SrcTy = OpI->getType();
8804       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8805       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8806       if (LHSTrunc->getType() != SrcTy && 
8807           RHSTrunc->getType() != SrcTy) {
8808         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8809         // If the source types were both smaller than the destination type of
8810         // the cast, do this xform.
8811         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8812             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8813           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8814                                       CI.getType(), CI);
8815           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8816                                       CI.getType(), CI);
8817           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8818         }
8819       }
8820       break;  
8821     }
8822   }
8823   return 0;
8824 }
8825
8826 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8827   return commonCastTransforms(CI);
8828 }
8829
8830 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8831   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8832   if (OpI == 0)
8833     return commonCastTransforms(FI);
8834
8835   // fptoui(uitofp(X)) --> X
8836   // fptoui(sitofp(X)) --> X
8837   // This is safe if the intermediate type has enough bits in its mantissa to
8838   // accurately represent all values of X.  For example, do not do this with
8839   // i64->float->i64.  This is also safe for sitofp case, because any negative
8840   // 'X' value would cause an undefined result for the fptoui. 
8841   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8842       OpI->getOperand(0)->getType() == FI.getType() &&
8843       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8844                     OpI->getType()->getFPMantissaWidth())
8845     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8846
8847   return commonCastTransforms(FI);
8848 }
8849
8850 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8851   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8852   if (OpI == 0)
8853     return commonCastTransforms(FI);
8854   
8855   // fptosi(sitofp(X)) --> X
8856   // fptosi(uitofp(X)) --> X
8857   // This is safe if the intermediate type has enough bits in its mantissa to
8858   // accurately represent all values of X.  For example, do not do this with
8859   // i64->float->i64.  This is also safe for sitofp case, because any negative
8860   // 'X' value would cause an undefined result for the fptoui. 
8861   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8862       OpI->getOperand(0)->getType() == FI.getType() &&
8863       (int)FI.getType()->getScalarSizeInBits() <=
8864                     OpI->getType()->getFPMantissaWidth())
8865     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8866   
8867   return commonCastTransforms(FI);
8868 }
8869
8870 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8871   return commonCastTransforms(CI);
8872 }
8873
8874 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8875   return commonCastTransforms(CI);
8876 }
8877
8878 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8879   // If the destination integer type is smaller than the intptr_t type for
8880   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8881   // trunc to be exposed to other transforms.  Don't do this for extending
8882   // ptrtoint's, because we don't know if the target sign or zero extends its
8883   // pointers.
8884   if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8885     Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8886                                                     TD->getIntPtrType(),
8887                                                     "tmp"), CI);
8888     return new TruncInst(P, CI.getType());
8889   }
8890   
8891   return commonPointerCastTransforms(CI);
8892 }
8893
8894 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8895   // If the source integer type is larger than the intptr_t type for
8896   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8897   // allows the trunc to be exposed to other transforms.  Don't do this for
8898   // extending inttoptr's, because we don't know if the target sign or zero
8899   // extends to pointers.
8900   if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
8901       TD->getPointerSizeInBits()) {
8902     Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8903                                                  TD->getIntPtrType(),
8904                                                  "tmp"), CI);
8905     return new IntToPtrInst(P, CI.getType());
8906   }
8907   
8908   if (Instruction *I = commonCastTransforms(CI))
8909     return I;
8910   
8911   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8912   if (!DestPointee->isSized()) return 0;
8913
8914   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8915   ConstantInt *Cst;
8916   Value *X;
8917   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8918                                     m_ConstantInt(Cst)), *Context)) {
8919     // If the source and destination operands have the same type, see if this
8920     // is a single-index GEP.
8921     if (X->getType() == CI.getType()) {
8922       // Get the size of the pointee type.
8923       uint64_t Size = TD->getTypeAllocSize(DestPointee);
8924
8925       // Convert the constant to intptr type.
8926       APInt Offset = Cst->getValue();
8927       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8928
8929       // If Offset is evenly divisible by Size, we can do this xform.
8930       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8931         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8932         return GetElementPtrInst::Create(X, Context->getConstantInt(Offset));
8933       }
8934     }
8935     // TODO: Could handle other cases, e.g. where add is indexing into field of
8936     // struct etc.
8937   } else if (CI.getOperand(0)->hasOneUse() &&
8938              match(CI.getOperand(0), m_Add(m_Value(X),
8939                    m_ConstantInt(Cst)), *Context)) {
8940     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8941     // "inttoptr+GEP" instead of "add+intptr".
8942     
8943     // Get the size of the pointee type.
8944     uint64_t Size = TD->getTypeAllocSize(DestPointee);
8945     
8946     // Convert the constant to intptr type.
8947     APInt Offset = Cst->getValue();
8948     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8949     
8950     // If Offset is evenly divisible by Size, we can do this xform.
8951     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8952       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8953       
8954       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8955                                                             "tmp"), CI);
8956       return GetElementPtrInst::Create(P,
8957                                        Context->getConstantInt(Offset), "tmp");
8958     }
8959   }
8960   return 0;
8961 }
8962
8963 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8964   // If the operands are integer typed then apply the integer transforms,
8965   // otherwise just apply the common ones.
8966   Value *Src = CI.getOperand(0);
8967   const Type *SrcTy = Src->getType();
8968   const Type *DestTy = CI.getType();
8969
8970   if (isa<PointerType>(SrcTy)) {
8971     if (Instruction *I = commonPointerCastTransforms(CI))
8972       return I;
8973   } else {
8974     if (Instruction *Result = commonCastTransforms(CI))
8975       return Result;
8976   }
8977
8978
8979   // Get rid of casts from one type to the same type. These are useless and can
8980   // be replaced by the operand.
8981   if (DestTy == Src->getType())
8982     return ReplaceInstUsesWith(CI, Src);
8983
8984   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8985     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8986     const Type *DstElTy = DstPTy->getElementType();
8987     const Type *SrcElTy = SrcPTy->getElementType();
8988     
8989     // If the address spaces don't match, don't eliminate the bitcast, which is
8990     // required for changing types.
8991     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8992       return 0;
8993     
8994     // If we are casting a malloc or alloca to a pointer to a type of the same
8995     // size, rewrite the allocation instruction to allocate the "right" type.
8996     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8997       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8998         return V;
8999     
9000     // If the source and destination are pointers, and this cast is equivalent
9001     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
9002     // This can enhance SROA and other transforms that want type-safe pointers.
9003     Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
9004     unsigned NumZeros = 0;
9005     while (SrcElTy != DstElTy && 
9006            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9007            SrcElTy->getNumContainedTypes() /* not "{}" */) {
9008       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9009       ++NumZeros;
9010     }
9011
9012     // If we found a path from the src to dest, create the getelementptr now.
9013     if (SrcElTy == DstElTy) {
9014       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
9015       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
9016                                        ((Instruction*) NULL));
9017     }
9018   }
9019
9020   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9021     if (SVI->hasOneUse()) {
9022       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
9023       // a bitconvert to a vector with the same # elts.
9024       if (isa<VectorType>(DestTy) && 
9025           cast<VectorType>(DestTy)->getNumElements() ==
9026                 SVI->getType()->getNumElements() &&
9027           SVI->getType()->getNumElements() ==
9028             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9029         CastInst *Tmp;
9030         // If either of the operands is a cast from CI.getType(), then
9031         // evaluating the shuffle in the casted destination's type will allow
9032         // us to eliminate at least one cast.
9033         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
9034              Tmp->getOperand(0)->getType() == DestTy) ||
9035             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
9036              Tmp->getOperand(0)->getType() == DestTy)) {
9037           Value *LHS = InsertCastBefore(Instruction::BitCast,
9038                                         SVI->getOperand(0), DestTy, CI);
9039           Value *RHS = InsertCastBefore(Instruction::BitCast,
9040                                         SVI->getOperand(1), DestTy, CI);
9041           // Return a new shuffle vector.  Use the same element ID's, as we
9042           // know the vector types match #elts.
9043           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9044         }
9045       }
9046     }
9047   }
9048   return 0;
9049 }
9050
9051 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9052 ///   %C = or %A, %B
9053 ///   %D = select %cond, %C, %A
9054 /// into:
9055 ///   %C = select %cond, %B, 0
9056 ///   %D = or %A, %C
9057 ///
9058 /// Assuming that the specified instruction is an operand to the select, return
9059 /// a bitmask indicating which operands of this instruction are foldable if they
9060 /// equal the other incoming value of the select.
9061 ///
9062 static unsigned GetSelectFoldableOperands(Instruction *I) {
9063   switch (I->getOpcode()) {
9064   case Instruction::Add:
9065   case Instruction::Mul:
9066   case Instruction::And:
9067   case Instruction::Or:
9068   case Instruction::Xor:
9069     return 3;              // Can fold through either operand.
9070   case Instruction::Sub:   // Can only fold on the amount subtracted.
9071   case Instruction::Shl:   // Can only fold on the shift amount.
9072   case Instruction::LShr:
9073   case Instruction::AShr:
9074     return 1;
9075   default:
9076     return 0;              // Cannot fold
9077   }
9078 }
9079
9080 /// GetSelectFoldableConstant - For the same transformation as the previous
9081 /// function, return the identity constant that goes into the select.
9082 static Constant *GetSelectFoldableConstant(Instruction *I,
9083                                            LLVMContext *Context) {
9084   switch (I->getOpcode()) {
9085   default: LLVM_UNREACHABLE("This cannot happen!");
9086   case Instruction::Add:
9087   case Instruction::Sub:
9088   case Instruction::Or:
9089   case Instruction::Xor:
9090   case Instruction::Shl:
9091   case Instruction::LShr:
9092   case Instruction::AShr:
9093     return Context->getNullValue(I->getType());
9094   case Instruction::And:
9095     return Context->getAllOnesValue(I->getType());
9096   case Instruction::Mul:
9097     return Context->getConstantInt(I->getType(), 1);
9098   }
9099 }
9100
9101 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9102 /// have the same opcode and only one use each.  Try to simplify this.
9103 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9104                                           Instruction *FI) {
9105   if (TI->getNumOperands() == 1) {
9106     // If this is a non-volatile load or a cast from the same type,
9107     // merge.
9108     if (TI->isCast()) {
9109       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9110         return 0;
9111     } else {
9112       return 0;  // unknown unary op.
9113     }
9114
9115     // Fold this by inserting a select from the input values.
9116     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9117                                            FI->getOperand(0), SI.getName()+".v");
9118     InsertNewInstBefore(NewSI, SI);
9119     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9120                             TI->getType());
9121   }
9122
9123   // Only handle binary operators here.
9124   if (!isa<BinaryOperator>(TI))
9125     return 0;
9126
9127   // Figure out if the operations have any operands in common.
9128   Value *MatchOp, *OtherOpT, *OtherOpF;
9129   bool MatchIsOpZero;
9130   if (TI->getOperand(0) == FI->getOperand(0)) {
9131     MatchOp  = TI->getOperand(0);
9132     OtherOpT = TI->getOperand(1);
9133     OtherOpF = FI->getOperand(1);
9134     MatchIsOpZero = true;
9135   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9136     MatchOp  = TI->getOperand(1);
9137     OtherOpT = TI->getOperand(0);
9138     OtherOpF = FI->getOperand(0);
9139     MatchIsOpZero = false;
9140   } else if (!TI->isCommutative()) {
9141     return 0;
9142   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9143     MatchOp  = TI->getOperand(0);
9144     OtherOpT = TI->getOperand(1);
9145     OtherOpF = FI->getOperand(0);
9146     MatchIsOpZero = true;
9147   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9148     MatchOp  = TI->getOperand(1);
9149     OtherOpT = TI->getOperand(0);
9150     OtherOpF = FI->getOperand(1);
9151     MatchIsOpZero = true;
9152   } else {
9153     return 0;
9154   }
9155
9156   // If we reach here, they do have operations in common.
9157   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9158                                          OtherOpF, SI.getName()+".v");
9159   InsertNewInstBefore(NewSI, SI);
9160
9161   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9162     if (MatchIsOpZero)
9163       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9164     else
9165       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9166   }
9167   LLVM_UNREACHABLE("Shouldn't get here");
9168   return 0;
9169 }
9170
9171 static bool isSelect01(Constant *C1, Constant *C2) {
9172   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9173   if (!C1I)
9174     return false;
9175   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9176   if (!C2I)
9177     return false;
9178   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9179 }
9180
9181 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9182 /// facilitate further optimization.
9183 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9184                                             Value *FalseVal) {
9185   // See the comment above GetSelectFoldableOperands for a description of the
9186   // transformation we are doing here.
9187   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9188     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9189         !isa<Constant>(FalseVal)) {
9190       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9191         unsigned OpToFold = 0;
9192         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9193           OpToFold = 1;
9194         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9195           OpToFold = 2;
9196         }
9197
9198         if (OpToFold) {
9199           Constant *C = GetSelectFoldableConstant(TVI, Context);
9200           Value *OOp = TVI->getOperand(2-OpToFold);
9201           // Avoid creating select between 2 constants unless it's selecting
9202           // between 0 and 1.
9203           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9204             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9205             InsertNewInstBefore(NewSel, SI);
9206             NewSel->takeName(TVI);
9207             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9208               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9209             LLVM_UNREACHABLE("Unknown instruction!!");
9210           }
9211         }
9212       }
9213     }
9214   }
9215
9216   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9217     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9218         !isa<Constant>(TrueVal)) {
9219       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9220         unsigned OpToFold = 0;
9221         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9222           OpToFold = 1;
9223         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9224           OpToFold = 2;
9225         }
9226
9227         if (OpToFold) {
9228           Constant *C = GetSelectFoldableConstant(FVI, Context);
9229           Value *OOp = FVI->getOperand(2-OpToFold);
9230           // Avoid creating select between 2 constants unless it's selecting
9231           // between 0 and 1.
9232           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9233             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9234             InsertNewInstBefore(NewSel, SI);
9235             NewSel->takeName(FVI);
9236             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9237               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9238             LLVM_UNREACHABLE("Unknown instruction!!");
9239           }
9240         }
9241       }
9242     }
9243   }
9244
9245   return 0;
9246 }
9247
9248 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9249 /// ICmpInst as its first operand.
9250 ///
9251 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9252                                                    ICmpInst *ICI) {
9253   bool Changed = false;
9254   ICmpInst::Predicate Pred = ICI->getPredicate();
9255   Value *CmpLHS = ICI->getOperand(0);
9256   Value *CmpRHS = ICI->getOperand(1);
9257   Value *TrueVal = SI.getTrueValue();
9258   Value *FalseVal = SI.getFalseValue();
9259
9260   // Check cases where the comparison is with a constant that
9261   // can be adjusted to fit the min/max idiom. We may edit ICI in
9262   // place here, so make sure the select is the only user.
9263   if (ICI->hasOneUse())
9264     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9265       switch (Pred) {
9266       default: break;
9267       case ICmpInst::ICMP_ULT:
9268       case ICmpInst::ICMP_SLT: {
9269         // X < MIN ? T : F  -->  F
9270         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9271           return ReplaceInstUsesWith(SI, FalseVal);
9272         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9273         Constant *AdjustedRHS = SubOne(CI, Context);
9274         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9275             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9276           Pred = ICmpInst::getSwappedPredicate(Pred);
9277           CmpRHS = AdjustedRHS;
9278           std::swap(FalseVal, TrueVal);
9279           ICI->setPredicate(Pred);
9280           ICI->setOperand(1, CmpRHS);
9281           SI.setOperand(1, TrueVal);
9282           SI.setOperand(2, FalseVal);
9283           Changed = true;
9284         }
9285         break;
9286       }
9287       case ICmpInst::ICMP_UGT:
9288       case ICmpInst::ICMP_SGT: {
9289         // X > MAX ? T : F  -->  F
9290         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9291           return ReplaceInstUsesWith(SI, FalseVal);
9292         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9293         Constant *AdjustedRHS = AddOne(CI, Context);
9294         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9295             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9296           Pred = ICmpInst::getSwappedPredicate(Pred);
9297           CmpRHS = AdjustedRHS;
9298           std::swap(FalseVal, TrueVal);
9299           ICI->setPredicate(Pred);
9300           ICI->setOperand(1, CmpRHS);
9301           SI.setOperand(1, TrueVal);
9302           SI.setOperand(2, FalseVal);
9303           Changed = true;
9304         }
9305         break;
9306       }
9307       }
9308
9309       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9310       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9311       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9312       if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9313           match(FalseVal, m_ConstantInt<0>(), *Context))
9314         Pred = ICI->getPredicate();
9315       else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9316                match(FalseVal, m_ConstantInt<-1>(), *Context))
9317         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9318       
9319       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9320         // If we are just checking for a icmp eq of a single bit and zext'ing it
9321         // to an integer, then shift the bit to the appropriate place and then
9322         // cast to integer to avoid the comparison.
9323         const APInt &Op1CV = CI->getValue();
9324     
9325         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9326         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9327         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9328             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9329           Value *In = ICI->getOperand(0);
9330           Value *Sh = Context->getConstantInt(In->getType(),
9331                                        In->getType()->getScalarSizeInBits()-1);
9332           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9333                                                           In->getName()+".lobit"),
9334                                    *ICI);
9335           if (In->getType() != SI.getType())
9336             In = CastInst::CreateIntegerCast(In, SI.getType(),
9337                                              true/*SExt*/, "tmp", ICI);
9338     
9339           if (Pred == ICmpInst::ICMP_SGT)
9340             In = InsertNewInstBefore(BinaryOperator::CreateNot(*Context, In,
9341                                        In->getName()+".not"), *ICI);
9342     
9343           return ReplaceInstUsesWith(SI, In);
9344         }
9345       }
9346     }
9347
9348   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9349     // Transform (X == Y) ? X : Y  -> Y
9350     if (Pred == ICmpInst::ICMP_EQ)
9351       return ReplaceInstUsesWith(SI, FalseVal);
9352     // Transform (X != Y) ? X : Y  -> X
9353     if (Pred == ICmpInst::ICMP_NE)
9354       return ReplaceInstUsesWith(SI, TrueVal);
9355     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9356
9357   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9358     // Transform (X == Y) ? Y : X  -> X
9359     if (Pred == ICmpInst::ICMP_EQ)
9360       return ReplaceInstUsesWith(SI, FalseVal);
9361     // Transform (X != Y) ? Y : X  -> Y
9362     if (Pred == ICmpInst::ICMP_NE)
9363       return ReplaceInstUsesWith(SI, TrueVal);
9364     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9365   }
9366
9367   /// NOTE: if we wanted to, this is where to detect integer ABS
9368
9369   return Changed ? &SI : 0;
9370 }
9371
9372 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9373   Value *CondVal = SI.getCondition();
9374   Value *TrueVal = SI.getTrueValue();
9375   Value *FalseVal = SI.getFalseValue();
9376
9377   // select true, X, Y  -> X
9378   // select false, X, Y -> Y
9379   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9380     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9381
9382   // select C, X, X -> X
9383   if (TrueVal == FalseVal)
9384     return ReplaceInstUsesWith(SI, TrueVal);
9385
9386   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9387     return ReplaceInstUsesWith(SI, FalseVal);
9388   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9389     return ReplaceInstUsesWith(SI, TrueVal);
9390   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9391     if (isa<Constant>(TrueVal))
9392       return ReplaceInstUsesWith(SI, TrueVal);
9393     else
9394       return ReplaceInstUsesWith(SI, FalseVal);
9395   }
9396
9397   if (SI.getType() == Type::Int1Ty) {
9398     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9399       if (C->getZExtValue()) {
9400         // Change: A = select B, true, C --> A = or B, C
9401         return BinaryOperator::CreateOr(CondVal, FalseVal);
9402       } else {
9403         // Change: A = select B, false, C --> A = and !B, C
9404         Value *NotCond =
9405           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9406                                              "not."+CondVal->getName()), SI);
9407         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9408       }
9409     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9410       if (C->getZExtValue() == false) {
9411         // Change: A = select B, C, false --> A = and B, C
9412         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9413       } else {
9414         // Change: A = select B, C, true --> A = or !B, C
9415         Value *NotCond =
9416           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9417                                              "not."+CondVal->getName()), SI);
9418         return BinaryOperator::CreateOr(NotCond, TrueVal);
9419       }
9420     }
9421     
9422     // select a, b, a  -> a&b
9423     // select a, a, b  -> a|b
9424     if (CondVal == TrueVal)
9425       return BinaryOperator::CreateOr(CondVal, FalseVal);
9426     else if (CondVal == FalseVal)
9427       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9428   }
9429
9430   // Selecting between two integer constants?
9431   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9432     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9433       // select C, 1, 0 -> zext C to int
9434       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9435         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9436       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9437         // select C, 0, 1 -> zext !C to int
9438         Value *NotCond =
9439           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9440                                                "not."+CondVal->getName()), SI);
9441         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9442       }
9443
9444       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9445         // If one of the constants is zero (we know they can't both be) and we
9446         // have an icmp instruction with zero, and we have an 'and' with the
9447         // non-constant value, eliminate this whole mess.  This corresponds to
9448         // cases like this: ((X & 27) ? 27 : 0)
9449         if (TrueValC->isZero() || FalseValC->isZero())
9450           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9451               cast<Constant>(IC->getOperand(1))->isNullValue())
9452             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9453               if (ICA->getOpcode() == Instruction::And &&
9454                   isa<ConstantInt>(ICA->getOperand(1)) &&
9455                   (ICA->getOperand(1) == TrueValC ||
9456                    ICA->getOperand(1) == FalseValC) &&
9457                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9458                 // Okay, now we know that everything is set up, we just don't
9459                 // know whether we have a icmp_ne or icmp_eq and whether the 
9460                 // true or false val is the zero.
9461                 bool ShouldNotVal = !TrueValC->isZero();
9462                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9463                 Value *V = ICA;
9464                 if (ShouldNotVal)
9465                   V = InsertNewInstBefore(BinaryOperator::Create(
9466                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9467                 return ReplaceInstUsesWith(SI, V);
9468               }
9469       }
9470     }
9471
9472   // See if we are selecting two values based on a comparison of the two values.
9473   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9474     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9475       // Transform (X == Y) ? X : Y  -> Y
9476       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9477         // This is not safe in general for floating point:  
9478         // consider X== -0, Y== +0.
9479         // It becomes safe if either operand is a nonzero constant.
9480         ConstantFP *CFPt, *CFPf;
9481         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9482               !CFPt->getValueAPF().isZero()) ||
9483             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9484              !CFPf->getValueAPF().isZero()))
9485         return ReplaceInstUsesWith(SI, FalseVal);
9486       }
9487       // Transform (X != Y) ? X : Y  -> X
9488       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9489         return ReplaceInstUsesWith(SI, TrueVal);
9490       // NOTE: if we wanted to, this is where to detect MIN/MAX
9491
9492     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9493       // Transform (X == Y) ? Y : X  -> X
9494       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9495         // This is not safe in general for floating point:  
9496         // consider X== -0, Y== +0.
9497         // It becomes safe if either operand is a nonzero constant.
9498         ConstantFP *CFPt, *CFPf;
9499         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9500               !CFPt->getValueAPF().isZero()) ||
9501             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9502              !CFPf->getValueAPF().isZero()))
9503           return ReplaceInstUsesWith(SI, FalseVal);
9504       }
9505       // Transform (X != Y) ? Y : X  -> Y
9506       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9507         return ReplaceInstUsesWith(SI, TrueVal);
9508       // NOTE: if we wanted to, this is where to detect MIN/MAX
9509     }
9510     // NOTE: if we wanted to, this is where to detect ABS
9511   }
9512
9513   // See if we are selecting two values based on a comparison of the two values.
9514   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9515     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9516       return Result;
9517
9518   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9519     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9520       if (TI->hasOneUse() && FI->hasOneUse()) {
9521         Instruction *AddOp = 0, *SubOp = 0;
9522
9523         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9524         if (TI->getOpcode() == FI->getOpcode())
9525           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9526             return IV;
9527
9528         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9529         // even legal for FP.
9530         if ((TI->getOpcode() == Instruction::Sub &&
9531              FI->getOpcode() == Instruction::Add) ||
9532             (TI->getOpcode() == Instruction::FSub &&
9533              FI->getOpcode() == Instruction::FAdd)) {
9534           AddOp = FI; SubOp = TI;
9535         } else if ((FI->getOpcode() == Instruction::Sub &&
9536                     TI->getOpcode() == Instruction::Add) ||
9537                    (FI->getOpcode() == Instruction::FSub &&
9538                     TI->getOpcode() == Instruction::FAdd)) {
9539           AddOp = TI; SubOp = FI;
9540         }
9541
9542         if (AddOp) {
9543           Value *OtherAddOp = 0;
9544           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9545             OtherAddOp = AddOp->getOperand(1);
9546           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9547             OtherAddOp = AddOp->getOperand(0);
9548           }
9549
9550           if (OtherAddOp) {
9551             // So at this point we know we have (Y -> OtherAddOp):
9552             //        select C, (add X, Y), (sub X, Z)
9553             Value *NegVal;  // Compute -Z
9554             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9555               NegVal = Context->getConstantExprNeg(C);
9556             } else {
9557               NegVal = InsertNewInstBefore(
9558                     BinaryOperator::CreateNeg(*Context, SubOp->getOperand(1),
9559                                               "tmp"), SI);
9560             }
9561
9562             Value *NewTrueOp = OtherAddOp;
9563             Value *NewFalseOp = NegVal;
9564             if (AddOp != TI)
9565               std::swap(NewTrueOp, NewFalseOp);
9566             Instruction *NewSel =
9567               SelectInst::Create(CondVal, NewTrueOp,
9568                                  NewFalseOp, SI.getName() + ".p");
9569
9570             NewSel = InsertNewInstBefore(NewSel, SI);
9571             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9572           }
9573         }
9574       }
9575
9576   // See if we can fold the select into one of our operands.
9577   if (SI.getType()->isInteger()) {
9578     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9579     if (FoldI)
9580       return FoldI;
9581   }
9582
9583   if (BinaryOperator::isNot(CondVal)) {
9584     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9585     SI.setOperand(1, FalseVal);
9586     SI.setOperand(2, TrueVal);
9587     return &SI;
9588   }
9589
9590   return 0;
9591 }
9592
9593 /// EnforceKnownAlignment - If the specified pointer points to an object that
9594 /// we control, modify the object's alignment to PrefAlign. This isn't
9595 /// often possible though. If alignment is important, a more reliable approach
9596 /// is to simply align all global variables and allocation instructions to
9597 /// their preferred alignment from the beginning.
9598 ///
9599 static unsigned EnforceKnownAlignment(Value *V,
9600                                       unsigned Align, unsigned PrefAlign) {
9601
9602   User *U = dyn_cast<User>(V);
9603   if (!U) return Align;
9604
9605   switch (getOpcode(U)) {
9606   default: break;
9607   case Instruction::BitCast:
9608     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9609   case Instruction::GetElementPtr: {
9610     // If all indexes are zero, it is just the alignment of the base pointer.
9611     bool AllZeroOperands = true;
9612     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9613       if (!isa<Constant>(*i) ||
9614           !cast<Constant>(*i)->isNullValue()) {
9615         AllZeroOperands = false;
9616         break;
9617       }
9618
9619     if (AllZeroOperands) {
9620       // Treat this like a bitcast.
9621       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9622     }
9623     break;
9624   }
9625   }
9626
9627   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9628     // If there is a large requested alignment and we can, bump up the alignment
9629     // of the global.
9630     if (!GV->isDeclaration()) {
9631       if (GV->getAlignment() >= PrefAlign)
9632         Align = GV->getAlignment();
9633       else {
9634         GV->setAlignment(PrefAlign);
9635         Align = PrefAlign;
9636       }
9637     }
9638   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9639     // If there is a requested alignment and if this is an alloca, round up.  We
9640     // don't do this for malloc, because some systems can't respect the request.
9641     if (isa<AllocaInst>(AI)) {
9642       if (AI->getAlignment() >= PrefAlign)
9643         Align = AI->getAlignment();
9644       else {
9645         AI->setAlignment(PrefAlign);
9646         Align = PrefAlign;
9647       }
9648     }
9649   }
9650
9651   return Align;
9652 }
9653
9654 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9655 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9656 /// and it is more than the alignment of the ultimate object, see if we can
9657 /// increase the alignment of the ultimate object, making this check succeed.
9658 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9659                                                   unsigned PrefAlign) {
9660   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9661                       sizeof(PrefAlign) * CHAR_BIT;
9662   APInt Mask = APInt::getAllOnesValue(BitWidth);
9663   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9664   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9665   unsigned TrailZ = KnownZero.countTrailingOnes();
9666   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9667
9668   if (PrefAlign > Align)
9669     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9670   
9671     // We don't need to make any adjustment.
9672   return Align;
9673 }
9674
9675 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9676   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9677   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9678   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9679   unsigned CopyAlign = MI->getAlignment();
9680
9681   if (CopyAlign < MinAlign) {
9682     MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(), 
9683                                              MinAlign, false));
9684     return MI;
9685   }
9686   
9687   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9688   // load/store.
9689   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9690   if (MemOpLength == 0) return 0;
9691   
9692   // Source and destination pointer types are always "i8*" for intrinsic.  See
9693   // if the size is something we can handle with a single primitive load/store.
9694   // A single load+store correctly handles overlapping memory in the memmove
9695   // case.
9696   unsigned Size = MemOpLength->getZExtValue();
9697   if (Size == 0) return MI;  // Delete this mem transfer.
9698   
9699   if (Size > 8 || (Size&(Size-1)))
9700     return 0;  // If not 1/2/4/8 bytes, exit.
9701   
9702   // Use an integer load+store unless we can find something better.
9703   Type *NewPtrTy =
9704                 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
9705   
9706   // Memcpy forces the use of i8* for the source and destination.  That means
9707   // that if you're using memcpy to move one double around, you'll get a cast
9708   // from double* to i8*.  We'd much rather use a double load+store rather than
9709   // an i64 load+store, here because this improves the odds that the source or
9710   // dest address will be promotable.  See if we can find a better type than the
9711   // integer datatype.
9712   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9713     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9714     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9715       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9716       // down through these levels if so.
9717       while (!SrcETy->isSingleValueType()) {
9718         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9719           if (STy->getNumElements() == 1)
9720             SrcETy = STy->getElementType(0);
9721           else
9722             break;
9723         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9724           if (ATy->getNumElements() == 1)
9725             SrcETy = ATy->getElementType();
9726           else
9727             break;
9728         } else
9729           break;
9730       }
9731       
9732       if (SrcETy->isSingleValueType())
9733         NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
9734     }
9735   }
9736   
9737   
9738   // If the memcpy/memmove provides better alignment info than we can
9739   // infer, use it.
9740   SrcAlign = std::max(SrcAlign, CopyAlign);
9741   DstAlign = std::max(DstAlign, CopyAlign);
9742   
9743   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9744   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9745   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9746   InsertNewInstBefore(L, *MI);
9747   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9748
9749   // Set the size of the copy to 0, it will be deleted on the next iteration.
9750   MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
9751   return MI;
9752 }
9753
9754 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9755   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9756   if (MI->getAlignment() < Alignment) {
9757     MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9758                                              Alignment, false));
9759     return MI;
9760   }
9761   
9762   // Extract the length and alignment and fill if they are constant.
9763   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9764   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9765   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9766     return 0;
9767   uint64_t Len = LenC->getZExtValue();
9768   Alignment = MI->getAlignment();
9769   
9770   // If the length is zero, this is a no-op
9771   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9772   
9773   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9774   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9775     const Type *ITy = Context->getIntegerType(Len*8);  // n=1 -> i8.
9776     
9777     Value *Dest = MI->getDest();
9778     Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
9779
9780     // Alignment 0 is identity for alignment 1 for memset, but not store.
9781     if (Alignment == 0) Alignment = 1;
9782     
9783     // Extract the fill value and store.
9784     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9785     InsertNewInstBefore(new StoreInst(Context->getConstantInt(ITy, Fill),
9786                                       Dest, false, Alignment), *MI);
9787     
9788     // Set the size of the copy to 0, it will be deleted on the next iteration.
9789     MI->setLength(Context->getNullValue(LenC->getType()));
9790     return MI;
9791   }
9792
9793   return 0;
9794 }
9795
9796
9797 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9798 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9799 /// the heavy lifting.
9800 ///
9801 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9802   // If the caller function is nounwind, mark the call as nounwind, even if the
9803   // callee isn't.
9804   if (CI.getParent()->getParent()->doesNotThrow() &&
9805       !CI.doesNotThrow()) {
9806     CI.setDoesNotThrow();
9807     return &CI;
9808   }
9809   
9810   
9811   
9812   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9813   if (!II) return visitCallSite(&CI);
9814   
9815   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9816   // visitCallSite.
9817   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9818     bool Changed = false;
9819
9820     // memmove/cpy/set of zero bytes is a noop.
9821     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9822       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9823
9824       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9825         if (CI->getZExtValue() == 1) {
9826           // Replace the instruction with just byte operations.  We would
9827           // transform other cases to loads/stores, but we don't know if
9828           // alignment is sufficient.
9829         }
9830     }
9831
9832     // If we have a memmove and the source operation is a constant global,
9833     // then the source and dest pointers can't alias, so we can change this
9834     // into a call to memcpy.
9835     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9836       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9837         if (GVSrc->isConstant()) {
9838           Module *M = CI.getParent()->getParent()->getParent();
9839           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9840           const Type *Tys[1];
9841           Tys[0] = CI.getOperand(3)->getType();
9842           CI.setOperand(0, 
9843                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9844           Changed = true;
9845         }
9846
9847       // memmove(x,x,size) -> noop.
9848       if (MMI->getSource() == MMI->getDest())
9849         return EraseInstFromFunction(CI);
9850     }
9851
9852     // If we can determine a pointer alignment that is bigger than currently
9853     // set, update the alignment.
9854     if (isa<MemTransferInst>(MI)) {
9855       if (Instruction *I = SimplifyMemTransfer(MI))
9856         return I;
9857     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9858       if (Instruction *I = SimplifyMemSet(MSI))
9859         return I;
9860     }
9861           
9862     if (Changed) return II;
9863   }
9864   
9865   switch (II->getIntrinsicID()) {
9866   default: break;
9867   case Intrinsic::bswap:
9868     // bswap(bswap(x)) -> x
9869     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9870       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9871         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9872     break;
9873   case Intrinsic::ppc_altivec_lvx:
9874   case Intrinsic::ppc_altivec_lvxl:
9875   case Intrinsic::x86_sse_loadu_ps:
9876   case Intrinsic::x86_sse2_loadu_pd:
9877   case Intrinsic::x86_sse2_loadu_dq:
9878     // Turn PPC lvx     -> load if the pointer is known aligned.
9879     // Turn X86 loadups -> load if the pointer is known aligned.
9880     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9881       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9882                                    Context->getPointerTypeUnqual(II->getType()),
9883                                        CI);
9884       return new LoadInst(Ptr);
9885     }
9886     break;
9887   case Intrinsic::ppc_altivec_stvx:
9888   case Intrinsic::ppc_altivec_stvxl:
9889     // Turn stvx -> store if the pointer is known aligned.
9890     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9891       const Type *OpPtrTy = 
9892         Context->getPointerTypeUnqual(II->getOperand(1)->getType());
9893       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9894       return new StoreInst(II->getOperand(1), Ptr);
9895     }
9896     break;
9897   case Intrinsic::x86_sse_storeu_ps:
9898   case Intrinsic::x86_sse2_storeu_pd:
9899   case Intrinsic::x86_sse2_storeu_dq:
9900     // Turn X86 storeu -> store if the pointer is known aligned.
9901     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9902       const Type *OpPtrTy = 
9903         Context->getPointerTypeUnqual(II->getOperand(2)->getType());
9904       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9905       return new StoreInst(II->getOperand(2), Ptr);
9906     }
9907     break;
9908     
9909   case Intrinsic::x86_sse_cvttss2si: {
9910     // These intrinsics only demands the 0th element of its input vector.  If
9911     // we can simplify the input based on that, do so now.
9912     unsigned VWidth =
9913       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9914     APInt DemandedElts(VWidth, 1);
9915     APInt UndefElts(VWidth, 0);
9916     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9917                                               UndefElts)) {
9918       II->setOperand(1, V);
9919       return II;
9920     }
9921     break;
9922   }
9923     
9924   case Intrinsic::ppc_altivec_vperm:
9925     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9926     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9927       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9928       
9929       // Check that all of the elements are integer constants or undefs.
9930       bool AllEltsOk = true;
9931       for (unsigned i = 0; i != 16; ++i) {
9932         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9933             !isa<UndefValue>(Mask->getOperand(i))) {
9934           AllEltsOk = false;
9935           break;
9936         }
9937       }
9938       
9939       if (AllEltsOk) {
9940         // Cast the input vectors to byte vectors.
9941         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9942         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9943         Value *Result = Context->getUndef(Op0->getType());
9944         
9945         // Only extract each element once.
9946         Value *ExtractedElts[32];
9947         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9948         
9949         for (unsigned i = 0; i != 16; ++i) {
9950           if (isa<UndefValue>(Mask->getOperand(i)))
9951             continue;
9952           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9953           Idx &= 31;  // Match the hardware behavior.
9954           
9955           if (ExtractedElts[Idx] == 0) {
9956             Instruction *Elt = 
9957               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9958             InsertNewInstBefore(Elt, CI);
9959             ExtractedElts[Idx] = Elt;
9960           }
9961         
9962           // Insert this value into the result vector.
9963           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9964                                              i, "tmp");
9965           InsertNewInstBefore(cast<Instruction>(Result), CI);
9966         }
9967         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9968       }
9969     }
9970     break;
9971
9972   case Intrinsic::stackrestore: {
9973     // If the save is right next to the restore, remove the restore.  This can
9974     // happen when variable allocas are DCE'd.
9975     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9976       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9977         BasicBlock::iterator BI = SS;
9978         if (&*++BI == II)
9979           return EraseInstFromFunction(CI);
9980       }
9981     }
9982     
9983     // Scan down this block to see if there is another stack restore in the
9984     // same block without an intervening call/alloca.
9985     BasicBlock::iterator BI = II;
9986     TerminatorInst *TI = II->getParent()->getTerminator();
9987     bool CannotRemove = false;
9988     for (++BI; &*BI != TI; ++BI) {
9989       if (isa<AllocaInst>(BI)) {
9990         CannotRemove = true;
9991         break;
9992       }
9993       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9994         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9995           // If there is a stackrestore below this one, remove this one.
9996           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9997             return EraseInstFromFunction(CI);
9998           // Otherwise, ignore the intrinsic.
9999         } else {
10000           // If we found a non-intrinsic call, we can't remove the stack
10001           // restore.
10002           CannotRemove = true;
10003           break;
10004         }
10005       }
10006     }
10007     
10008     // If the stack restore is in a return/unwind block and if there are no
10009     // allocas or calls between the restore and the return, nuke the restore.
10010     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10011       return EraseInstFromFunction(CI);
10012     break;
10013   }
10014   }
10015
10016   return visitCallSite(II);
10017 }
10018
10019 // InvokeInst simplification
10020 //
10021 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10022   return visitCallSite(&II);
10023 }
10024
10025 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
10026 /// passed through the varargs area, we can eliminate the use of the cast.
10027 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10028                                          const CastInst * const CI,
10029                                          const TargetData * const TD,
10030                                          const int ix) {
10031   if (!CI->isLosslessCast())
10032     return false;
10033
10034   // The size of ByVal arguments is derived from the type, so we
10035   // can't change to a type with a different size.  If the size were
10036   // passed explicitly we could avoid this check.
10037   if (!CS.paramHasAttr(ix, Attribute::ByVal))
10038     return true;
10039
10040   const Type* SrcTy = 
10041             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10042   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10043   if (!SrcTy->isSized() || !DstTy->isSized())
10044     return false;
10045   if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10046     return false;
10047   return true;
10048 }
10049
10050 // visitCallSite - Improvements for call and invoke instructions.
10051 //
10052 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10053   bool Changed = false;
10054
10055   // If the callee is a constexpr cast of a function, attempt to move the cast
10056   // to the arguments of the call/invoke.
10057   if (transformConstExprCastCall(CS)) return 0;
10058
10059   Value *Callee = CS.getCalledValue();
10060
10061   if (Function *CalleeF = dyn_cast<Function>(Callee))
10062     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10063       Instruction *OldCall = CS.getInstruction();
10064       // If the call and callee calling conventions don't match, this call must
10065       // be unreachable, as the call is undefined.
10066       new StoreInst(Context->getConstantIntTrue(),
10067                 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), 
10068                                   OldCall);
10069       if (!OldCall->use_empty())
10070         OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
10071       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10072         return EraseInstFromFunction(*OldCall);
10073       return 0;
10074     }
10075
10076   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10077     // This instruction is not reachable, just remove it.  We insert a store to
10078     // undef so that we know that this code is not reachable, despite the fact
10079     // that we can't modify the CFG here.
10080     new StoreInst(Context->getConstantIntTrue(),
10081                Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10082                   CS.getInstruction());
10083
10084     if (!CS.getInstruction()->use_empty())
10085       CS.getInstruction()->
10086         replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
10087
10088     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10089       // Don't break the CFG, insert a dummy cond branch.
10090       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10091                          Context->getConstantIntTrue(), II);
10092     }
10093     return EraseInstFromFunction(*CS.getInstruction());
10094   }
10095
10096   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10097     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10098       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10099         return transformCallThroughTrampoline(CS);
10100
10101   const PointerType *PTy = cast<PointerType>(Callee->getType());
10102   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10103   if (FTy->isVarArg()) {
10104     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10105     // See if we can optimize any arguments passed through the varargs area of
10106     // the call.
10107     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10108            E = CS.arg_end(); I != E; ++I, ++ix) {
10109       CastInst *CI = dyn_cast<CastInst>(*I);
10110       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10111         *I = CI->getOperand(0);
10112         Changed = true;
10113       }
10114     }
10115   }
10116
10117   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10118     // Inline asm calls cannot throw - mark them 'nounwind'.
10119     CS.setDoesNotThrow();
10120     Changed = true;
10121   }
10122
10123   return Changed ? CS.getInstruction() : 0;
10124 }
10125
10126 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10127 // attempt to move the cast to the arguments of the call/invoke.
10128 //
10129 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10130   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10131   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10132   if (CE->getOpcode() != Instruction::BitCast || 
10133       !isa<Function>(CE->getOperand(0)))
10134     return false;
10135   Function *Callee = cast<Function>(CE->getOperand(0));
10136   Instruction *Caller = CS.getInstruction();
10137   const AttrListPtr &CallerPAL = CS.getAttributes();
10138
10139   // Okay, this is a cast from a function to a different type.  Unless doing so
10140   // would cause a type conversion of one of our arguments, change this call to
10141   // be a direct call with arguments casted to the appropriate types.
10142   //
10143   const FunctionType *FT = Callee->getFunctionType();
10144   const Type *OldRetTy = Caller->getType();
10145   const Type *NewRetTy = FT->getReturnType();
10146
10147   if (isa<StructType>(NewRetTy))
10148     return false; // TODO: Handle multiple return values.
10149
10150   // Check to see if we are changing the return type...
10151   if (OldRetTy != NewRetTy) {
10152     if (Callee->isDeclaration() &&
10153         // Conversion is ok if changing from one pointer type to another or from
10154         // a pointer to an integer of the same size.
10155         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
10156           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
10157       return false;   // Cannot transform this return value.
10158
10159     if (!Caller->use_empty() &&
10160         // void -> non-void is handled specially
10161         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
10162       return false;   // Cannot transform this return value.
10163
10164     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10165       Attributes RAttrs = CallerPAL.getRetAttributes();
10166       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10167         return false;   // Attribute not compatible with transformed value.
10168     }
10169
10170     // If the callsite is an invoke instruction, and the return value is used by
10171     // a PHI node in a successor, we cannot change the return type of the call
10172     // because there is no place to put the cast instruction (without breaking
10173     // the critical edge).  Bail out in this case.
10174     if (!Caller->use_empty())
10175       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10176         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10177              UI != E; ++UI)
10178           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10179             if (PN->getParent() == II->getNormalDest() ||
10180                 PN->getParent() == II->getUnwindDest())
10181               return false;
10182   }
10183
10184   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10185   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10186
10187   CallSite::arg_iterator AI = CS.arg_begin();
10188   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10189     const Type *ParamTy = FT->getParamType(i);
10190     const Type *ActTy = (*AI)->getType();
10191
10192     if (!CastInst::isCastable(ActTy, ParamTy))
10193       return false;   // Cannot transform this parameter value.
10194
10195     if (CallerPAL.getParamAttributes(i + 1) 
10196         & Attribute::typeIncompatible(ParamTy))
10197       return false;   // Attribute not compatible with transformed value.
10198
10199     // Converting from one pointer type to another or between a pointer and an
10200     // integer of the same size is safe even if we do not have a body.
10201     bool isConvertible = ActTy == ParamTy ||
10202       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10203        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
10204     if (Callee->isDeclaration() && !isConvertible) return false;
10205   }
10206
10207   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10208       Callee->isDeclaration())
10209     return false;   // Do not delete arguments unless we have a function body.
10210
10211   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10212       !CallerPAL.isEmpty())
10213     // In this case we have more arguments than the new function type, but we
10214     // won't be dropping them.  Check that these extra arguments have attributes
10215     // that are compatible with being a vararg call argument.
10216     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10217       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10218         break;
10219       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10220       if (PAttrs & Attribute::VarArgsIncompatible)
10221         return false;
10222     }
10223
10224   // Okay, we decided that this is a safe thing to do: go ahead and start
10225   // inserting cast instructions as necessary...
10226   std::vector<Value*> Args;
10227   Args.reserve(NumActualArgs);
10228   SmallVector<AttributeWithIndex, 8> attrVec;
10229   attrVec.reserve(NumCommonArgs);
10230
10231   // Get any return attributes.
10232   Attributes RAttrs = CallerPAL.getRetAttributes();
10233
10234   // If the return value is not being used, the type may not be compatible
10235   // with the existing attributes.  Wipe out any problematic attributes.
10236   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10237
10238   // Add the new return attributes.
10239   if (RAttrs)
10240     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10241
10242   AI = CS.arg_begin();
10243   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10244     const Type *ParamTy = FT->getParamType(i);
10245     if ((*AI)->getType() == ParamTy) {
10246       Args.push_back(*AI);
10247     } else {
10248       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10249           false, ParamTy, false);
10250       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10251       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10252     }
10253
10254     // Add any parameter attributes.
10255     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10256       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10257   }
10258
10259   // If the function takes more arguments than the call was taking, add them
10260   // now...
10261   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10262     Args.push_back(Context->getNullValue(FT->getParamType(i)));
10263
10264   // If we are removing arguments to the function, emit an obnoxious warning...
10265   if (FT->getNumParams() < NumActualArgs) {
10266     if (!FT->isVarArg()) {
10267       cerr << "WARNING: While resolving call to function '"
10268            << Callee->getName() << "' arguments were dropped!\n";
10269     } else {
10270       // Add all of the arguments in their promoted form to the arg list...
10271       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10272         const Type *PTy = getPromotedType((*AI)->getType());
10273         if (PTy != (*AI)->getType()) {
10274           // Must promote to pass through va_arg area!
10275           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
10276                                                                 PTy, false);
10277           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10278           InsertNewInstBefore(Cast, *Caller);
10279           Args.push_back(Cast);
10280         } else {
10281           Args.push_back(*AI);
10282         }
10283
10284         // Add any parameter attributes.
10285         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10286           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10287       }
10288     }
10289   }
10290
10291   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10292     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10293
10294   if (NewRetTy == Type::VoidTy)
10295     Caller->setName("");   // Void type should not have a name.
10296
10297   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
10298
10299   Instruction *NC;
10300   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10301     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10302                             Args.begin(), Args.end(),
10303                             Caller->getName(), Caller);
10304     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10305     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10306   } else {
10307     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10308                           Caller->getName(), Caller);
10309     CallInst *CI = cast<CallInst>(Caller);
10310     if (CI->isTailCall())
10311       cast<CallInst>(NC)->setTailCall();
10312     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10313     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10314   }
10315
10316   // Insert a cast of the return type as necessary.
10317   Value *NV = NC;
10318   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10319     if (NV->getType() != Type::VoidTy) {
10320       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10321                                                             OldRetTy, false);
10322       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10323
10324       // If this is an invoke instruction, we should insert it after the first
10325       // non-phi, instruction in the normal successor block.
10326       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10327         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10328         InsertNewInstBefore(NC, *I);
10329       } else {
10330         // Otherwise, it's a call, just insert cast right after the call instr
10331         InsertNewInstBefore(NC, *Caller);
10332       }
10333       AddUsersToWorkList(*Caller);
10334     } else {
10335       NV = Context->getUndef(Caller->getType());
10336     }
10337   }
10338
10339   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10340     Caller->replaceAllUsesWith(NV);
10341   Caller->eraseFromParent();
10342   RemoveFromWorkList(Caller);
10343   return true;
10344 }
10345
10346 // transformCallThroughTrampoline - Turn a call to a function created by the
10347 // init_trampoline intrinsic into a direct call to the underlying function.
10348 //
10349 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10350   Value *Callee = CS.getCalledValue();
10351   const PointerType *PTy = cast<PointerType>(Callee->getType());
10352   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10353   const AttrListPtr &Attrs = CS.getAttributes();
10354
10355   // If the call already has the 'nest' attribute somewhere then give up -
10356   // otherwise 'nest' would occur twice after splicing in the chain.
10357   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10358     return 0;
10359
10360   IntrinsicInst *Tramp =
10361     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10362
10363   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10364   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10365   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10366
10367   const AttrListPtr &NestAttrs = NestF->getAttributes();
10368   if (!NestAttrs.isEmpty()) {
10369     unsigned NestIdx = 1;
10370     const Type *NestTy = 0;
10371     Attributes NestAttr = Attribute::None;
10372
10373     // Look for a parameter marked with the 'nest' attribute.
10374     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10375          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10376       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10377         // Record the parameter type and any other attributes.
10378         NestTy = *I;
10379         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10380         break;
10381       }
10382
10383     if (NestTy) {
10384       Instruction *Caller = CS.getInstruction();
10385       std::vector<Value*> NewArgs;
10386       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10387
10388       SmallVector<AttributeWithIndex, 8> NewAttrs;
10389       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10390
10391       // Insert the nest argument into the call argument list, which may
10392       // mean appending it.  Likewise for attributes.
10393
10394       // Add any result attributes.
10395       if (Attributes Attr = Attrs.getRetAttributes())
10396         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10397
10398       {
10399         unsigned Idx = 1;
10400         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10401         do {
10402           if (Idx == NestIdx) {
10403             // Add the chain argument and attributes.
10404             Value *NestVal = Tramp->getOperand(3);
10405             if (NestVal->getType() != NestTy)
10406               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10407             NewArgs.push_back(NestVal);
10408             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10409           }
10410
10411           if (I == E)
10412             break;
10413
10414           // Add the original argument and attributes.
10415           NewArgs.push_back(*I);
10416           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10417             NewAttrs.push_back
10418               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10419
10420           ++Idx, ++I;
10421         } while (1);
10422       }
10423
10424       // Add any function attributes.
10425       if (Attributes Attr = Attrs.getFnAttributes())
10426         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10427
10428       // The trampoline may have been bitcast to a bogus type (FTy).
10429       // Handle this by synthesizing a new function type, equal to FTy
10430       // with the chain parameter inserted.
10431
10432       std::vector<const Type*> NewTypes;
10433       NewTypes.reserve(FTy->getNumParams()+1);
10434
10435       // Insert the chain's type into the list of parameter types, which may
10436       // mean appending it.
10437       {
10438         unsigned Idx = 1;
10439         FunctionType::param_iterator I = FTy->param_begin(),
10440           E = FTy->param_end();
10441
10442         do {
10443           if (Idx == NestIdx)
10444             // Add the chain's type.
10445             NewTypes.push_back(NestTy);
10446
10447           if (I == E)
10448             break;
10449
10450           // Add the original type.
10451           NewTypes.push_back(*I);
10452
10453           ++Idx, ++I;
10454         } while (1);
10455       }
10456
10457       // Replace the trampoline call with a direct call.  Let the generic
10458       // code sort out any function type mismatches.
10459       FunctionType *NewFTy =
10460                        Context->getFunctionType(FTy->getReturnType(), NewTypes, 
10461                                                 FTy->isVarArg());
10462       Constant *NewCallee =
10463         NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10464         NestF : Context->getConstantExprBitCast(NestF, 
10465                                          Context->getPointerTypeUnqual(NewFTy));
10466       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
10467
10468       Instruction *NewCaller;
10469       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10470         NewCaller = InvokeInst::Create(NewCallee,
10471                                        II->getNormalDest(), II->getUnwindDest(),
10472                                        NewArgs.begin(), NewArgs.end(),
10473                                        Caller->getName(), Caller);
10474         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10475         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10476       } else {
10477         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10478                                      Caller->getName(), Caller);
10479         if (cast<CallInst>(Caller)->isTailCall())
10480           cast<CallInst>(NewCaller)->setTailCall();
10481         cast<CallInst>(NewCaller)->
10482           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10483         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10484       }
10485       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10486         Caller->replaceAllUsesWith(NewCaller);
10487       Caller->eraseFromParent();
10488       RemoveFromWorkList(Caller);
10489       return 0;
10490     }
10491   }
10492
10493   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10494   // parameter, there is no need to adjust the argument list.  Let the generic
10495   // code sort out any function type mismatches.
10496   Constant *NewCallee =
10497     NestF->getType() == PTy ? NestF : 
10498                               Context->getConstantExprBitCast(NestF, PTy);
10499   CS.setCalledFunction(NewCallee);
10500   return CS.getInstruction();
10501 }
10502
10503 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10504 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10505 /// and a single binop.
10506 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10507   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10508   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10509   unsigned Opc = FirstInst->getOpcode();
10510   Value *LHSVal = FirstInst->getOperand(0);
10511   Value *RHSVal = FirstInst->getOperand(1);
10512     
10513   const Type *LHSType = LHSVal->getType();
10514   const Type *RHSType = RHSVal->getType();
10515   
10516   // Scan to see if all operands are the same opcode, all have one use, and all
10517   // kill their operands (i.e. the operands have one use).
10518   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10519     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10520     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10521         // Verify type of the LHS matches so we don't fold cmp's of different
10522         // types or GEP's with different index types.
10523         I->getOperand(0)->getType() != LHSType ||
10524         I->getOperand(1)->getType() != RHSType)
10525       return 0;
10526
10527     // If they are CmpInst instructions, check their predicates
10528     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10529       if (cast<CmpInst>(I)->getPredicate() !=
10530           cast<CmpInst>(FirstInst)->getPredicate())
10531         return 0;
10532     
10533     // Keep track of which operand needs a phi node.
10534     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10535     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10536   }
10537   
10538   // Otherwise, this is safe to transform!
10539   
10540   Value *InLHS = FirstInst->getOperand(0);
10541   Value *InRHS = FirstInst->getOperand(1);
10542   PHINode *NewLHS = 0, *NewRHS = 0;
10543   if (LHSVal == 0) {
10544     NewLHS = PHINode::Create(LHSType,
10545                              FirstInst->getOperand(0)->getName() + ".pn");
10546     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10547     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10548     InsertNewInstBefore(NewLHS, PN);
10549     LHSVal = NewLHS;
10550   }
10551   
10552   if (RHSVal == 0) {
10553     NewRHS = PHINode::Create(RHSType,
10554                              FirstInst->getOperand(1)->getName() + ".pn");
10555     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10556     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10557     InsertNewInstBefore(NewRHS, PN);
10558     RHSVal = NewRHS;
10559   }
10560   
10561   // Add all operands to the new PHIs.
10562   if (NewLHS || NewRHS) {
10563     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10564       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10565       if (NewLHS) {
10566         Value *NewInLHS = InInst->getOperand(0);
10567         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10568       }
10569       if (NewRHS) {
10570         Value *NewInRHS = InInst->getOperand(1);
10571         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10572       }
10573     }
10574   }
10575     
10576   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10577     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10578   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10579   return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10580                          LHSVal, RHSVal);
10581 }
10582
10583 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10584   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10585   
10586   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10587                                         FirstInst->op_end());
10588   // This is true if all GEP bases are allocas and if all indices into them are
10589   // constants.
10590   bool AllBasePointersAreAllocas = true;
10591   
10592   // Scan to see if all operands are the same opcode, all have one use, and all
10593   // kill their operands (i.e. the operands have one use).
10594   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10595     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10596     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10597       GEP->getNumOperands() != FirstInst->getNumOperands())
10598       return 0;
10599
10600     // Keep track of whether or not all GEPs are of alloca pointers.
10601     if (AllBasePointersAreAllocas &&
10602         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10603          !GEP->hasAllConstantIndices()))
10604       AllBasePointersAreAllocas = false;
10605     
10606     // Compare the operand lists.
10607     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10608       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10609         continue;
10610       
10611       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10612       // if one of the PHIs has a constant for the index.  The index may be
10613       // substantially cheaper to compute for the constants, so making it a
10614       // variable index could pessimize the path.  This also handles the case
10615       // for struct indices, which must always be constant.
10616       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10617           isa<ConstantInt>(GEP->getOperand(op)))
10618         return 0;
10619       
10620       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10621         return 0;
10622       FixedOperands[op] = 0;  // Needs a PHI.
10623     }
10624   }
10625   
10626   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10627   // bother doing this transformation.  At best, this will just save a bit of
10628   // offset calculation, but all the predecessors will have to materialize the
10629   // stack address into a register anyway.  We'd actually rather *clone* the
10630   // load up into the predecessors so that we have a load of a gep of an alloca,
10631   // which can usually all be folded into the load.
10632   if (AllBasePointersAreAllocas)
10633     return 0;
10634   
10635   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10636   // that is variable.
10637   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10638   
10639   bool HasAnyPHIs = false;
10640   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10641     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10642     Value *FirstOp = FirstInst->getOperand(i);
10643     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10644                                      FirstOp->getName()+".pn");
10645     InsertNewInstBefore(NewPN, PN);
10646     
10647     NewPN->reserveOperandSpace(e);
10648     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10649     OperandPhis[i] = NewPN;
10650     FixedOperands[i] = NewPN;
10651     HasAnyPHIs = true;
10652   }
10653
10654   
10655   // Add all operands to the new PHIs.
10656   if (HasAnyPHIs) {
10657     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10658       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10659       BasicBlock *InBB = PN.getIncomingBlock(i);
10660       
10661       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10662         if (PHINode *OpPhi = OperandPhis[op])
10663           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10664     }
10665   }
10666   
10667   Value *Base = FixedOperands[0];
10668   return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10669                                    FixedOperands.end());
10670 }
10671
10672
10673 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10674 /// sink the load out of the block that defines it.  This means that it must be
10675 /// obvious the value of the load is not changed from the point of the load to
10676 /// the end of the block it is in.
10677 ///
10678 /// Finally, it is safe, but not profitable, to sink a load targetting a
10679 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10680 /// to a register.
10681 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10682   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10683   
10684   for (++BBI; BBI != E; ++BBI)
10685     if (BBI->mayWriteToMemory())
10686       return false;
10687   
10688   // Check for non-address taken alloca.  If not address-taken already, it isn't
10689   // profitable to do this xform.
10690   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10691     bool isAddressTaken = false;
10692     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10693          UI != E; ++UI) {
10694       if (isa<LoadInst>(UI)) continue;
10695       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10696         // If storing TO the alloca, then the address isn't taken.
10697         if (SI->getOperand(1) == AI) continue;
10698       }
10699       isAddressTaken = true;
10700       break;
10701     }
10702     
10703     if (!isAddressTaken && AI->isStaticAlloca())
10704       return false;
10705   }
10706   
10707   // If this load is a load from a GEP with a constant offset from an alloca,
10708   // then we don't want to sink it.  In its present form, it will be
10709   // load [constant stack offset].  Sinking it will cause us to have to
10710   // materialize the stack addresses in each predecessor in a register only to
10711   // do a shared load from register in the successor.
10712   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10713     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10714       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10715         return false;
10716   
10717   return true;
10718 }
10719
10720
10721 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10722 // operator and they all are only used by the PHI, PHI together their
10723 // inputs, and do the operation once, to the result of the PHI.
10724 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10725   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10726
10727   // Scan the instruction, looking for input operations that can be folded away.
10728   // If all input operands to the phi are the same instruction (e.g. a cast from
10729   // the same type or "+42") we can pull the operation through the PHI, reducing
10730   // code size and simplifying code.
10731   Constant *ConstantOp = 0;
10732   const Type *CastSrcTy = 0;
10733   bool isVolatile = false;
10734   if (isa<CastInst>(FirstInst)) {
10735     CastSrcTy = FirstInst->getOperand(0)->getType();
10736   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10737     // Can fold binop, compare or shift here if the RHS is a constant, 
10738     // otherwise call FoldPHIArgBinOpIntoPHI.
10739     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10740     if (ConstantOp == 0)
10741       return FoldPHIArgBinOpIntoPHI(PN);
10742   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10743     isVolatile = LI->isVolatile();
10744     // We can't sink the load if the loaded value could be modified between the
10745     // load and the PHI.
10746     if (LI->getParent() != PN.getIncomingBlock(0) ||
10747         !isSafeAndProfitableToSinkLoad(LI))
10748       return 0;
10749     
10750     // If the PHI is of volatile loads and the load block has multiple
10751     // successors, sinking it would remove a load of the volatile value from
10752     // the path through the other successor.
10753     if (isVolatile &&
10754         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10755       return 0;
10756     
10757   } else if (isa<GetElementPtrInst>(FirstInst)) {
10758     return FoldPHIArgGEPIntoPHI(PN);
10759   } else {
10760     return 0;  // Cannot fold this operation.
10761   }
10762
10763   // Check to see if all arguments are the same operation.
10764   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10765     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10766     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10767     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10768       return 0;
10769     if (CastSrcTy) {
10770       if (I->getOperand(0)->getType() != CastSrcTy)
10771         return 0;  // Cast operation must match.
10772     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10773       // We can't sink the load if the loaded value could be modified between 
10774       // the load and the PHI.
10775       if (LI->isVolatile() != isVolatile ||
10776           LI->getParent() != PN.getIncomingBlock(i) ||
10777           !isSafeAndProfitableToSinkLoad(LI))
10778         return 0;
10779       
10780       // If the PHI is of volatile loads and the load block has multiple
10781       // successors, sinking it would remove a load of the volatile value from
10782       // the path through the other successor.
10783       if (isVolatile &&
10784           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10785         return 0;
10786       
10787     } else if (I->getOperand(1) != ConstantOp) {
10788       return 0;
10789     }
10790   }
10791
10792   // Okay, they are all the same operation.  Create a new PHI node of the
10793   // correct type, and PHI together all of the LHS's of the instructions.
10794   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10795                                    PN.getName()+".in");
10796   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10797
10798   Value *InVal = FirstInst->getOperand(0);
10799   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10800
10801   // Add all operands to the new PHI.
10802   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10803     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10804     if (NewInVal != InVal)
10805       InVal = 0;
10806     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10807   }
10808
10809   Value *PhiVal;
10810   if (InVal) {
10811     // The new PHI unions all of the same values together.  This is really
10812     // common, so we handle it intelligently here for compile-time speed.
10813     PhiVal = InVal;
10814     delete NewPN;
10815   } else {
10816     InsertNewInstBefore(NewPN, PN);
10817     PhiVal = NewPN;
10818   }
10819
10820   // Insert and return the new operation.
10821   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10822     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10823   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10824     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10825   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10826     return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10827                            PhiVal, ConstantOp);
10828   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10829   
10830   // If this was a volatile load that we are merging, make sure to loop through
10831   // and mark all the input loads as non-volatile.  If we don't do this, we will
10832   // insert a new volatile load and the old ones will not be deletable.
10833   if (isVolatile)
10834     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10835       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10836   
10837   return new LoadInst(PhiVal, "", isVolatile);
10838 }
10839
10840 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10841 /// that is dead.
10842 static bool DeadPHICycle(PHINode *PN,
10843                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10844   if (PN->use_empty()) return true;
10845   if (!PN->hasOneUse()) return false;
10846
10847   // Remember this node, and if we find the cycle, return.
10848   if (!PotentiallyDeadPHIs.insert(PN))
10849     return true;
10850   
10851   // Don't scan crazily complex things.
10852   if (PotentiallyDeadPHIs.size() == 16)
10853     return false;
10854
10855   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10856     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10857
10858   return false;
10859 }
10860
10861 /// PHIsEqualValue - Return true if this phi node is always equal to
10862 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10863 ///   z = some value; x = phi (y, z); y = phi (x, z)
10864 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10865                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10866   // See if we already saw this PHI node.
10867   if (!ValueEqualPHIs.insert(PN))
10868     return true;
10869   
10870   // Don't scan crazily complex things.
10871   if (ValueEqualPHIs.size() == 16)
10872     return false;
10873  
10874   // Scan the operands to see if they are either phi nodes or are equal to
10875   // the value.
10876   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10877     Value *Op = PN->getIncomingValue(i);
10878     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10879       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10880         return false;
10881     } else if (Op != NonPhiInVal)
10882       return false;
10883   }
10884   
10885   return true;
10886 }
10887
10888
10889 // PHINode simplification
10890 //
10891 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10892   // If LCSSA is around, don't mess with Phi nodes
10893   if (MustPreserveLCSSA) return 0;
10894   
10895   if (Value *V = PN.hasConstantValue())
10896     return ReplaceInstUsesWith(PN, V);
10897
10898   // If all PHI operands are the same operation, pull them through the PHI,
10899   // reducing code size.
10900   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10901       isa<Instruction>(PN.getIncomingValue(1)) &&
10902       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10903       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10904       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10905       // than themselves more than once.
10906       PN.getIncomingValue(0)->hasOneUse())
10907     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10908       return Result;
10909
10910   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10911   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10912   // PHI)... break the cycle.
10913   if (PN.hasOneUse()) {
10914     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10915     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10916       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10917       PotentiallyDeadPHIs.insert(&PN);
10918       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10919         return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10920     }
10921    
10922     // If this phi has a single use, and if that use just computes a value for
10923     // the next iteration of a loop, delete the phi.  This occurs with unused
10924     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10925     // common case here is good because the only other things that catch this
10926     // are induction variable analysis (sometimes) and ADCE, which is only run
10927     // late.
10928     if (PHIUser->hasOneUse() &&
10929         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10930         PHIUser->use_back() == &PN) {
10931       return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10932     }
10933   }
10934
10935   // We sometimes end up with phi cycles that non-obviously end up being the
10936   // same value, for example:
10937   //   z = some value; x = phi (y, z); y = phi (x, z)
10938   // where the phi nodes don't necessarily need to be in the same block.  Do a
10939   // quick check to see if the PHI node only contains a single non-phi value, if
10940   // so, scan to see if the phi cycle is actually equal to that value.
10941   {
10942     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10943     // Scan for the first non-phi operand.
10944     while (InValNo != NumOperandVals && 
10945            isa<PHINode>(PN.getIncomingValue(InValNo)))
10946       ++InValNo;
10947
10948     if (InValNo != NumOperandVals) {
10949       Value *NonPhiInVal = PN.getOperand(InValNo);
10950       
10951       // Scan the rest of the operands to see if there are any conflicts, if so
10952       // there is no need to recursively scan other phis.
10953       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10954         Value *OpVal = PN.getIncomingValue(InValNo);
10955         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10956           break;
10957       }
10958       
10959       // If we scanned over all operands, then we have one unique value plus
10960       // phi values.  Scan PHI nodes to see if they all merge in each other or
10961       // the value.
10962       if (InValNo == NumOperandVals) {
10963         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10964         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10965           return ReplaceInstUsesWith(PN, NonPhiInVal);
10966       }
10967     }
10968   }
10969   return 0;
10970 }
10971
10972 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10973                                    Instruction *InsertPoint,
10974                                    InstCombiner *IC) {
10975   unsigned PtrSize = DTy->getScalarSizeInBits();
10976   unsigned VTySize = V->getType()->getScalarSizeInBits();
10977   // We must cast correctly to the pointer type. Ensure that we
10978   // sign extend the integer value if it is smaller as this is
10979   // used for address computation.
10980   Instruction::CastOps opcode = 
10981      (VTySize < PtrSize ? Instruction::SExt :
10982       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10983   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10984 }
10985
10986
10987 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10988   Value *PtrOp = GEP.getOperand(0);
10989   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10990   // If so, eliminate the noop.
10991   if (GEP.getNumOperands() == 1)
10992     return ReplaceInstUsesWith(GEP, PtrOp);
10993
10994   if (isa<UndefValue>(GEP.getOperand(0)))
10995     return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
10996
10997   bool HasZeroPointerIndex = false;
10998   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10999     HasZeroPointerIndex = C->isNullValue();
11000
11001   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11002     return ReplaceInstUsesWith(GEP, PtrOp);
11003
11004   // Eliminate unneeded casts for indices.
11005   bool MadeChange = false;
11006   
11007   gep_type_iterator GTI = gep_type_begin(GEP);
11008   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11009        i != e; ++i, ++GTI) {
11010     if (isa<SequentialType>(*GTI)) {
11011       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
11012         if (CI->getOpcode() == Instruction::ZExt ||
11013             CI->getOpcode() == Instruction::SExt) {
11014           const Type *SrcTy = CI->getOperand(0)->getType();
11015           // We can eliminate a cast from i32 to i64 iff the target 
11016           // is a 32-bit pointer target.
11017           if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
11018             MadeChange = true;
11019             *i = CI->getOperand(0);
11020           }
11021         }
11022       }
11023       // If we are using a wider index than needed for this platform, shrink it
11024       // to what we need.  If narrower, sign-extend it to what we need.
11025       // If the incoming value needs a cast instruction,
11026       // insert it.  This explicit cast can make subsequent optimizations more
11027       // obvious.
11028       Value *Op = *i;
11029       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
11030         if (Constant *C = dyn_cast<Constant>(Op)) {
11031           *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
11032           MadeChange = true;
11033         } else {
11034           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11035                                 GEP);
11036           *i = Op;
11037           MadeChange = true;
11038         }
11039       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
11040         if (Constant *C = dyn_cast<Constant>(Op)) {
11041           *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
11042           MadeChange = true;
11043         } else {
11044           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11045                                 GEP);
11046           *i = Op;
11047           MadeChange = true;
11048         }
11049       }
11050     }
11051   }
11052   if (MadeChange) return &GEP;
11053
11054   // Combine Indices - If the source pointer to this getelementptr instruction
11055   // is a getelementptr instruction, combine the indices of the two
11056   // getelementptr instructions into a single instruction.
11057   //
11058   SmallVector<Value*, 8> SrcGEPOperands;
11059   if (User *Src = dyn_castGetElementPtr(PtrOp))
11060     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
11061
11062   if (!SrcGEPOperands.empty()) {
11063     // Note that if our source is a gep chain itself that we wait for that
11064     // chain to be resolved before we perform this transformation.  This
11065     // avoids us creating a TON of code in some cases.
11066     //
11067     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11068         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11069       return 0;   // Wait until our source is folded to completion.
11070
11071     SmallVector<Value*, 8> Indices;
11072
11073     // Find out whether the last index in the source GEP is a sequential idx.
11074     bool EndsWithSequential = false;
11075     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11076            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11077       EndsWithSequential = !isa<StructType>(*I);
11078
11079     // Can we combine the two pointer arithmetics offsets?
11080     if (EndsWithSequential) {
11081       // Replace: gep (gep %P, long B), long A, ...
11082       // With:    T = long A+B; gep %P, T, ...
11083       //
11084       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
11085       if (SO1 == Context->getNullValue(SO1->getType())) {
11086         Sum = GO1;
11087       } else if (GO1 == Context->getNullValue(GO1->getType())) {
11088         Sum = SO1;
11089       } else {
11090         // If they aren't the same type, convert both to an integer of the
11091         // target's pointer size.
11092         if (SO1->getType() != GO1->getType()) {
11093           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
11094             SO1 =
11095                 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
11096           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
11097             GO1 =
11098                 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
11099           } else {
11100             unsigned PS = TD->getPointerSizeInBits();
11101             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
11102               // Convert GO1 to SO1's type.
11103               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11104
11105             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
11106               // Convert SO1 to GO1's type.
11107               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11108             } else {
11109               const Type *PT = TD->getIntPtrType();
11110               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11111               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11112             }
11113           }
11114         }
11115         if (isa<Constant>(SO1) && isa<Constant>(GO1))
11116           Sum = Context->getConstantExprAdd(cast<Constant>(SO1), 
11117                                             cast<Constant>(GO1));
11118         else {
11119           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11120           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11121         }
11122       }
11123
11124       // Recycle the GEP we already have if possible.
11125       if (SrcGEPOperands.size() == 2) {
11126         GEP.setOperand(0, SrcGEPOperands[0]);
11127         GEP.setOperand(1, Sum);
11128         return &GEP;
11129       } else {
11130         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11131                        SrcGEPOperands.end()-1);
11132         Indices.push_back(Sum);
11133         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11134       }
11135     } else if (isa<Constant>(*GEP.idx_begin()) &&
11136                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11137                SrcGEPOperands.size() != 1) {
11138       // Otherwise we can do the fold if the first index of the GEP is a zero
11139       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11140                      SrcGEPOperands.end());
11141       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11142     }
11143
11144     if (!Indices.empty())
11145       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11146                                        Indices.end(), GEP.getName());
11147
11148   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11149     // GEP of global variable.  If all of the indices for this GEP are
11150     // constants, we can promote this to a constexpr instead of an instruction.
11151
11152     // Scan for nonconstants...
11153     SmallVector<Constant*, 8> Indices;
11154     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11155     for (; I != E && isa<Constant>(*I); ++I)
11156       Indices.push_back(cast<Constant>(*I));
11157
11158     if (I == E) {  // If they are all constants...
11159       Constant *CE = Context->getConstantExprGetElementPtr(GV,
11160                                                     &Indices[0],Indices.size());
11161
11162       // Replace all uses of the GEP with the new constexpr...
11163       return ReplaceInstUsesWith(GEP, CE);
11164     }
11165   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
11166     if (!isa<PointerType>(X->getType())) {
11167       // Not interesting.  Source pointer must be a cast from pointer.
11168     } else if (HasZeroPointerIndex) {
11169       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11170       // into     : GEP [10 x i8]* X, i32 0, ...
11171       //
11172       // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11173       //           into     : GEP i8* X, ...
11174       // 
11175       // This occurs when the program declares an array extern like "int X[];"
11176       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11177       const PointerType *XTy = cast<PointerType>(X->getType());
11178       if (const ArrayType *CATy =
11179           dyn_cast<ArrayType>(CPTy->getElementType())) {
11180         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11181         if (CATy->getElementType() == XTy->getElementType()) {
11182           // -> GEP i8* X, ...
11183           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11184           return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11185                                            GEP.getName());
11186         } else if (const ArrayType *XATy =
11187                  dyn_cast<ArrayType>(XTy->getElementType())) {
11188           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11189           if (CATy->getElementType() == XATy->getElementType()) {
11190             // -> GEP [10 x i8]* X, i32 0, ...
11191             // At this point, we know that the cast source type is a pointer
11192             // to an array of the same type as the destination pointer
11193             // array.  Because the array type is never stepped over (there
11194             // is a leading zero) we can fold the cast into this GEP.
11195             GEP.setOperand(0, X);
11196             return &GEP;
11197           }
11198         }
11199       }
11200     } else if (GEP.getNumOperands() == 2) {
11201       // Transform things like:
11202       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11203       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11204       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11205       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11206       if (isa<ArrayType>(SrcElTy) &&
11207           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11208           TD->getTypeAllocSize(ResElTy)) {
11209         Value *Idx[2];
11210         Idx[0] = Context->getNullValue(Type::Int32Ty);
11211         Idx[1] = GEP.getOperand(1);
11212         Value *V = InsertNewInstBefore(
11213                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
11214         // V and GEP are both pointer types --> BitCast
11215         return new BitCastInst(V, GEP.getType());
11216       }
11217       
11218       // Transform things like:
11219       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11220       //   (where tmp = 8*tmp2) into:
11221       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11222       
11223       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
11224         uint64_t ArrayEltSize =
11225             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11226         
11227         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11228         // allow either a mul, shift, or constant here.
11229         Value *NewIdx = 0;
11230         ConstantInt *Scale = 0;
11231         if (ArrayEltSize == 1) {
11232           NewIdx = GEP.getOperand(1);
11233           Scale = 
11234                Context->getConstantInt(cast<IntegerType>(NewIdx->getType()), 1);
11235         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11236           NewIdx = Context->getConstantInt(CI->getType(), 1);
11237           Scale = CI;
11238         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11239           if (Inst->getOpcode() == Instruction::Shl &&
11240               isa<ConstantInt>(Inst->getOperand(1))) {
11241             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11242             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11243             Scale = Context->getConstantInt(cast<IntegerType>(Inst->getType()),
11244                                      1ULL << ShAmtVal);
11245             NewIdx = Inst->getOperand(0);
11246           } else if (Inst->getOpcode() == Instruction::Mul &&
11247                      isa<ConstantInt>(Inst->getOperand(1))) {
11248             Scale = cast<ConstantInt>(Inst->getOperand(1));
11249             NewIdx = Inst->getOperand(0);
11250           }
11251         }
11252         
11253         // If the index will be to exactly the right offset with the scale taken
11254         // out, perform the transformation. Note, we don't know whether Scale is
11255         // signed or not. We'll use unsigned version of division/modulo
11256         // operation after making sure Scale doesn't have the sign bit set.
11257         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11258             Scale->getZExtValue() % ArrayEltSize == 0) {
11259           Scale = Context->getConstantInt(Scale->getType(),
11260                                    Scale->getZExtValue() / ArrayEltSize);
11261           if (Scale->getZExtValue() != 1) {
11262             Constant *C =
11263                    Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
11264                                                        false /*ZExt*/);
11265             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11266             NewIdx = InsertNewInstBefore(Sc, GEP);
11267           }
11268
11269           // Insert the new GEP instruction.
11270           Value *Idx[2];
11271           Idx[0] = Context->getNullValue(Type::Int32Ty);
11272           Idx[1] = NewIdx;
11273           Instruction *NewGEP =
11274             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11275           NewGEP = InsertNewInstBefore(NewGEP, GEP);
11276           // The NewGEP must be pointer typed, so must the old one -> BitCast
11277           return new BitCastInst(NewGEP, GEP.getType());
11278         }
11279       }
11280     }
11281   }
11282   
11283   /// See if we can simplify:
11284   ///   X = bitcast A to B*
11285   ///   Y = gep X, <...constant indices...>
11286   /// into a gep of the original struct.  This is important for SROA and alias
11287   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11288   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11289     if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11290       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11291       // a constant back from EmitGEPOffset.
11292       ConstantInt *OffsetV =
11293                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11294       int64_t Offset = OffsetV->getSExtValue();
11295       
11296       // If this GEP instruction doesn't move the pointer, just replace the GEP
11297       // with a bitcast of the real input to the dest type.
11298       if (Offset == 0) {
11299         // If the bitcast is of an allocation, and the allocation will be
11300         // converted to match the type of the cast, don't touch this.
11301         if (isa<AllocationInst>(BCI->getOperand(0))) {
11302           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11303           if (Instruction *I = visitBitCast(*BCI)) {
11304             if (I != BCI) {
11305               I->takeName(BCI);
11306               BCI->getParent()->getInstList().insert(BCI, I);
11307               ReplaceInstUsesWith(*BCI, I);
11308             }
11309             return &GEP;
11310           }
11311         }
11312         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11313       }
11314       
11315       // Otherwise, if the offset is non-zero, we need to find out if there is a
11316       // field at Offset in 'A's type.  If so, we can pull the cast through the
11317       // GEP.
11318       SmallVector<Value*, 8> NewIndices;
11319       const Type *InTy =
11320         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11321       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11322         Instruction *NGEP =
11323            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11324                                      NewIndices.end());
11325         if (NGEP->getType() == GEP.getType()) return NGEP;
11326         InsertNewInstBefore(NGEP, GEP);
11327         NGEP->takeName(&GEP);
11328         return new BitCastInst(NGEP, GEP.getType());
11329       }
11330     }
11331   }    
11332     
11333   return 0;
11334 }
11335
11336 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11337   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11338   if (AI.isArrayAllocation()) {  // Check C != 1
11339     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11340       const Type *NewTy = 
11341         Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
11342       AllocationInst *New = 0;
11343
11344       // Create and insert the replacement instruction...
11345       if (isa<MallocInst>(AI))
11346         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11347       else {
11348         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11349         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11350       }
11351
11352       InsertNewInstBefore(New, AI);
11353
11354       // Scan to the end of the allocation instructions, to skip over a block of
11355       // allocas if possible...also skip interleaved debug info
11356       //
11357       BasicBlock::iterator It = New;
11358       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11359
11360       // Now that I is pointing to the first non-allocation-inst in the block,
11361       // insert our getelementptr instruction...
11362       //
11363       Value *NullIdx = Context->getNullValue(Type::Int32Ty);
11364       Value *Idx[2];
11365       Idx[0] = NullIdx;
11366       Idx[1] = NullIdx;
11367       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11368                                            New->getName()+".sub", It);
11369
11370       // Now make everything use the getelementptr instead of the original
11371       // allocation.
11372       return ReplaceInstUsesWith(AI, V);
11373     } else if (isa<UndefValue>(AI.getArraySize())) {
11374       return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11375     }
11376   }
11377
11378   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11379     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11380     // Note that we only do this for alloca's, because malloc should allocate
11381     // and return a unique pointer, even for a zero byte allocation.
11382     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11383       return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11384
11385     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11386     if (AI.getAlignment() == 0)
11387       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11388   }
11389
11390   return 0;
11391 }
11392
11393 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11394   Value *Op = FI.getOperand(0);
11395
11396   // free undef -> unreachable.
11397   if (isa<UndefValue>(Op)) {
11398     // Insert a new store to null because we cannot modify the CFG here.
11399     new StoreInst(Context->getConstantIntTrue(),
11400            Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
11401     return EraseInstFromFunction(FI);
11402   }
11403   
11404   // If we have 'free null' delete the instruction.  This can happen in stl code
11405   // when lots of inlining happens.
11406   if (isa<ConstantPointerNull>(Op))
11407     return EraseInstFromFunction(FI);
11408   
11409   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11410   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11411     FI.setOperand(0, CI->getOperand(0));
11412     return &FI;
11413   }
11414   
11415   // Change free (gep X, 0,0,0,0) into free(X)
11416   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11417     if (GEPI->hasAllZeroIndices()) {
11418       AddToWorkList(GEPI);
11419       FI.setOperand(0, GEPI->getOperand(0));
11420       return &FI;
11421     }
11422   }
11423   
11424   // Change free(malloc) into nothing, if the malloc has a single use.
11425   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11426     if (MI->hasOneUse()) {
11427       EraseInstFromFunction(FI);
11428       return EraseInstFromFunction(*MI);
11429     }
11430
11431   return 0;
11432 }
11433
11434
11435 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11436 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11437                                         const TargetData *TD) {
11438   User *CI = cast<User>(LI.getOperand(0));
11439   Value *CastOp = CI->getOperand(0);
11440   LLVMContext *Context = IC.getContext();
11441
11442   if (TD) {
11443     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11444       // Instead of loading constant c string, use corresponding integer value
11445       // directly if string length is small enough.
11446       std::string Str;
11447       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11448         unsigned len = Str.length();
11449         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11450         unsigned numBits = Ty->getPrimitiveSizeInBits();
11451         // Replace LI with immediate integer store.
11452         if ((numBits >> 3) == len + 1) {
11453           APInt StrVal(numBits, 0);
11454           APInt SingleChar(numBits, 0);
11455           if (TD->isLittleEndian()) {
11456             for (signed i = len-1; i >= 0; i--) {
11457               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11458               StrVal = (StrVal << 8) | SingleChar;
11459             }
11460           } else {
11461             for (unsigned i = 0; i < len; i++) {
11462               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11463               StrVal = (StrVal << 8) | SingleChar;
11464             }
11465             // Append NULL at the end.
11466             SingleChar = 0;
11467             StrVal = (StrVal << 8) | SingleChar;
11468           }
11469           Value *NL = Context->getConstantInt(StrVal);
11470           return IC.ReplaceInstUsesWith(LI, NL);
11471         }
11472       }
11473     }
11474   }
11475
11476   const PointerType *DestTy = cast<PointerType>(CI->getType());
11477   const Type *DestPTy = DestTy->getElementType();
11478   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11479
11480     // If the address spaces don't match, don't eliminate the cast.
11481     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11482       return 0;
11483
11484     const Type *SrcPTy = SrcTy->getElementType();
11485
11486     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11487          isa<VectorType>(DestPTy)) {
11488       // If the source is an array, the code below will not succeed.  Check to
11489       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11490       // constants.
11491       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11492         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11493           if (ASrcTy->getNumElements() != 0) {
11494             Value *Idxs[2];
11495             Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11496             CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
11497             SrcTy = cast<PointerType>(CastOp->getType());
11498             SrcPTy = SrcTy->getElementType();
11499           }
11500
11501       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11502             isa<VectorType>(SrcPTy)) &&
11503           // Do not allow turning this into a load of an integer, which is then
11504           // casted to a pointer, this pessimizes pointer analysis a lot.
11505           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11506           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11507                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11508
11509         // Okay, we are casting from one integer or pointer type to another of
11510         // the same size.  Instead of casting the pointer before the load, cast
11511         // the result of the loaded value.
11512         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11513                                                              CI->getName(),
11514                                                          LI.isVolatile()),LI);
11515         // Now cast the result of the load.
11516         return new BitCastInst(NewLoad, LI.getType());
11517       }
11518     }
11519   }
11520   return 0;
11521 }
11522
11523 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11524   Value *Op = LI.getOperand(0);
11525
11526   // Attempt to improve the alignment.
11527   unsigned KnownAlign =
11528     GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11529   if (KnownAlign >
11530       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11531                                 LI.getAlignment()))
11532     LI.setAlignment(KnownAlign);
11533
11534   // load (cast X) --> cast (load X) iff safe
11535   if (isa<CastInst>(Op))
11536     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11537       return Res;
11538
11539   // None of the following transforms are legal for volatile loads.
11540   if (LI.isVolatile()) return 0;
11541   
11542   // Do really simple store-to-load forwarding and load CSE, to catch cases
11543   // where there are several consequtive memory accesses to the same location,
11544   // separated by a few arithmetic operations.
11545   BasicBlock::iterator BBI = &LI;
11546   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11547     return ReplaceInstUsesWith(LI, AvailableVal);
11548
11549   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11550     const Value *GEPI0 = GEPI->getOperand(0);
11551     // TODO: Consider a target hook for valid address spaces for this xform.
11552     if (isa<ConstantPointerNull>(GEPI0) &&
11553         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11554       // Insert a new store to null instruction before the load to indicate
11555       // that this code is not reachable.  We do this instead of inserting
11556       // an unreachable instruction directly because we cannot modify the
11557       // CFG.
11558       new StoreInst(Context->getUndef(LI.getType()),
11559                     Context->getNullValue(Op->getType()), &LI);
11560       return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11561     }
11562   } 
11563
11564   if (Constant *C = dyn_cast<Constant>(Op)) {
11565     // load null/undef -> undef
11566     // TODO: Consider a target hook for valid address spaces for this xform.
11567     if (isa<UndefValue>(C) || (C->isNullValue() && 
11568         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11569       // Insert a new store to null instruction before the load to indicate that
11570       // this code is not reachable.  We do this instead of inserting an
11571       // unreachable instruction directly because we cannot modify the CFG.
11572       new StoreInst(Context->getUndef(LI.getType()),
11573                     Context->getNullValue(Op->getType()), &LI);
11574       return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11575     }
11576
11577     // Instcombine load (constant global) into the value loaded.
11578     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11579       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11580         return ReplaceInstUsesWith(LI, GV->getInitializer());
11581
11582     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11583     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11584       if (CE->getOpcode() == Instruction::GetElementPtr) {
11585         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11586           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11587             if (Constant *V = 
11588                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE, 
11589                                                       Context))
11590               return ReplaceInstUsesWith(LI, V);
11591         if (CE->getOperand(0)->isNullValue()) {
11592           // Insert a new store to null instruction before the load to indicate
11593           // that this code is not reachable.  We do this instead of inserting
11594           // an unreachable instruction directly because we cannot modify the
11595           // CFG.
11596           new StoreInst(Context->getUndef(LI.getType()),
11597                         Context->getNullValue(Op->getType()), &LI);
11598           return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11599         }
11600
11601       } else if (CE->isCast()) {
11602         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11603           return Res;
11604       }
11605     }
11606   }
11607     
11608   // If this load comes from anywhere in a constant global, and if the global
11609   // is all undef or zero, we know what it loads.
11610   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11611     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11612       if (GV->getInitializer()->isNullValue())
11613         return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
11614       else if (isa<UndefValue>(GV->getInitializer()))
11615         return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11616     }
11617   }
11618
11619   if (Op->hasOneUse()) {
11620     // Change select and PHI nodes to select values instead of addresses: this
11621     // helps alias analysis out a lot, allows many others simplifications, and
11622     // exposes redundancy in the code.
11623     //
11624     // Note that we cannot do the transformation unless we know that the
11625     // introduced loads cannot trap!  Something like this is valid as long as
11626     // the condition is always false: load (select bool %C, int* null, int* %G),
11627     // but it would not be valid if we transformed it to load from null
11628     // unconditionally.
11629     //
11630     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11631       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11632       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11633           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11634         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11635                                      SI->getOperand(1)->getName()+".val"), LI);
11636         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11637                                      SI->getOperand(2)->getName()+".val"), LI);
11638         return SelectInst::Create(SI->getCondition(), V1, V2);
11639       }
11640
11641       // load (select (cond, null, P)) -> load P
11642       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11643         if (C->isNullValue()) {
11644           LI.setOperand(0, SI->getOperand(2));
11645           return &LI;
11646         }
11647
11648       // load (select (cond, P, null)) -> load P
11649       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11650         if (C->isNullValue()) {
11651           LI.setOperand(0, SI->getOperand(1));
11652           return &LI;
11653         }
11654     }
11655   }
11656   return 0;
11657 }
11658
11659 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11660 /// when possible.  This makes it generally easy to do alias analysis and/or
11661 /// SROA/mem2reg of the memory object.
11662 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11663   User *CI = cast<User>(SI.getOperand(1));
11664   Value *CastOp = CI->getOperand(0);
11665   LLVMContext *Context = IC.getContext();
11666
11667   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11668   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11669   if (SrcTy == 0) return 0;
11670   
11671   const Type *SrcPTy = SrcTy->getElementType();
11672
11673   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11674     return 0;
11675   
11676   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11677   /// to its first element.  This allows us to handle things like:
11678   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11679   /// on 32-bit hosts.
11680   SmallVector<Value*, 4> NewGEPIndices;
11681   
11682   // If the source is an array, the code below will not succeed.  Check to
11683   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11684   // constants.
11685   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11686     // Index through pointer.
11687     Constant *Zero = Context->getNullValue(Type::Int32Ty);
11688     NewGEPIndices.push_back(Zero);
11689     
11690     while (1) {
11691       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11692         if (!STy->getNumElements()) /* Struct can be empty {} */
11693           break;
11694         NewGEPIndices.push_back(Zero);
11695         SrcPTy = STy->getElementType(0);
11696       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11697         NewGEPIndices.push_back(Zero);
11698         SrcPTy = ATy->getElementType();
11699       } else {
11700         break;
11701       }
11702     }
11703     
11704     SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
11705   }
11706
11707   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11708     return 0;
11709   
11710   // If the pointers point into different address spaces or if they point to
11711   // values with different sizes, we can't do the transformation.
11712   if (SrcTy->getAddressSpace() != 
11713         cast<PointerType>(CI->getType())->getAddressSpace() ||
11714       IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
11715       IC.getTargetData().getTypeSizeInBits(DestPTy))
11716     return 0;
11717
11718   // Okay, we are casting from one integer or pointer type to another of
11719   // the same size.  Instead of casting the pointer before 
11720   // the store, cast the value to be stored.
11721   Value *NewCast;
11722   Value *SIOp0 = SI.getOperand(0);
11723   Instruction::CastOps opcode = Instruction::BitCast;
11724   const Type* CastSrcTy = SIOp0->getType();
11725   const Type* CastDstTy = SrcPTy;
11726   if (isa<PointerType>(CastDstTy)) {
11727     if (CastSrcTy->isInteger())
11728       opcode = Instruction::IntToPtr;
11729   } else if (isa<IntegerType>(CastDstTy)) {
11730     if (isa<PointerType>(SIOp0->getType()))
11731       opcode = Instruction::PtrToInt;
11732   }
11733   
11734   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11735   // emit a GEP to index into its first field.
11736   if (!NewGEPIndices.empty()) {
11737     if (Constant *C = dyn_cast<Constant>(CastOp))
11738       CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0], 
11739                                               NewGEPIndices.size());
11740     else
11741       CastOp = IC.InsertNewInstBefore(
11742               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11743                                         NewGEPIndices.end()), SI);
11744   }
11745   
11746   if (Constant *C = dyn_cast<Constant>(SIOp0))
11747     NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
11748   else
11749     NewCast = IC.InsertNewInstBefore(
11750       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11751       SI);
11752   return new StoreInst(NewCast, CastOp);
11753 }
11754
11755 /// equivalentAddressValues - Test if A and B will obviously have the same
11756 /// value. This includes recognizing that %t0 and %t1 will have the same
11757 /// value in code like this:
11758 ///   %t0 = getelementptr \@a, 0, 3
11759 ///   store i32 0, i32* %t0
11760 ///   %t1 = getelementptr \@a, 0, 3
11761 ///   %t2 = load i32* %t1
11762 ///
11763 static bool equivalentAddressValues(Value *A, Value *B) {
11764   // Test if the values are trivially equivalent.
11765   if (A == B) return true;
11766   
11767   // Test if the values come form identical arithmetic instructions.
11768   if (isa<BinaryOperator>(A) ||
11769       isa<CastInst>(A) ||
11770       isa<PHINode>(A) ||
11771       isa<GetElementPtrInst>(A))
11772     if (Instruction *BI = dyn_cast<Instruction>(B))
11773       if (cast<Instruction>(A)->isIdenticalTo(BI))
11774         return true;
11775   
11776   // Otherwise they may not be equivalent.
11777   return false;
11778 }
11779
11780 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11781 // return the llvm.dbg.declare.
11782 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11783   if (!V->hasNUses(2))
11784     return 0;
11785   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11786        UI != E; ++UI) {
11787     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11788       return DI;
11789     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11790       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11791         return DI;
11792       }
11793   }
11794   return 0;
11795 }
11796
11797 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11798   Value *Val = SI.getOperand(0);
11799   Value *Ptr = SI.getOperand(1);
11800
11801   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11802     EraseInstFromFunction(SI);
11803     ++NumCombined;
11804     return 0;
11805   }
11806   
11807   // If the RHS is an alloca with a single use, zapify the store, making the
11808   // alloca dead.
11809   // If the RHS is an alloca with a two uses, the other one being a 
11810   // llvm.dbg.declare, zapify the store and the declare, making the
11811   // alloca dead.  We must do this to prevent declare's from affecting
11812   // codegen.
11813   if (!SI.isVolatile()) {
11814     if (Ptr->hasOneUse()) {
11815       if (isa<AllocaInst>(Ptr)) {
11816         EraseInstFromFunction(SI);
11817         ++NumCombined;
11818         return 0;
11819       }
11820       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11821         if (isa<AllocaInst>(GEP->getOperand(0))) {
11822           if (GEP->getOperand(0)->hasOneUse()) {
11823             EraseInstFromFunction(SI);
11824             ++NumCombined;
11825             return 0;
11826           }
11827           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11828             EraseInstFromFunction(*DI);
11829             EraseInstFromFunction(SI);
11830             ++NumCombined;
11831             return 0;
11832           }
11833         }
11834       }
11835     }
11836     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11837       EraseInstFromFunction(*DI);
11838       EraseInstFromFunction(SI);
11839       ++NumCombined;
11840       return 0;
11841     }
11842   }
11843
11844   // Attempt to improve the alignment.
11845   unsigned KnownAlign =
11846     GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11847   if (KnownAlign >
11848       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11849                                 SI.getAlignment()))
11850     SI.setAlignment(KnownAlign);
11851
11852   // Do really simple DSE, to catch cases where there are several consecutive
11853   // stores to the same location, separated by a few arithmetic operations. This
11854   // situation often occurs with bitfield accesses.
11855   BasicBlock::iterator BBI = &SI;
11856   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11857        --ScanInsts) {
11858     --BBI;
11859     // Don't count debug info directives, lest they affect codegen,
11860     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11861     // It is necessary for correctness to skip those that feed into a
11862     // llvm.dbg.declare, as these are not present when debugging is off.
11863     if (isa<DbgInfoIntrinsic>(BBI) ||
11864         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11865       ScanInsts++;
11866       continue;
11867     }    
11868     
11869     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11870       // Prev store isn't volatile, and stores to the same location?
11871       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11872                                                           SI.getOperand(1))) {
11873         ++NumDeadStore;
11874         ++BBI;
11875         EraseInstFromFunction(*PrevSI);
11876         continue;
11877       }
11878       break;
11879     }
11880     
11881     // If this is a load, we have to stop.  However, if the loaded value is from
11882     // the pointer we're loading and is producing the pointer we're storing,
11883     // then *this* store is dead (X = load P; store X -> P).
11884     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11885       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11886           !SI.isVolatile()) {
11887         EraseInstFromFunction(SI);
11888         ++NumCombined;
11889         return 0;
11890       }
11891       // Otherwise, this is a load from some other location.  Stores before it
11892       // may not be dead.
11893       break;
11894     }
11895     
11896     // Don't skip over loads or things that can modify memory.
11897     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11898       break;
11899   }
11900   
11901   
11902   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11903
11904   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11905   if (isa<ConstantPointerNull>(Ptr) &&
11906       cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11907     if (!isa<UndefValue>(Val)) {
11908       SI.setOperand(0, Context->getUndef(Val->getType()));
11909       if (Instruction *U = dyn_cast<Instruction>(Val))
11910         AddToWorkList(U);  // Dropped a use.
11911       ++NumCombined;
11912     }
11913     return 0;  // Do not modify these!
11914   }
11915
11916   // store undef, Ptr -> noop
11917   if (isa<UndefValue>(Val)) {
11918     EraseInstFromFunction(SI);
11919     ++NumCombined;
11920     return 0;
11921   }
11922
11923   // If the pointer destination is a cast, see if we can fold the cast into the
11924   // source instead.
11925   if (isa<CastInst>(Ptr))
11926     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11927       return Res;
11928   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11929     if (CE->isCast())
11930       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11931         return Res;
11932
11933   
11934   // If this store is the last instruction in the basic block (possibly
11935   // excepting debug info instructions and the pointer bitcasts that feed
11936   // into them), and if the block ends with an unconditional branch, try
11937   // to move it to the successor block.
11938   BBI = &SI; 
11939   do {
11940     ++BBI;
11941   } while (isa<DbgInfoIntrinsic>(BBI) ||
11942            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11943   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11944     if (BI->isUnconditional())
11945       if (SimplifyStoreAtEndOfBlock(SI))
11946         return 0;  // xform done!
11947   
11948   return 0;
11949 }
11950
11951 /// SimplifyStoreAtEndOfBlock - Turn things like:
11952 ///   if () { *P = v1; } else { *P = v2 }
11953 /// into a phi node with a store in the successor.
11954 ///
11955 /// Simplify things like:
11956 ///   *P = v1; if () { *P = v2; }
11957 /// into a phi node with a store in the successor.
11958 ///
11959 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11960   BasicBlock *StoreBB = SI.getParent();
11961   
11962   // Check to see if the successor block has exactly two incoming edges.  If
11963   // so, see if the other predecessor contains a store to the same location.
11964   // if so, insert a PHI node (if needed) and move the stores down.
11965   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11966   
11967   // Determine whether Dest has exactly two predecessors and, if so, compute
11968   // the other predecessor.
11969   pred_iterator PI = pred_begin(DestBB);
11970   BasicBlock *OtherBB = 0;
11971   if (*PI != StoreBB)
11972     OtherBB = *PI;
11973   ++PI;
11974   if (PI == pred_end(DestBB))
11975     return false;
11976   
11977   if (*PI != StoreBB) {
11978     if (OtherBB)
11979       return false;
11980     OtherBB = *PI;
11981   }
11982   if (++PI != pred_end(DestBB))
11983     return false;
11984
11985   // Bail out if all the relevant blocks aren't distinct (this can happen,
11986   // for example, if SI is in an infinite loop)
11987   if (StoreBB == DestBB || OtherBB == DestBB)
11988     return false;
11989
11990   // Verify that the other block ends in a branch and is not otherwise empty.
11991   BasicBlock::iterator BBI = OtherBB->getTerminator();
11992   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11993   if (!OtherBr || BBI == OtherBB->begin())
11994     return false;
11995   
11996   // If the other block ends in an unconditional branch, check for the 'if then
11997   // else' case.  there is an instruction before the branch.
11998   StoreInst *OtherStore = 0;
11999   if (OtherBr->isUnconditional()) {
12000     --BBI;
12001     // Skip over debugging info.
12002     while (isa<DbgInfoIntrinsic>(BBI) ||
12003            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12004       if (BBI==OtherBB->begin())
12005         return false;
12006       --BBI;
12007     }
12008     // If this isn't a store, or isn't a store to the same location, bail out.
12009     OtherStore = dyn_cast<StoreInst>(BBI);
12010     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12011       return false;
12012   } else {
12013     // Otherwise, the other block ended with a conditional branch. If one of the
12014     // destinations is StoreBB, then we have the if/then case.
12015     if (OtherBr->getSuccessor(0) != StoreBB && 
12016         OtherBr->getSuccessor(1) != StoreBB)
12017       return false;
12018     
12019     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12020     // if/then triangle.  See if there is a store to the same ptr as SI that
12021     // lives in OtherBB.
12022     for (;; --BBI) {
12023       // Check to see if we find the matching store.
12024       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12025         if (OtherStore->getOperand(1) != SI.getOperand(1))
12026           return false;
12027         break;
12028       }
12029       // If we find something that may be using or overwriting the stored
12030       // value, or if we run out of instructions, we can't do the xform.
12031       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12032           BBI == OtherBB->begin())
12033         return false;
12034     }
12035     
12036     // In order to eliminate the store in OtherBr, we have to
12037     // make sure nothing reads or overwrites the stored value in
12038     // StoreBB.
12039     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12040       // FIXME: This should really be AA driven.
12041       if (I->mayReadFromMemory() || I->mayWriteToMemory())
12042         return false;
12043     }
12044   }
12045   
12046   // Insert a PHI node now if we need it.
12047   Value *MergedVal = OtherStore->getOperand(0);
12048   if (MergedVal != SI.getOperand(0)) {
12049     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12050     PN->reserveOperandSpace(2);
12051     PN->addIncoming(SI.getOperand(0), SI.getParent());
12052     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12053     MergedVal = InsertNewInstBefore(PN, DestBB->front());
12054   }
12055   
12056   // Advance to a place where it is safe to insert the new store and
12057   // insert it.
12058   BBI = DestBB->getFirstNonPHI();
12059   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12060                                     OtherStore->isVolatile()), *BBI);
12061   
12062   // Nuke the old stores.
12063   EraseInstFromFunction(SI);
12064   EraseInstFromFunction(*OtherStore);
12065   ++NumCombined;
12066   return true;
12067 }
12068
12069
12070 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12071   // Change br (not X), label True, label False to: br X, label False, True
12072   Value *X = 0;
12073   BasicBlock *TrueDest;
12074   BasicBlock *FalseDest;
12075   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
12076       !isa<Constant>(X)) {
12077     // Swap Destinations and condition...
12078     BI.setCondition(X);
12079     BI.setSuccessor(0, FalseDest);
12080     BI.setSuccessor(1, TrueDest);
12081     return &BI;
12082   }
12083
12084   // Cannonicalize fcmp_one -> fcmp_oeq
12085   FCmpInst::Predicate FPred; Value *Y;
12086   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
12087                              TrueDest, FalseDest), *Context))
12088     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12089          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12090       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12091       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
12092       Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
12093       NewSCC->takeName(I);
12094       // Swap Destinations and condition...
12095       BI.setCondition(NewSCC);
12096       BI.setSuccessor(0, FalseDest);
12097       BI.setSuccessor(1, TrueDest);
12098       RemoveFromWorkList(I);
12099       I->eraseFromParent();
12100       AddToWorkList(NewSCC);
12101       return &BI;
12102     }
12103
12104   // Cannonicalize icmp_ne -> icmp_eq
12105   ICmpInst::Predicate IPred;
12106   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12107                       TrueDest, FalseDest), *Context))
12108     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12109          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12110          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12111       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12112       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
12113       Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
12114       NewSCC->takeName(I);
12115       // Swap Destinations and condition...
12116       BI.setCondition(NewSCC);
12117       BI.setSuccessor(0, FalseDest);
12118       BI.setSuccessor(1, TrueDest);
12119       RemoveFromWorkList(I);
12120       I->eraseFromParent();;
12121       AddToWorkList(NewSCC);
12122       return &BI;
12123     }
12124
12125   return 0;
12126 }
12127
12128 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12129   Value *Cond = SI.getCondition();
12130   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12131     if (I->getOpcode() == Instruction::Add)
12132       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12133         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12134         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12135           SI.setOperand(i,
12136                    Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
12137                                                 AddRHS));
12138         SI.setOperand(0, I->getOperand(0));
12139         AddToWorkList(I);
12140         return &SI;
12141       }
12142   }
12143   return 0;
12144 }
12145
12146 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12147   Value *Agg = EV.getAggregateOperand();
12148
12149   if (!EV.hasIndices())
12150     return ReplaceInstUsesWith(EV, Agg);
12151
12152   if (Constant *C = dyn_cast<Constant>(Agg)) {
12153     if (isa<UndefValue>(C))
12154       return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
12155       
12156     if (isa<ConstantAggregateZero>(C))
12157       return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
12158
12159     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12160       // Extract the element indexed by the first index out of the constant
12161       Value *V = C->getOperand(*EV.idx_begin());
12162       if (EV.getNumIndices() > 1)
12163         // Extract the remaining indices out of the constant indexed by the
12164         // first index
12165         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12166       else
12167         return ReplaceInstUsesWith(EV, V);
12168     }
12169     return 0; // Can't handle other constants
12170   } 
12171   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12172     // We're extracting from an insertvalue instruction, compare the indices
12173     const unsigned *exti, *exte, *insi, *inse;
12174     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12175          exte = EV.idx_end(), inse = IV->idx_end();
12176          exti != exte && insi != inse;
12177          ++exti, ++insi) {
12178       if (*insi != *exti)
12179         // The insert and extract both reference distinctly different elements.
12180         // This means the extract is not influenced by the insert, and we can
12181         // replace the aggregate operand of the extract with the aggregate
12182         // operand of the insert. i.e., replace
12183         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12184         // %E = extractvalue { i32, { i32 } } %I, 0
12185         // with
12186         // %E = extractvalue { i32, { i32 } } %A, 0
12187         return ExtractValueInst::Create(IV->getAggregateOperand(),
12188                                         EV.idx_begin(), EV.idx_end());
12189     }
12190     if (exti == exte && insi == inse)
12191       // Both iterators are at the end: Index lists are identical. Replace
12192       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12193       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12194       // with "i32 42"
12195       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12196     if (exti == exte) {
12197       // The extract list is a prefix of the insert list. i.e. replace
12198       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12199       // %E = extractvalue { i32, { i32 } } %I, 1
12200       // with
12201       // %X = extractvalue { i32, { i32 } } %A, 1
12202       // %E = insertvalue { i32 } %X, i32 42, 0
12203       // by switching the order of the insert and extract (though the
12204       // insertvalue should be left in, since it may have other uses).
12205       Value *NewEV = InsertNewInstBefore(
12206         ExtractValueInst::Create(IV->getAggregateOperand(),
12207                                  EV.idx_begin(), EV.idx_end()),
12208         EV);
12209       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12210                                      insi, inse);
12211     }
12212     if (insi == inse)
12213       // The insert list is a prefix of the extract list
12214       // We can simply remove the common indices from the extract and make it
12215       // operate on the inserted value instead of the insertvalue result.
12216       // i.e., replace
12217       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12218       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12219       // with
12220       // %E extractvalue { i32 } { i32 42 }, 0
12221       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12222                                       exti, exte);
12223   }
12224   // Can't simplify extracts from other values. Note that nested extracts are
12225   // already simplified implicitely by the above (extract ( extract (insert) )
12226   // will be translated into extract ( insert ( extract ) ) first and then just
12227   // the value inserted, if appropriate).
12228   return 0;
12229 }
12230
12231 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12232 /// is to leave as a vector operation.
12233 static bool CheapToScalarize(Value *V, bool isConstant) {
12234   if (isa<ConstantAggregateZero>(V)) 
12235     return true;
12236   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12237     if (isConstant) return true;
12238     // If all elts are the same, we can extract.
12239     Constant *Op0 = C->getOperand(0);
12240     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12241       if (C->getOperand(i) != Op0)
12242         return false;
12243     return true;
12244   }
12245   Instruction *I = dyn_cast<Instruction>(V);
12246   if (!I) return false;
12247   
12248   // Insert element gets simplified to the inserted element or is deleted if
12249   // this is constant idx extract element and its a constant idx insertelt.
12250   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12251       isa<ConstantInt>(I->getOperand(2)))
12252     return true;
12253   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12254     return true;
12255   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12256     if (BO->hasOneUse() &&
12257         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12258          CheapToScalarize(BO->getOperand(1), isConstant)))
12259       return true;
12260   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12261     if (CI->hasOneUse() &&
12262         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12263          CheapToScalarize(CI->getOperand(1), isConstant)))
12264       return true;
12265   
12266   return false;
12267 }
12268
12269 /// Read and decode a shufflevector mask.
12270 ///
12271 /// It turns undef elements into values that are larger than the number of
12272 /// elements in the input.
12273 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12274   unsigned NElts = SVI->getType()->getNumElements();
12275   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12276     return std::vector<unsigned>(NElts, 0);
12277   if (isa<UndefValue>(SVI->getOperand(2)))
12278     return std::vector<unsigned>(NElts, 2*NElts);
12279
12280   std::vector<unsigned> Result;
12281   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12282   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12283     if (isa<UndefValue>(*i))
12284       Result.push_back(NElts*2);  // undef -> 8
12285     else
12286       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12287   return Result;
12288 }
12289
12290 /// FindScalarElement - Given a vector and an element number, see if the scalar
12291 /// value is already around as a register, for example if it were inserted then
12292 /// extracted from the vector.
12293 static Value *FindScalarElement(Value *V, unsigned EltNo,
12294                                 LLVMContext *Context) {
12295   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12296   const VectorType *PTy = cast<VectorType>(V->getType());
12297   unsigned Width = PTy->getNumElements();
12298   if (EltNo >= Width)  // Out of range access.
12299     return Context->getUndef(PTy->getElementType());
12300   
12301   if (isa<UndefValue>(V))
12302     return Context->getUndef(PTy->getElementType());
12303   else if (isa<ConstantAggregateZero>(V))
12304     return Context->getNullValue(PTy->getElementType());
12305   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12306     return CP->getOperand(EltNo);
12307   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12308     // If this is an insert to a variable element, we don't know what it is.
12309     if (!isa<ConstantInt>(III->getOperand(2))) 
12310       return 0;
12311     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12312     
12313     // If this is an insert to the element we are looking for, return the
12314     // inserted value.
12315     if (EltNo == IIElt) 
12316       return III->getOperand(1);
12317     
12318     // Otherwise, the insertelement doesn't modify the value, recurse on its
12319     // vector input.
12320     return FindScalarElement(III->getOperand(0), EltNo, Context);
12321   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12322     unsigned LHSWidth =
12323       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12324     unsigned InEl = getShuffleMask(SVI)[EltNo];
12325     if (InEl < LHSWidth)
12326       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12327     else if (InEl < LHSWidth*2)
12328       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12329     else
12330       return Context->getUndef(PTy->getElementType());
12331   }
12332   
12333   // Otherwise, we don't know.
12334   return 0;
12335 }
12336
12337 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12338   // If vector val is undef, replace extract with scalar undef.
12339   if (isa<UndefValue>(EI.getOperand(0)))
12340     return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12341
12342   // If vector val is constant 0, replace extract with scalar 0.
12343   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12344     return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
12345   
12346   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12347     // If vector val is constant with all elements the same, replace EI with
12348     // that element. When the elements are not identical, we cannot replace yet
12349     // (we do that below, but only when the index is constant).
12350     Constant *op0 = C->getOperand(0);
12351     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12352       if (C->getOperand(i) != op0) {
12353         op0 = 0; 
12354         break;
12355       }
12356     if (op0)
12357       return ReplaceInstUsesWith(EI, op0);
12358   }
12359   
12360   // If extracting a specified index from the vector, see if we can recursively
12361   // find a previously computed scalar that was inserted into the vector.
12362   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12363     unsigned IndexVal = IdxC->getZExtValue();
12364     unsigned VectorWidth = 
12365       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12366       
12367     // If this is extracting an invalid index, turn this into undef, to avoid
12368     // crashing the code below.
12369     if (IndexVal >= VectorWidth)
12370       return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12371     
12372     // This instruction only demands the single element from the input vector.
12373     // If the input vector has a single use, simplify it based on this use
12374     // property.
12375     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12376       APInt UndefElts(VectorWidth, 0);
12377       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12378       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12379                                                 DemandedMask, UndefElts)) {
12380         EI.setOperand(0, V);
12381         return &EI;
12382       }
12383     }
12384     
12385     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12386       return ReplaceInstUsesWith(EI, Elt);
12387     
12388     // If the this extractelement is directly using a bitcast from a vector of
12389     // the same number of elements, see if we can find the source element from
12390     // it.  In this case, we will end up needing to bitcast the scalars.
12391     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12392       if (const VectorType *VT = 
12393               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12394         if (VT->getNumElements() == VectorWidth)
12395           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12396                                              IndexVal, Context))
12397             return new BitCastInst(Elt, EI.getType());
12398     }
12399   }
12400   
12401   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12402     if (I->hasOneUse()) {
12403       // Push extractelement into predecessor operation if legal and
12404       // profitable to do so
12405       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12406         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12407         if (CheapToScalarize(BO, isConstantElt)) {
12408           ExtractElementInst *newEI0 = 
12409             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12410                                    EI.getName()+".lhs");
12411           ExtractElementInst *newEI1 =
12412             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12413                                    EI.getName()+".rhs");
12414           InsertNewInstBefore(newEI0, EI);
12415           InsertNewInstBefore(newEI1, EI);
12416           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12417         }
12418       } else if (isa<LoadInst>(I)) {
12419         unsigned AS = 
12420           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12421         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12422                                   Context->getPointerType(EI.getType(), AS),EI);
12423         GetElementPtrInst *GEP =
12424           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12425         InsertNewInstBefore(GEP, EI);
12426         return new LoadInst(GEP);
12427       }
12428     }
12429     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12430       // Extracting the inserted element?
12431       if (IE->getOperand(2) == EI.getOperand(1))
12432         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12433       // If the inserted and extracted elements are constants, they must not
12434       // be the same value, extract from the pre-inserted value instead.
12435       if (isa<Constant>(IE->getOperand(2)) &&
12436           isa<Constant>(EI.getOperand(1))) {
12437         AddUsesToWorkList(EI);
12438         EI.setOperand(0, IE->getOperand(0));
12439         return &EI;
12440       }
12441     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12442       // If this is extracting an element from a shufflevector, figure out where
12443       // it came from and extract from the appropriate input element instead.
12444       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12445         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12446         Value *Src;
12447         unsigned LHSWidth =
12448           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12449
12450         if (SrcIdx < LHSWidth)
12451           Src = SVI->getOperand(0);
12452         else if (SrcIdx < LHSWidth*2) {
12453           SrcIdx -= LHSWidth;
12454           Src = SVI->getOperand(1);
12455         } else {
12456           return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12457         }
12458         return new ExtractElementInst(Src, SrcIdx);
12459       }
12460     }
12461   }
12462   return 0;
12463 }
12464
12465 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12466 /// elements from either LHS or RHS, return the shuffle mask and true. 
12467 /// Otherwise, return false.
12468 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12469                                          std::vector<Constant*> &Mask,
12470                                          LLVMContext *Context) {
12471   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12472          "Invalid CollectSingleShuffleElements");
12473   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12474
12475   if (isa<UndefValue>(V)) {
12476     Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12477     return true;
12478   } else if (V == LHS) {
12479     for (unsigned i = 0; i != NumElts; ++i)
12480       Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12481     return true;
12482   } else if (V == RHS) {
12483     for (unsigned i = 0; i != NumElts; ++i)
12484       Mask.push_back(Context->getConstantInt(Type::Int32Ty, i+NumElts));
12485     return true;
12486   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12487     // If this is an insert of an extract from some other vector, include it.
12488     Value *VecOp    = IEI->getOperand(0);
12489     Value *ScalarOp = IEI->getOperand(1);
12490     Value *IdxOp    = IEI->getOperand(2);
12491     
12492     if (!isa<ConstantInt>(IdxOp))
12493       return false;
12494     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12495     
12496     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12497       // Okay, we can handle this if the vector we are insertinting into is
12498       // transitively ok.
12499       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12500         // If so, update the mask to reflect the inserted undef.
12501         Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
12502         return true;
12503       }      
12504     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12505       if (isa<ConstantInt>(EI->getOperand(1)) &&
12506           EI->getOperand(0)->getType() == V->getType()) {
12507         unsigned ExtractedIdx =
12508           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12509         
12510         // This must be extracting from either LHS or RHS.
12511         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12512           // Okay, we can handle this if the vector we are insertinting into is
12513           // transitively ok.
12514           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12515             // If so, update the mask to reflect the inserted value.
12516             if (EI->getOperand(0) == LHS) {
12517               Mask[InsertedIdx % NumElts] = 
12518                  Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12519             } else {
12520               assert(EI->getOperand(0) == RHS);
12521               Mask[InsertedIdx % NumElts] = 
12522                 Context->getConstantInt(Type::Int32Ty, ExtractedIdx+NumElts);
12523               
12524             }
12525             return true;
12526           }
12527         }
12528       }
12529     }
12530   }
12531   // TODO: Handle shufflevector here!
12532   
12533   return false;
12534 }
12535
12536 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12537 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12538 /// that computes V and the LHS value of the shuffle.
12539 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12540                                      Value *&RHS, LLVMContext *Context) {
12541   assert(isa<VectorType>(V->getType()) && 
12542          (RHS == 0 || V->getType() == RHS->getType()) &&
12543          "Invalid shuffle!");
12544   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12545
12546   if (isa<UndefValue>(V)) {
12547     Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12548     return V;
12549   } else if (isa<ConstantAggregateZero>(V)) {
12550     Mask.assign(NumElts, Context->getConstantInt(Type::Int32Ty, 0));
12551     return V;
12552   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12553     // If this is an insert of an extract from some other vector, include it.
12554     Value *VecOp    = IEI->getOperand(0);
12555     Value *ScalarOp = IEI->getOperand(1);
12556     Value *IdxOp    = IEI->getOperand(2);
12557     
12558     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12559       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12560           EI->getOperand(0)->getType() == V->getType()) {
12561         unsigned ExtractedIdx =
12562           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12563         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12564         
12565         // Either the extracted from or inserted into vector must be RHSVec,
12566         // otherwise we'd end up with a shuffle of three inputs.
12567         if (EI->getOperand(0) == RHS || RHS == 0) {
12568           RHS = EI->getOperand(0);
12569           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12570           Mask[InsertedIdx % NumElts] = 
12571             Context->getConstantInt(Type::Int32Ty, NumElts+ExtractedIdx);
12572           return V;
12573         }
12574         
12575         if (VecOp == RHS) {
12576           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12577                                             RHS, Context);
12578           // Everything but the extracted element is replaced with the RHS.
12579           for (unsigned i = 0; i != NumElts; ++i) {
12580             if (i != InsertedIdx)
12581               Mask[i] = Context->getConstantInt(Type::Int32Ty, NumElts+i);
12582           }
12583           return V;
12584         }
12585         
12586         // If this insertelement is a chain that comes from exactly these two
12587         // vectors, return the vector and the effective shuffle.
12588         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12589                                          Context))
12590           return EI->getOperand(0);
12591         
12592       }
12593     }
12594   }
12595   // TODO: Handle shufflevector here!
12596   
12597   // Otherwise, can't do anything fancy.  Return an identity vector.
12598   for (unsigned i = 0; i != NumElts; ++i)
12599     Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12600   return V;
12601 }
12602
12603 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12604   Value *VecOp    = IE.getOperand(0);
12605   Value *ScalarOp = IE.getOperand(1);
12606   Value *IdxOp    = IE.getOperand(2);
12607   
12608   // Inserting an undef or into an undefined place, remove this.
12609   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12610     ReplaceInstUsesWith(IE, VecOp);
12611   
12612   // If the inserted element was extracted from some other vector, and if the 
12613   // indexes are constant, try to turn this into a shufflevector operation.
12614   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12615     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12616         EI->getOperand(0)->getType() == IE.getType()) {
12617       unsigned NumVectorElts = IE.getType()->getNumElements();
12618       unsigned ExtractedIdx =
12619         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12620       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12621       
12622       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12623         return ReplaceInstUsesWith(IE, VecOp);
12624       
12625       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12626         return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
12627       
12628       // If we are extracting a value from a vector, then inserting it right
12629       // back into the same place, just use the input vector.
12630       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12631         return ReplaceInstUsesWith(IE, VecOp);      
12632       
12633       // We could theoretically do this for ANY input.  However, doing so could
12634       // turn chains of insertelement instructions into a chain of shufflevector
12635       // instructions, and right now we do not merge shufflevectors.  As such,
12636       // only do this in a situation where it is clear that there is benefit.
12637       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12638         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12639         // the values of VecOp, except then one read from EIOp0.
12640         // Build a new shuffle mask.
12641         std::vector<Constant*> Mask;
12642         if (isa<UndefValue>(VecOp))
12643           Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
12644         else {
12645           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12646           Mask.assign(NumVectorElts, Context->getConstantInt(Type::Int32Ty,
12647                                                        NumVectorElts));
12648         } 
12649         Mask[InsertedIdx] = 
12650                            Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12651         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12652                                      Context->getConstantVector(Mask));
12653       }
12654       
12655       // If this insertelement isn't used by some other insertelement, turn it
12656       // (and any insertelements it points to), into one big shuffle.
12657       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12658         std::vector<Constant*> Mask;
12659         Value *RHS = 0;
12660         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12661         if (RHS == 0) RHS = Context->getUndef(LHS->getType());
12662         // We now have a shuffle of LHS, RHS, Mask.
12663         return new ShuffleVectorInst(LHS, RHS,
12664                                      Context->getConstantVector(Mask));
12665       }
12666     }
12667   }
12668
12669   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12670   APInt UndefElts(VWidth, 0);
12671   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12672   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12673     return &IE;
12674
12675   return 0;
12676 }
12677
12678
12679 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12680   Value *LHS = SVI.getOperand(0);
12681   Value *RHS = SVI.getOperand(1);
12682   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12683
12684   bool MadeChange = false;
12685
12686   // Undefined shuffle mask -> undefined value.
12687   if (isa<UndefValue>(SVI.getOperand(2)))
12688     return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
12689
12690   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12691
12692   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12693     return 0;
12694
12695   APInt UndefElts(VWidth, 0);
12696   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12697   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12698     LHS = SVI.getOperand(0);
12699     RHS = SVI.getOperand(1);
12700     MadeChange = true;
12701   }
12702   
12703   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12704   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12705   if (LHS == RHS || isa<UndefValue>(LHS)) {
12706     if (isa<UndefValue>(LHS) && LHS == RHS) {
12707       // shuffle(undef,undef,mask) -> undef.
12708       return ReplaceInstUsesWith(SVI, LHS);
12709     }
12710     
12711     // Remap any references to RHS to use LHS.
12712     std::vector<Constant*> Elts;
12713     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12714       if (Mask[i] >= 2*e)
12715         Elts.push_back(Context->getUndef(Type::Int32Ty));
12716       else {
12717         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12718             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12719           Mask[i] = 2*e;     // Turn into undef.
12720           Elts.push_back(Context->getUndef(Type::Int32Ty));
12721         } else {
12722           Mask[i] = Mask[i] % e;  // Force to LHS.
12723           Elts.push_back(Context->getConstantInt(Type::Int32Ty, Mask[i]));
12724         }
12725       }
12726     }
12727     SVI.setOperand(0, SVI.getOperand(1));
12728     SVI.setOperand(1, Context->getUndef(RHS->getType()));
12729     SVI.setOperand(2, Context->getConstantVector(Elts));
12730     LHS = SVI.getOperand(0);
12731     RHS = SVI.getOperand(1);
12732     MadeChange = true;
12733   }
12734   
12735   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12736   bool isLHSID = true, isRHSID = true;
12737     
12738   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12739     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12740     // Is this an identity shuffle of the LHS value?
12741     isLHSID &= (Mask[i] == i);
12742       
12743     // Is this an identity shuffle of the RHS value?
12744     isRHSID &= (Mask[i]-e == i);
12745   }
12746
12747   // Eliminate identity shuffles.
12748   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12749   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12750   
12751   // If the LHS is a shufflevector itself, see if we can combine it with this
12752   // one without producing an unusual shuffle.  Here we are really conservative:
12753   // we are absolutely afraid of producing a shuffle mask not in the input
12754   // program, because the code gen may not be smart enough to turn a merged
12755   // shuffle into two specific shuffles: it may produce worse code.  As such,
12756   // we only merge two shuffles if the result is one of the two input shuffle
12757   // masks.  In this case, merging the shuffles just removes one instruction,
12758   // which we know is safe.  This is good for things like turning:
12759   // (splat(splat)) -> splat.
12760   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12761     if (isa<UndefValue>(RHS)) {
12762       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12763
12764       std::vector<unsigned> NewMask;
12765       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12766         if (Mask[i] >= 2*e)
12767           NewMask.push_back(2*e);
12768         else
12769           NewMask.push_back(LHSMask[Mask[i]]);
12770       
12771       // If the result mask is equal to the src shuffle or this shuffle mask, do
12772       // the replacement.
12773       if (NewMask == LHSMask || NewMask == Mask) {
12774         unsigned LHSInNElts =
12775           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12776         std::vector<Constant*> Elts;
12777         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12778           if (NewMask[i] >= LHSInNElts*2) {
12779             Elts.push_back(Context->getUndef(Type::Int32Ty));
12780           } else {
12781             Elts.push_back(Context->getConstantInt(Type::Int32Ty, NewMask[i]));
12782           }
12783         }
12784         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12785                                      LHSSVI->getOperand(1),
12786                                      Context->getConstantVector(Elts));
12787       }
12788     }
12789   }
12790
12791   return MadeChange ? &SVI : 0;
12792 }
12793
12794
12795
12796
12797 /// TryToSinkInstruction - Try to move the specified instruction from its
12798 /// current block into the beginning of DestBlock, which can only happen if it's
12799 /// safe to move the instruction past all of the instructions between it and the
12800 /// end of its block.
12801 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12802   assert(I->hasOneUse() && "Invariants didn't hold!");
12803
12804   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12805   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12806     return false;
12807
12808   // Do not sink alloca instructions out of the entry block.
12809   if (isa<AllocaInst>(I) && I->getParent() ==
12810         &DestBlock->getParent()->getEntryBlock())
12811     return false;
12812
12813   // We can only sink load instructions if there is nothing between the load and
12814   // the end of block that could change the value.
12815   if (I->mayReadFromMemory()) {
12816     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12817          Scan != E; ++Scan)
12818       if (Scan->mayWriteToMemory())
12819         return false;
12820   }
12821
12822   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12823
12824   CopyPrecedingStopPoint(I, InsertPos);
12825   I->moveBefore(InsertPos);
12826   ++NumSunkInst;
12827   return true;
12828 }
12829
12830
12831 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12832 /// all reachable code to the worklist.
12833 ///
12834 /// This has a couple of tricks to make the code faster and more powerful.  In
12835 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12836 /// them to the worklist (this significantly speeds up instcombine on code where
12837 /// many instructions are dead or constant).  Additionally, if we find a branch
12838 /// whose condition is a known constant, we only visit the reachable successors.
12839 ///
12840 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12841                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12842                                        InstCombiner &IC,
12843                                        const TargetData *TD) {
12844   SmallVector<BasicBlock*, 256> Worklist;
12845   Worklist.push_back(BB);
12846
12847   while (!Worklist.empty()) {
12848     BB = Worklist.back();
12849     Worklist.pop_back();
12850     
12851     // We have now visited this block!  If we've already been here, ignore it.
12852     if (!Visited.insert(BB)) continue;
12853
12854     DbgInfoIntrinsic *DBI_Prev = NULL;
12855     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12856       Instruction *Inst = BBI++;
12857       
12858       // DCE instruction if trivially dead.
12859       if (isInstructionTriviallyDead(Inst)) {
12860         ++NumDeadInst;
12861         DOUT << "IC: DCE: " << *Inst;
12862         Inst->eraseFromParent();
12863         continue;
12864       }
12865       
12866       // ConstantProp instruction if trivially constant.
12867       if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12868         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12869         Inst->replaceAllUsesWith(C);
12870         ++NumConstProp;
12871         Inst->eraseFromParent();
12872         continue;
12873       }
12874      
12875       // If there are two consecutive llvm.dbg.stoppoint calls then
12876       // it is likely that the optimizer deleted code in between these
12877       // two intrinsics. 
12878       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12879       if (DBI_Next) {
12880         if (DBI_Prev
12881             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12882             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12883           IC.RemoveFromWorkList(DBI_Prev);
12884           DBI_Prev->eraseFromParent();
12885         }
12886         DBI_Prev = DBI_Next;
12887       } else {
12888         DBI_Prev = 0;
12889       }
12890
12891       IC.AddToWorkList(Inst);
12892     }
12893
12894     // Recursively visit successors.  If this is a branch or switch on a
12895     // constant, only visit the reachable successor.
12896     TerminatorInst *TI = BB->getTerminator();
12897     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12898       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12899         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12900         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12901         Worklist.push_back(ReachableBB);
12902         continue;
12903       }
12904     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12905       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12906         // See if this is an explicit destination.
12907         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12908           if (SI->getCaseValue(i) == Cond) {
12909             BasicBlock *ReachableBB = SI->getSuccessor(i);
12910             Worklist.push_back(ReachableBB);
12911             continue;
12912           }
12913         
12914         // Otherwise it is the default destination.
12915         Worklist.push_back(SI->getSuccessor(0));
12916         continue;
12917       }
12918     }
12919     
12920     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12921       Worklist.push_back(TI->getSuccessor(i));
12922   }
12923 }
12924
12925 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12926   bool Changed = false;
12927   TD = &getAnalysis<TargetData>();
12928   
12929   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12930              << F.getNameStr() << "\n");
12931
12932   {
12933     // Do a depth-first traversal of the function, populate the worklist with
12934     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12935     // track of which blocks we visit.
12936     SmallPtrSet<BasicBlock*, 64> Visited;
12937     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12938
12939     // Do a quick scan over the function.  If we find any blocks that are
12940     // unreachable, remove any instructions inside of them.  This prevents
12941     // the instcombine code from having to deal with some bad special cases.
12942     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12943       if (!Visited.count(BB)) {
12944         Instruction *Term = BB->getTerminator();
12945         while (Term != BB->begin()) {   // Remove instrs bottom-up
12946           BasicBlock::iterator I = Term; --I;
12947
12948           DOUT << "IC: DCE: " << *I;
12949           // A debug intrinsic shouldn't force another iteration if we weren't
12950           // going to do one without it.
12951           if (!isa<DbgInfoIntrinsic>(I)) {
12952             ++NumDeadInst;
12953             Changed = true;
12954           }
12955           if (!I->use_empty())
12956             I->replaceAllUsesWith(Context->getUndef(I->getType()));
12957           I->eraseFromParent();
12958         }
12959       }
12960   }
12961
12962   while (!Worklist.empty()) {
12963     Instruction *I = RemoveOneFromWorkList();
12964     if (I == 0) continue;  // skip null values.
12965
12966     // Check to see if we can DCE the instruction.
12967     if (isInstructionTriviallyDead(I)) {
12968       // Add operands to the worklist.
12969       if (I->getNumOperands() < 4)
12970         AddUsesToWorkList(*I);
12971       ++NumDeadInst;
12972
12973       DOUT << "IC: DCE: " << *I;
12974
12975       I->eraseFromParent();
12976       RemoveFromWorkList(I);
12977       Changed = true;
12978       continue;
12979     }
12980
12981     // Instruction isn't dead, see if we can constant propagate it.
12982     if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12983       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12984
12985       // Add operands to the worklist.
12986       AddUsesToWorkList(*I);
12987       ReplaceInstUsesWith(*I, C);
12988
12989       ++NumConstProp;
12990       I->eraseFromParent();
12991       RemoveFromWorkList(I);
12992       Changed = true;
12993       continue;
12994     }
12995
12996     if (TD &&
12997         (I->getType()->getTypeID() == Type::VoidTyID ||
12998          I->isTrapping())) {
12999       // See if we can constant fold its operands.
13000       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13001         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
13002           if (Constant *NewC = ConstantFoldConstantExpression(CE,   
13003                                   F.getContext(), TD))
13004             if (NewC != CE) {
13005               i->set(NewC);
13006               Changed = true;
13007             }
13008     }
13009
13010     // See if we can trivially sink this instruction to a successor basic block.
13011     if (I->hasOneUse()) {
13012       BasicBlock *BB = I->getParent();
13013       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13014       if (UserParent != BB) {
13015         bool UserIsSuccessor = false;
13016         // See if the user is one of our successors.
13017         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13018           if (*SI == UserParent) {
13019             UserIsSuccessor = true;
13020             break;
13021           }
13022
13023         // If the user is one of our immediate successors, and if that successor
13024         // only has us as a predecessors (we'd have to split the critical edge
13025         // otherwise), we can keep going.
13026         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13027             next(pred_begin(UserParent)) == pred_end(UserParent))
13028           // Okay, the CFG is simple enough, try to sink this instruction.
13029           Changed |= TryToSinkInstruction(I, UserParent);
13030       }
13031     }
13032
13033     // Now that we have an instruction, try combining it to simplify it...
13034 #ifndef NDEBUG
13035     std::string OrigI;
13036 #endif
13037     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
13038     if (Instruction *Result = visit(*I)) {
13039       ++NumCombined;
13040       // Should we replace the old instruction with a new one?
13041       if (Result != I) {
13042         DOUT << "IC: Old = " << *I
13043              << "    New = " << *Result;
13044
13045         // Everything uses the new instruction now.
13046         I->replaceAllUsesWith(Result);
13047
13048         // Push the new instruction and any users onto the worklist.
13049         AddToWorkList(Result);
13050         AddUsersToWorkList(*Result);
13051
13052         // Move the name to the new instruction first.
13053         Result->takeName(I);
13054
13055         // Insert the new instruction into the basic block...
13056         BasicBlock *InstParent = I->getParent();
13057         BasicBlock::iterator InsertPos = I;
13058
13059         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
13060           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13061             ++InsertPos;
13062
13063         InstParent->getInstList().insert(InsertPos, Result);
13064
13065         // Make sure that we reprocess all operands now that we reduced their
13066         // use counts.
13067         AddUsesToWorkList(*I);
13068
13069         // Instructions can end up on the worklist more than once.  Make sure
13070         // we do not process an instruction that has been deleted.
13071         RemoveFromWorkList(I);
13072
13073         // Erase the old instruction.
13074         InstParent->getInstList().erase(I);
13075       } else {
13076 #ifndef NDEBUG
13077         DOUT << "IC: Mod = " << OrigI
13078              << "    New = " << *I;
13079 #endif
13080
13081         // If the instruction was modified, it's possible that it is now dead.
13082         // if so, remove it.
13083         if (isInstructionTriviallyDead(I)) {
13084           // Make sure we process all operands now that we are reducing their
13085           // use counts.
13086           AddUsesToWorkList(*I);
13087
13088           // Instructions may end up in the worklist more than once.  Erase all
13089           // occurrences of this instruction.
13090           RemoveFromWorkList(I);
13091           I->eraseFromParent();
13092         } else {
13093           AddToWorkList(I);
13094           AddUsersToWorkList(*I);
13095         }
13096       }
13097       Changed = true;
13098     }
13099   }
13100
13101   assert(WorklistMap.empty() && "Worklist empty, but map not?");
13102     
13103   // Do an explicit clear, this shrinks the map if needed.
13104   WorklistMap.clear();
13105   return Changed;
13106 }
13107
13108
13109 bool InstCombiner::runOnFunction(Function &F) {
13110   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13111   
13112   bool EverMadeChange = false;
13113
13114   // Iterate while there is work to do.
13115   unsigned Iteration = 0;
13116   while (DoOneIteration(F, Iteration++))
13117     EverMadeChange = true;
13118   return EverMadeChange;
13119 }
13120
13121 FunctionPass *llvm::createInstructionCombiningPass() {
13122   return new InstCombiner();
13123 }