Move more functionality over to LLVMContext.
[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(*Context, V) ||
414         BinaryOperator::isFNeg(*Context, 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(*Context, 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(*Context, 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(i1) - 1  ->  select i1, 0, -1
2105       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2106         if (CI->isAllOnesValue() &&
2107             ZI->getOperand(0)->getType() == Type::Int1Ty)
2108           return SelectInst::Create(ZI->getOperand(0),
2109                                     Context->getNullValue(I.getType()),
2110                               Context->getAllOnesValue(I.getType()));
2111     }
2112
2113     if (isa<PHINode>(LHS))
2114       if (Instruction *NV = FoldOpIntoPhi(I))
2115         return NV;
2116     
2117     ConstantInt *XorRHS = 0;
2118     Value *XorLHS = 0;
2119     if (isa<ConstantInt>(RHSC) &&
2120         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)), *Context)) {
2121       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2122       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2123       
2124       uint32_t Size = TySizeBits / 2;
2125       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2126       APInt CFF80Val(-C0080Val);
2127       do {
2128         if (TySizeBits > Size) {
2129           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2130           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2131           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2132               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2133             // This is a sign extend if the top bits are known zero.
2134             if (!MaskedValueIsZero(XorLHS, 
2135                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2136               Size = 0;  // Not a sign ext, but can't be any others either.
2137             break;
2138           }
2139         }
2140         Size >>= 1;
2141         C0080Val = APIntOps::lshr(C0080Val, Size);
2142         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2143       } while (Size >= 1);
2144       
2145       // FIXME: This shouldn't be necessary. When the backends can handle types
2146       // with funny bit widths then this switch statement should be removed. It
2147       // is just here to get the size of the "middle" type back up to something
2148       // that the back ends can handle.
2149       const Type *MiddleType = 0;
2150       switch (Size) {
2151         default: break;
2152         case 32: MiddleType = Type::Int32Ty; break;
2153         case 16: MiddleType = Type::Int16Ty; break;
2154         case  8: MiddleType = Type::Int8Ty; break;
2155       }
2156       if (MiddleType) {
2157         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2158         InsertNewInstBefore(NewTrunc, I);
2159         return new SExtInst(NewTrunc, I.getType(), I.getName());
2160       }
2161     }
2162   }
2163
2164   if (I.getType() == Type::Int1Ty)
2165     return BinaryOperator::CreateXor(LHS, RHS);
2166
2167   // X + X --> X << 1
2168   if (I.getType()->isInteger()) {
2169     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2170       return Result;
2171
2172     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2173       if (RHSI->getOpcode() == Instruction::Sub)
2174         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2175           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2176     }
2177     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2178       if (LHSI->getOpcode() == Instruction::Sub)
2179         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2180           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2181     }
2182   }
2183
2184   // -A + B  -->  B - A
2185   // -A + -B  -->  -(A + B)
2186   if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
2187     if (LHS->getType()->isIntOrIntVector()) {
2188       if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
2189         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2190         InsertNewInstBefore(NewAdd, I);
2191         return BinaryOperator::CreateNeg(*Context, NewAdd);
2192       }
2193     }
2194     
2195     return BinaryOperator::CreateSub(RHS, LHSV);
2196   }
2197
2198   // A + -B  -->  A - B
2199   if (!isa<Constant>(RHS))
2200     if (Value *V = dyn_castNegVal(RHS, Context))
2201       return BinaryOperator::CreateSub(LHS, V);
2202
2203
2204   ConstantInt *C2;
2205   if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
2206     if (X == RHS)   // X*C + X --> X * (C+1)
2207       return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
2208
2209     // X*C1 + X*C2 --> X * (C1+C2)
2210     ConstantInt *C1;
2211     if (X == dyn_castFoldableMul(RHS, C1, Context))
2212       return BinaryOperator::CreateMul(X, Context->getConstantExprAdd(C1, C2));
2213   }
2214
2215   // X + X*C --> X * (C+1)
2216   if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2217     return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
2218
2219   // X + ~X --> -1   since   ~X = -X-1
2220   if (dyn_castNotVal(LHS, Context) == RHS ||
2221       dyn_castNotVal(RHS, Context) == LHS)
2222     return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
2223   
2224
2225   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2226   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)), *Context))
2227     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
2228       return R;
2229   
2230   // A+B --> A|B iff A and B have no bits set in common.
2231   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2232     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2233     APInt LHSKnownOne(IT->getBitWidth(), 0);
2234     APInt LHSKnownZero(IT->getBitWidth(), 0);
2235     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2236     if (LHSKnownZero != 0) {
2237       APInt RHSKnownOne(IT->getBitWidth(), 0);
2238       APInt RHSKnownZero(IT->getBitWidth(), 0);
2239       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2240       
2241       // No bits in common -> bitwise or.
2242       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2243         return BinaryOperator::CreateOr(LHS, RHS);
2244     }
2245   }
2246
2247   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2248   if (I.getType()->isIntOrIntVector()) {
2249     Value *W, *X, *Y, *Z;
2250     if (match(LHS, m_Mul(m_Value(W), m_Value(X)), *Context) &&
2251         match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
2252       if (W != Y) {
2253         if (W == Z) {
2254           std::swap(Y, Z);
2255         } else if (Y == X) {
2256           std::swap(W, X);
2257         } else if (X == Z) {
2258           std::swap(Y, Z);
2259           std::swap(W, X);
2260         }
2261       }
2262
2263       if (W == Y) {
2264         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2265                                                             LHS->getName()), I);
2266         return BinaryOperator::CreateMul(W, NewAdd);
2267       }
2268     }
2269   }
2270
2271   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2272     Value *X = 0;
2273     if (match(LHS, m_Not(m_Value(X)), *Context))    // ~X + C --> (C-1) - X
2274       return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
2275
2276     // (X & FF00) + xx00  -> (X+xx00) & FF00
2277     if (LHS->hasOneUse() &&
2278         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
2279       Constant *Anded = Context->getConstantExprAnd(CRHS, C2);
2280       if (Anded == CRHS) {
2281         // See if all bits from the first bit set in the Add RHS up are included
2282         // in the mask.  First, get the rightmost bit.
2283         const APInt& AddRHSV = CRHS->getValue();
2284
2285         // Form a mask of all bits from the lowest bit added through the top.
2286         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2287
2288         // See if the and mask includes all of these bits.
2289         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2290
2291         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2292           // Okay, the xform is safe.  Insert the new add pronto.
2293           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2294                                                             LHS->getName()), I);
2295           return BinaryOperator::CreateAnd(NewAdd, C2);
2296         }
2297       }
2298     }
2299
2300     // Try to fold constant add into select arguments.
2301     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2302       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2303         return R;
2304   }
2305
2306   // add (cast *A to intptrtype) B -> 
2307   //   cast (GEP (cast *A to i8*) B)  -->  intptrtype
2308   {
2309     CastInst *CI = dyn_cast<CastInst>(LHS);
2310     Value *Other = RHS;
2311     if (!CI) {
2312       CI = dyn_cast<CastInst>(RHS);
2313       Other = LHS;
2314     }
2315     if (CI && CI->getType()->isSized() && 
2316         (CI->getType()->getScalarSizeInBits() ==
2317          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2318         && isa<PointerType>(CI->getOperand(0)->getType())) {
2319       unsigned AS =
2320         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2321       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2322                                   Context->getPointerType(Type::Int8Ty, AS), I);
2323       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2324       return new PtrToIntInst(I2, CI->getType());
2325     }
2326   }
2327   
2328   // add (select X 0 (sub n A)) A  -->  select X A n
2329   {
2330     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2331     Value *A = RHS;
2332     if (!SI) {
2333       SI = dyn_cast<SelectInst>(RHS);
2334       A = LHS;
2335     }
2336     if (SI && SI->hasOneUse()) {
2337       Value *TV = SI->getTrueValue();
2338       Value *FV = SI->getFalseValue();
2339       Value *N;
2340
2341       // Can we fold the add into the argument of the select?
2342       // We check both true and false select arguments for a matching subtract.
2343       if (match(FV, m_Zero(), *Context) &&
2344           match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2345         // Fold the add into the true select value.
2346         return SelectInst::Create(SI->getCondition(), N, A);
2347       if (match(TV, m_Zero(), *Context) &&
2348           match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
2349         // Fold the add into the false select value.
2350         return SelectInst::Create(SI->getCondition(), A, N);
2351     }
2352   }
2353
2354   // Check for (add (sext x), y), see if we can merge this into an
2355   // integer add followed by a sext.
2356   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2357     // (add (sext x), cst) --> (sext (add x, cst'))
2358     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2359       Constant *CI = 
2360         Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
2361       if (LHSConv->hasOneUse() &&
2362           Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
2363           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2364         // Insert the new, smaller add.
2365         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2366                                                         CI, "addconv");
2367         InsertNewInstBefore(NewAdd, I);
2368         return new SExtInst(NewAdd, I.getType());
2369       }
2370     }
2371     
2372     // (add (sext x), (sext y)) --> (sext (add int x, y))
2373     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2374       // Only do this if x/y have the same type, if at last one of them has a
2375       // single use (so we don't increase the number of sexts), and if the
2376       // integer add will not overflow.
2377       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2378           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2379           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2380                                    RHSConv->getOperand(0))) {
2381         // Insert the new integer add.
2382         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2383                                                         RHSConv->getOperand(0),
2384                                                         "addconv");
2385         InsertNewInstBefore(NewAdd, I);
2386         return new SExtInst(NewAdd, I.getType());
2387       }
2388     }
2389   }
2390
2391   return Changed ? &I : 0;
2392 }
2393
2394 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2395   bool Changed = SimplifyCommutative(I);
2396   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2397
2398   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2399     // X + 0 --> X
2400     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2401       if (CFP->isExactlyValue(Context->getConstantFPNegativeZero
2402                               (I.getType())->getValueAPF()))
2403         return ReplaceInstUsesWith(I, LHS);
2404     }
2405
2406     if (isa<PHINode>(LHS))
2407       if (Instruction *NV = FoldOpIntoPhi(I))
2408         return NV;
2409   }
2410
2411   // -A + B  -->  B - A
2412   // -A + -B  -->  -(A + B)
2413   if (Value *LHSV = dyn_castFNegVal(LHS, Context))
2414     return BinaryOperator::CreateFSub(RHS, LHSV);
2415
2416   // A + -B  -->  A - B
2417   if (!isa<Constant>(RHS))
2418     if (Value *V = dyn_castFNegVal(RHS, Context))
2419       return BinaryOperator::CreateFSub(LHS, V);
2420
2421   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2422   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2423     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2424       return ReplaceInstUsesWith(I, LHS);
2425
2426   // Check for (add double (sitofp x), y), see if we can merge this into an
2427   // integer add followed by a promotion.
2428   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2429     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2430     // ... if the constant fits in the integer value.  This is useful for things
2431     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2432     // requires a constant pool load, and generally allows the add to be better
2433     // instcombined.
2434     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2435       Constant *CI = 
2436       Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
2437       if (LHSConv->hasOneUse() &&
2438           Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
2439           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2440         // Insert the new integer add.
2441         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2442                                                         CI, "addconv");
2443         InsertNewInstBefore(NewAdd, I);
2444         return new SIToFPInst(NewAdd, I.getType());
2445       }
2446     }
2447     
2448     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2449     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2450       // Only do this if x/y have the same type, if at last one of them has a
2451       // single use (so we don't increase the number of int->fp conversions),
2452       // and if the integer add will not overflow.
2453       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2454           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2455           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2456                                    RHSConv->getOperand(0))) {
2457         // Insert the new integer add.
2458         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2459                                                         RHSConv->getOperand(0),
2460                                                         "addconv");
2461         InsertNewInstBefore(NewAdd, I);
2462         return new SIToFPInst(NewAdd, I.getType());
2463       }
2464     }
2465   }
2466   
2467   return Changed ? &I : 0;
2468 }
2469
2470 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2471   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2472
2473   if (Op0 == Op1)                        // sub X, X  -> 0
2474     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2475
2476   // If this is a 'B = x-(-A)', change to B = x+A...
2477   if (Value *V = dyn_castNegVal(Op1, Context))
2478     return BinaryOperator::CreateAdd(Op0, V);
2479
2480   if (isa<UndefValue>(Op0))
2481     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2482   if (isa<UndefValue>(Op1))
2483     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2484
2485   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2486     // Replace (-1 - A) with (~A)...
2487     if (C->isAllOnesValue())
2488       return BinaryOperator::CreateNot(*Context, Op1);
2489
2490     // C - ~X == X + (1+C)
2491     Value *X = 0;
2492     if (match(Op1, m_Not(m_Value(X)), *Context))
2493       return BinaryOperator::CreateAdd(X, AddOne(C, Context));
2494
2495     // -(X >>u 31) -> (X >>s 31)
2496     // -(X >>s 31) -> (X >>u 31)
2497     if (C->isZero()) {
2498       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2499         if (SI->getOpcode() == Instruction::LShr) {
2500           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2501             // Check to see if we are shifting out everything but the sign bit.
2502             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2503                 SI->getType()->getPrimitiveSizeInBits()-1) {
2504               // Ok, the transformation is safe.  Insert AShr.
2505               return BinaryOperator::Create(Instruction::AShr, 
2506                                           SI->getOperand(0), CU, SI->getName());
2507             }
2508           }
2509         }
2510         else if (SI->getOpcode() == Instruction::AShr) {
2511           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2512             // Check to see if we are shifting out everything but the sign bit.
2513             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2514                 SI->getType()->getPrimitiveSizeInBits()-1) {
2515               // Ok, the transformation is safe.  Insert LShr. 
2516               return BinaryOperator::CreateLShr(
2517                                           SI->getOperand(0), CU, SI->getName());
2518             }
2519           }
2520         }
2521       }
2522     }
2523
2524     // Try to fold constant sub into select arguments.
2525     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2526       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2527         return R;
2528   }
2529
2530   if (I.getType() == Type::Int1Ty)
2531     return BinaryOperator::CreateXor(Op0, Op1);
2532
2533   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2534     if (Op1I->getOpcode() == Instruction::Add) {
2535       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2536         return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(1),
2537                                          I.getName());
2538       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2539         return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(0), 
2540                                          I.getName());
2541       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2542         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2543           // C1-(X+C2) --> (C1-C2)-X
2544           return BinaryOperator::CreateSub(
2545             Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
2546       }
2547     }
2548
2549     if (Op1I->hasOneUse()) {
2550       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2551       // is not used by anyone else...
2552       //
2553       if (Op1I->getOpcode() == Instruction::Sub) {
2554         // Swap the two operands of the subexpr...
2555         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2556         Op1I->setOperand(0, IIOp1);
2557         Op1I->setOperand(1, IIOp0);
2558
2559         // Create the new top level add instruction...
2560         return BinaryOperator::CreateAdd(Op0, Op1);
2561       }
2562
2563       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2564       //
2565       if (Op1I->getOpcode() == Instruction::And &&
2566           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2567         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2568
2569         Value *NewNot =
2570           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, 
2571                                                         OtherOp, "B.not"), I);
2572         return BinaryOperator::CreateAnd(Op0, NewNot);
2573       }
2574
2575       // 0 - (X sdiv C)  -> (X sdiv -C)
2576       if (Op1I->getOpcode() == Instruction::SDiv)
2577         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2578           if (CSI->isZero())
2579             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2580               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2581                                           Context->getConstantExprNeg(DivRHS));
2582
2583       // X - X*C --> X * (1-C)
2584       ConstantInt *C2 = 0;
2585       if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2586         Constant *CP1 = 
2587           Context->getConstantExprSub(Context->getConstantInt(I.getType(), 1),
2588                                              C2);
2589         return BinaryOperator::CreateMul(Op0, CP1);
2590       }
2591     }
2592   }
2593
2594   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2595     if (Op0I->getOpcode() == Instruction::Add) {
2596       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2597         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2598       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2599         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2600     } else if (Op0I->getOpcode() == Instruction::Sub) {
2601       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2602         return BinaryOperator::CreateNeg(*Context, Op0I->getOperand(1),
2603                                          I.getName());
2604     }
2605   }
2606
2607   ConstantInt *C1;
2608   if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
2609     if (X == Op1)  // X*C - X --> X * (C-1)
2610       return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
2611
2612     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2613     if (X == dyn_castFoldableMul(Op1, C2, Context))
2614       return BinaryOperator::CreateMul(X, Context->getConstantExprSub(C1, C2));
2615   }
2616   return 0;
2617 }
2618
2619 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2620   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2621
2622   // If this is a 'B = x-(-A)', change to B = x+A...
2623   if (Value *V = dyn_castFNegVal(Op1, Context))
2624     return BinaryOperator::CreateFAdd(Op0, V);
2625
2626   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2627     if (Op1I->getOpcode() == Instruction::FAdd) {
2628       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2629         return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(1),
2630                                           I.getName());
2631       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2632         return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(0),
2633                                           I.getName());
2634     }
2635   }
2636
2637   return 0;
2638 }
2639
2640 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2641 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2642 /// TrueIfSigned if the result of the comparison is true when the input value is
2643 /// signed.
2644 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2645                            bool &TrueIfSigned) {
2646   switch (pred) {
2647   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2648     TrueIfSigned = true;
2649     return RHS->isZero();
2650   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2651     TrueIfSigned = true;
2652     return RHS->isAllOnesValue();
2653   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2654     TrueIfSigned = false;
2655     return RHS->isAllOnesValue();
2656   case ICmpInst::ICMP_UGT:
2657     // True if LHS u> RHS and RHS == high-bit-mask - 1
2658     TrueIfSigned = true;
2659     return RHS->getValue() ==
2660       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2661   case ICmpInst::ICMP_UGE: 
2662     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2663     TrueIfSigned = true;
2664     return RHS->getValue().isSignBit();
2665   default:
2666     return false;
2667   }
2668 }
2669
2670 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2671   bool Changed = SimplifyCommutative(I);
2672   Value *Op0 = I.getOperand(0);
2673
2674   // TODO: If Op1 is undef and Op0 is finite, return zero.
2675   if (!I.getType()->isFPOrFPVector() &&
2676       isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2677     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2678
2679   // Simplify mul instructions with a constant RHS...
2680   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2681     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2682
2683       // ((X << C1)*C2) == (X * (C2 << C1))
2684       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2685         if (SI->getOpcode() == Instruction::Shl)
2686           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2687             return BinaryOperator::CreateMul(SI->getOperand(0),
2688                                         Context->getConstantExprShl(CI, ShOp));
2689
2690       if (CI->isZero())
2691         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2692       if (CI->equalsInt(1))                  // X * 1  == X
2693         return ReplaceInstUsesWith(I, Op0);
2694       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2695         return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2696
2697       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2698       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2699         return BinaryOperator::CreateShl(Op0,
2700                  Context->getConstantInt(Op0->getType(), Val.logBase2()));
2701       }
2702     } else if (isa<VectorType>(Op1->getType())) {
2703       // TODO: If Op1 is all zeros and Op0 is all finite, return all zeros.
2704
2705       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2706         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2707           return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
2708
2709         // As above, vector X*splat(1.0) -> X in all defined cases.
2710         if (Constant *Splat = Op1V->getSplatValue()) {
2711           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2712             if (CI->equalsInt(1))
2713               return ReplaceInstUsesWith(I, Op0);
2714         }
2715       }
2716     }
2717     
2718     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2719       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2720           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2721         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2722         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2723                                                      Op1, "tmp");
2724         InsertNewInstBefore(Add, I);
2725         Value *C1C2 = Context->getConstantExprMul(Op1, 
2726                                            cast<Constant>(Op0I->getOperand(1)));
2727         return BinaryOperator::CreateAdd(Add, C1C2);
2728         
2729       }
2730
2731     // Try to fold constant mul into select arguments.
2732     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2733       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2734         return R;
2735
2736     if (isa<PHINode>(Op0))
2737       if (Instruction *NV = FoldOpIntoPhi(I))
2738         return NV;
2739   }
2740
2741   if (Value *Op0v = dyn_castNegVal(Op0, Context))     // -X * -Y = X*Y
2742     if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
2743       return BinaryOperator::CreateMul(Op0v, Op1v);
2744
2745   // (X / Y) *  Y = X - (X % Y)
2746   // (X / Y) * -Y = (X % Y) - X
2747   {
2748     Value *Op1 = I.getOperand(1);
2749     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2750     if (!BO ||
2751         (BO->getOpcode() != Instruction::UDiv && 
2752          BO->getOpcode() != Instruction::SDiv)) {
2753       Op1 = Op0;
2754       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2755     }
2756     Value *Neg = dyn_castNegVal(Op1, Context);
2757     if (BO && BO->hasOneUse() &&
2758         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2759         (BO->getOpcode() == Instruction::UDiv ||
2760          BO->getOpcode() == Instruction::SDiv)) {
2761       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2762
2763       Instruction *Rem;
2764       if (BO->getOpcode() == Instruction::UDiv)
2765         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2766       else
2767         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2768
2769       InsertNewInstBefore(Rem, I);
2770       Rem->takeName(BO);
2771
2772       if (Op1BO == Op1)
2773         return BinaryOperator::CreateSub(Op0BO, Rem);
2774       else
2775         return BinaryOperator::CreateSub(Rem, Op0BO);
2776     }
2777   }
2778
2779   if (I.getType() == Type::Int1Ty)
2780     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2781
2782   // If one of the operands of the multiply is a cast from a boolean value, then
2783   // we know the bool is either zero or one, so this is a 'masking' multiply.
2784   // See if we can simplify things based on how the boolean was originally
2785   // formed.
2786   CastInst *BoolCast = 0;
2787   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2788     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2789       BoolCast = CI;
2790   if (!BoolCast)
2791     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2792       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2793         BoolCast = CI;
2794   if (BoolCast) {
2795     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2796       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2797       const Type *SCOpTy = SCIOp0->getType();
2798       bool TIS = false;
2799       
2800       // If the icmp is true iff the sign bit of X is set, then convert this
2801       // multiply into a shift/and combination.
2802       if (isa<ConstantInt>(SCIOp1) &&
2803           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2804           TIS) {
2805         // Shift the X value right to turn it into "all signbits".
2806         Constant *Amt = Context->getConstantInt(SCIOp0->getType(),
2807                                           SCOpTy->getPrimitiveSizeInBits()-1);
2808         Value *V =
2809           InsertNewInstBefore(
2810             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2811                                             BoolCast->getOperand(0)->getName()+
2812                                             ".mask"), I);
2813
2814         // If the multiply type is not the same as the source type, sign extend
2815         // or truncate to the multiply type.
2816         if (I.getType() != V->getType()) {
2817           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2818           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2819           Instruction::CastOps opcode = 
2820             (SrcBits == DstBits ? Instruction::BitCast : 
2821              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2822           V = InsertCastBefore(opcode, V, I.getType(), I);
2823         }
2824
2825         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2826         return BinaryOperator::CreateAnd(V, OtherOp);
2827       }
2828     }
2829   }
2830
2831   return Changed ? &I : 0;
2832 }
2833
2834 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2835   bool Changed = SimplifyCommutative(I);
2836   Value *Op0 = I.getOperand(0);
2837
2838   // Simplify mul instructions with a constant RHS...
2839   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2840     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2841       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2842       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2843       if (Op1F->isExactlyValue(1.0))
2844         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2845     } else if (isa<VectorType>(Op1->getType())) {
2846       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2847         // As above, vector X*splat(1.0) -> X in all defined cases.
2848         if (Constant *Splat = Op1V->getSplatValue()) {
2849           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2850             if (F->isExactlyValue(1.0))
2851               return ReplaceInstUsesWith(I, Op0);
2852         }
2853       }
2854     }
2855
2856     // Try to fold constant mul into select arguments.
2857     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2858       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2859         return R;
2860
2861     if (isa<PHINode>(Op0))
2862       if (Instruction *NV = FoldOpIntoPhi(I))
2863         return NV;
2864   }
2865
2866   if (Value *Op0v = dyn_castFNegVal(Op0, Context))     // -X * -Y = X*Y
2867     if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
2868       return BinaryOperator::CreateFMul(Op0v, Op1v);
2869
2870   return Changed ? &I : 0;
2871 }
2872
2873 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2874 /// instruction.
2875 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2876   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2877   
2878   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2879   int NonNullOperand = -1;
2880   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2881     if (ST->isNullValue())
2882       NonNullOperand = 2;
2883   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2884   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2885     if (ST->isNullValue())
2886       NonNullOperand = 1;
2887   
2888   if (NonNullOperand == -1)
2889     return false;
2890   
2891   Value *SelectCond = SI->getOperand(0);
2892   
2893   // Change the div/rem to use 'Y' instead of the select.
2894   I.setOperand(1, SI->getOperand(NonNullOperand));
2895   
2896   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2897   // problem.  However, the select, or the condition of the select may have
2898   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2899   // propagate the known value for the select into other uses of it, and
2900   // propagate a known value of the condition into its other users.
2901   
2902   // If the select and condition only have a single use, don't bother with this,
2903   // early exit.
2904   if (SI->use_empty() && SelectCond->hasOneUse())
2905     return true;
2906   
2907   // Scan the current block backward, looking for other uses of SI.
2908   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2909   
2910   while (BBI != BBFront) {
2911     --BBI;
2912     // If we found a call to a function, we can't assume it will return, so
2913     // information from below it cannot be propagated above it.
2914     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2915       break;
2916     
2917     // Replace uses of the select or its condition with the known values.
2918     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2919          I != E; ++I) {
2920       if (*I == SI) {
2921         *I = SI->getOperand(NonNullOperand);
2922         AddToWorkList(BBI);
2923       } else if (*I == SelectCond) {
2924         *I = NonNullOperand == 1 ? Context->getConstantIntTrue() :
2925                                    Context->getConstantIntFalse();
2926         AddToWorkList(BBI);
2927       }
2928     }
2929     
2930     // If we past the instruction, quit looking for it.
2931     if (&*BBI == SI)
2932       SI = 0;
2933     if (&*BBI == SelectCond)
2934       SelectCond = 0;
2935     
2936     // If we ran out of things to eliminate, break out of the loop.
2937     if (SelectCond == 0 && SI == 0)
2938       break;
2939     
2940   }
2941   return true;
2942 }
2943
2944
2945 /// This function implements the transforms on div instructions that work
2946 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2947 /// used by the visitors to those instructions.
2948 /// @brief Transforms common to all three div instructions
2949 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2950   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2951
2952   // undef / X -> 0        for integer.
2953   // undef / X -> undef    for FP (the undef could be a snan).
2954   if (isa<UndefValue>(Op0)) {
2955     if (Op0->getType()->isFPOrFPVector())
2956       return ReplaceInstUsesWith(I, Op0);
2957     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2958   }
2959
2960   // X / undef -> undef
2961   if (isa<UndefValue>(Op1))
2962     return ReplaceInstUsesWith(I, Op1);
2963
2964   return 0;
2965 }
2966
2967 /// This function implements the transforms common to both integer division
2968 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2969 /// division instructions.
2970 /// @brief Common integer divide transforms
2971 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2972   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2973
2974   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2975   if (Op0 == Op1) {
2976     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2977       Constant *CI = Context->getConstantInt(Ty->getElementType(), 1);
2978       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2979       return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
2980     }
2981
2982     Constant *CI = Context->getConstantInt(I.getType(), 1);
2983     return ReplaceInstUsesWith(I, CI);
2984   }
2985   
2986   if (Instruction *Common = commonDivTransforms(I))
2987     return Common;
2988   
2989   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2990   // This does not apply for fdiv.
2991   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2992     return &I;
2993
2994   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2995     // div X, 1 == X
2996     if (RHS->equalsInt(1))
2997       return ReplaceInstUsesWith(I, Op0);
2998
2999     // (X / C1) / C2  -> X / (C1*C2)
3000     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3001       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3002         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3003           if (MultiplyOverflows(RHS, LHSRHS,
3004                                 I.getOpcode()==Instruction::SDiv, Context))
3005             return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3006           else 
3007             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
3008                                       Context->getConstantExprMul(RHS, LHSRHS));
3009         }
3010
3011     if (!RHS->isZero()) { // avoid X udiv 0
3012       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3013         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3014           return R;
3015       if (isa<PHINode>(Op0))
3016         if (Instruction *NV = FoldOpIntoPhi(I))
3017           return NV;
3018     }
3019   }
3020
3021   // 0 / X == 0, we don't need to preserve faults!
3022   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3023     if (LHS->equalsInt(0))
3024       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3025
3026   // It can't be division by zero, hence it must be division by one.
3027   if (I.getType() == Type::Int1Ty)
3028     return ReplaceInstUsesWith(I, Op0);
3029
3030   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3031     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3032       // div X, 1 == X
3033       if (X->isOne())
3034         return ReplaceInstUsesWith(I, Op0);
3035   }
3036
3037   return 0;
3038 }
3039
3040 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3041   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3042
3043   // Handle the integer div common cases
3044   if (Instruction *Common = commonIDivTransforms(I))
3045     return Common;
3046
3047   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3048     // X udiv C^2 -> X >> C
3049     // Check to see if this is an unsigned division with an exact power of 2,
3050     // if so, convert to a right shift.
3051     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3052       return BinaryOperator::CreateLShr(Op0, 
3053             Context->getConstantInt(Op0->getType(), C->getValue().logBase2()));
3054
3055     // X udiv C, where C >= signbit
3056     if (C->getValue().isNegative()) {
3057       Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3058                                                     ICmpInst::ICMP_ULT, Op0, C),
3059                                       I);
3060       return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3061                                 Context->getConstantInt(I.getType(), 1));
3062     }
3063   }
3064
3065   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3066   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3067     if (RHSI->getOpcode() == Instruction::Shl &&
3068         isa<ConstantInt>(RHSI->getOperand(0))) {
3069       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3070       if (C1.isPowerOf2()) {
3071         Value *N = RHSI->getOperand(1);
3072         const Type *NTy = N->getType();
3073         if (uint32_t C2 = C1.logBase2()) {
3074           Constant *C2V = Context->getConstantInt(NTy, C2);
3075           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3076         }
3077         return BinaryOperator::CreateLShr(Op0, N);
3078       }
3079     }
3080   }
3081   
3082   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3083   // where C1&C2 are powers of two.
3084   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3085     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3086       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3087         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3088         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3089           // Compute the shift amounts
3090           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3091           // Construct the "on true" case of the select
3092           Constant *TC = Context->getConstantInt(Op0->getType(), TSA);
3093           Instruction *TSI = BinaryOperator::CreateLShr(
3094                                                  Op0, TC, SI->getName()+".t");
3095           TSI = InsertNewInstBefore(TSI, I);
3096   
3097           // Construct the "on false" case of the select
3098           Constant *FC = Context->getConstantInt(Op0->getType(), FSA); 
3099           Instruction *FSI = BinaryOperator::CreateLShr(
3100                                                  Op0, FC, SI->getName()+".f");
3101           FSI = InsertNewInstBefore(FSI, I);
3102
3103           // construct the select instruction and return it.
3104           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3105         }
3106       }
3107   return 0;
3108 }
3109
3110 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3111   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3112
3113   // Handle the integer div common cases
3114   if (Instruction *Common = commonIDivTransforms(I))
3115     return Common;
3116
3117   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3118     // sdiv X, -1 == -X
3119     if (RHS->isAllOnesValue())
3120       return BinaryOperator::CreateNeg(*Context, Op0);
3121   }
3122
3123   // If the sign bits of both operands are zero (i.e. we can prove they are
3124   // unsigned inputs), turn this into a udiv.
3125   if (I.getType()->isInteger()) {
3126     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3127     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3128       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3129       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3130     }
3131   }      
3132   
3133   return 0;
3134 }
3135
3136 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3137   return commonDivTransforms(I);
3138 }
3139
3140 /// This function implements the transforms on rem instructions that work
3141 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3142 /// is used by the visitors to those instructions.
3143 /// @brief Transforms common to all three rem instructions
3144 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3145   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3146
3147   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3148     if (I.getType()->isFPOrFPVector())
3149       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3150     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3151   }
3152   if (isa<UndefValue>(Op1))
3153     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3154
3155   // Handle cases involving: rem X, (select Cond, Y, Z)
3156   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3157     return &I;
3158
3159   return 0;
3160 }
3161
3162 /// This function implements the transforms common to both integer remainder
3163 /// instructions (urem and srem). It is called by the visitors to those integer
3164 /// remainder instructions.
3165 /// @brief Common integer remainder transforms
3166 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3167   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3168
3169   if (Instruction *common = commonRemTransforms(I))
3170     return common;
3171
3172   // 0 % X == 0 for integer, we don't need to preserve faults!
3173   if (Constant *LHS = dyn_cast<Constant>(Op0))
3174     if (LHS->isNullValue())
3175       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3176
3177   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3178     // X % 0 == undef, we don't need to preserve faults!
3179     if (RHS->equalsInt(0))
3180       return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
3181     
3182     if (RHS->equalsInt(1))  // X % 1 == 0
3183       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3184
3185     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3186       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3187         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3188           return R;
3189       } else if (isa<PHINode>(Op0I)) {
3190         if (Instruction *NV = FoldOpIntoPhi(I))
3191           return NV;
3192       }
3193
3194       // See if we can fold away this rem instruction.
3195       if (SimplifyDemandedInstructionBits(I))
3196         return &I;
3197     }
3198   }
3199
3200   return 0;
3201 }
3202
3203 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3204   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3205
3206   if (Instruction *common = commonIRemTransforms(I))
3207     return common;
3208   
3209   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3210     // X urem C^2 -> X and C
3211     // Check to see if this is an unsigned remainder with an exact power of 2,
3212     // if so, convert to a bitwise and.
3213     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3214       if (C->getValue().isPowerOf2())
3215         return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
3216   }
3217
3218   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3219     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3220     if (RHSI->getOpcode() == Instruction::Shl &&
3221         isa<ConstantInt>(RHSI->getOperand(0))) {
3222       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3223         Constant *N1 = Context->getAllOnesValue(I.getType());
3224         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3225                                                                    "tmp"), I);
3226         return BinaryOperator::CreateAnd(Op0, Add);
3227       }
3228     }
3229   }
3230
3231   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3232   // where C1&C2 are powers of two.
3233   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3234     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3235       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3236         // STO == 0 and SFO == 0 handled above.
3237         if ((STO->getValue().isPowerOf2()) && 
3238             (SFO->getValue().isPowerOf2())) {
3239           Value *TrueAnd = InsertNewInstBefore(
3240             BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3241                                       SI->getName()+".t"), I);
3242           Value *FalseAnd = InsertNewInstBefore(
3243             BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3244                                       SI->getName()+".f"), I);
3245           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3246         }
3247       }
3248   }
3249   
3250   return 0;
3251 }
3252
3253 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3254   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3255
3256   // Handle the integer rem common cases
3257   if (Instruction *common = commonIRemTransforms(I))
3258     return common;
3259   
3260   if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
3261     if (!isa<Constant>(RHSNeg) ||
3262         (isa<ConstantInt>(RHSNeg) &&
3263          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3264       // X % -Y -> X % Y
3265       AddUsesToWorkList(I);
3266       I.setOperand(1, RHSNeg);
3267       return &I;
3268     }
3269
3270   // If the sign bits of both operands are zero (i.e. we can prove they are
3271   // unsigned inputs), turn this into a urem.
3272   if (I.getType()->isInteger()) {
3273     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3274     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3275       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3276       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3277     }
3278   }
3279
3280   // If it's a constant vector, flip any negative values positive.
3281   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3282     unsigned VWidth = RHSV->getNumOperands();
3283
3284     bool hasNegative = false;
3285     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3286       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3287         if (RHS->getValue().isNegative())
3288           hasNegative = true;
3289
3290     if (hasNegative) {
3291       std::vector<Constant *> Elts(VWidth);
3292       for (unsigned i = 0; i != VWidth; ++i) {
3293         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3294           if (RHS->getValue().isNegative())
3295             Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
3296           else
3297             Elts[i] = RHS;
3298         }
3299       }
3300
3301       Constant *NewRHSV = Context->getConstantVector(Elts);
3302       if (NewRHSV != RHSV) {
3303         AddUsesToWorkList(I);
3304         I.setOperand(1, NewRHSV);
3305         return &I;
3306       }
3307     }
3308   }
3309
3310   return 0;
3311 }
3312
3313 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3314   return commonRemTransforms(I);
3315 }
3316
3317 // isOneBitSet - Return true if there is exactly one bit set in the specified
3318 // constant.
3319 static bool isOneBitSet(const ConstantInt *CI) {
3320   return CI->getValue().isPowerOf2();
3321 }
3322
3323 // isHighOnes - Return true if the constant is of the form 1+0+.
3324 // This is the same as lowones(~X).
3325 static bool isHighOnes(const ConstantInt *CI) {
3326   return (~CI->getValue() + 1).isPowerOf2();
3327 }
3328
3329 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3330 /// are carefully arranged to allow folding of expressions such as:
3331 ///
3332 ///      (A < B) | (A > B) --> (A != B)
3333 ///
3334 /// Note that this is only valid if the first and second predicates have the
3335 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3336 ///
3337 /// Three bits are used to represent the condition, as follows:
3338 ///   0  A > B
3339 ///   1  A == B
3340 ///   2  A < B
3341 ///
3342 /// <=>  Value  Definition
3343 /// 000     0   Always false
3344 /// 001     1   A >  B
3345 /// 010     2   A == B
3346 /// 011     3   A >= B
3347 /// 100     4   A <  B
3348 /// 101     5   A != B
3349 /// 110     6   A <= B
3350 /// 111     7   Always true
3351 ///  
3352 static unsigned getICmpCode(const ICmpInst *ICI) {
3353   switch (ICI->getPredicate()) {
3354     // False -> 0
3355   case ICmpInst::ICMP_UGT: return 1;  // 001
3356   case ICmpInst::ICMP_SGT: return 1;  // 001
3357   case ICmpInst::ICMP_EQ:  return 2;  // 010
3358   case ICmpInst::ICMP_UGE: return 3;  // 011
3359   case ICmpInst::ICMP_SGE: return 3;  // 011
3360   case ICmpInst::ICMP_ULT: return 4;  // 100
3361   case ICmpInst::ICMP_SLT: return 4;  // 100
3362   case ICmpInst::ICMP_NE:  return 5;  // 101
3363   case ICmpInst::ICMP_ULE: return 6;  // 110
3364   case ICmpInst::ICMP_SLE: return 6;  // 110
3365     // True -> 7
3366   default:
3367     LLVM_UNREACHABLE("Invalid ICmp predicate!");
3368     return 0;
3369   }
3370 }
3371
3372 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3373 /// predicate into a three bit mask. It also returns whether it is an ordered
3374 /// predicate by reference.
3375 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3376   isOrdered = false;
3377   switch (CC) {
3378   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3379   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3380   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3381   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3382   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3383   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3384   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3385   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3386   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3387   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3388   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3389   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3390   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3391   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3392     // True -> 7
3393   default:
3394     // Not expecting FCMP_FALSE and FCMP_TRUE;
3395     LLVM_UNREACHABLE("Unexpected FCmp predicate!");
3396     return 0;
3397   }
3398 }
3399
3400 /// getICmpValue - This is the complement of getICmpCode, which turns an
3401 /// opcode and two operands into either a constant true or false, or a brand 
3402 /// new ICmp instruction. The sign is passed in to determine which kind
3403 /// of predicate to use in the new icmp instruction.
3404 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3405                            LLVMContext *Context) {
3406   switch (code) {
3407   default: LLVM_UNREACHABLE("Illegal ICmp code!");
3408   case  0: return Context->getConstantIntFalse();
3409   case  1: 
3410     if (sign)
3411       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
3412     else
3413       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3414   case  2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ,  LHS, RHS);
3415   case  3: 
3416     if (sign)
3417       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
3418     else
3419       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
3420   case  4: 
3421     if (sign)
3422       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
3423     else
3424       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3425   case  5: return new ICmpInst(*Context, ICmpInst::ICMP_NE,  LHS, RHS);
3426   case  6: 
3427     if (sign)
3428       return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
3429     else
3430       return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
3431   case  7: return Context->getConstantIntTrue();
3432   }
3433 }
3434
3435 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3436 /// opcode and two operands into either a FCmp instruction. isordered is passed
3437 /// in to determine which kind of predicate to use in the new fcmp instruction.
3438 static Value *getFCmpValue(bool isordered, unsigned code,
3439                            Value *LHS, Value *RHS, LLVMContext *Context) {
3440   switch (code) {
3441   default: LLVM_UNREACHABLE("Illegal FCmp code!");
3442   case  0:
3443     if (isordered)
3444       return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
3445     else
3446       return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
3447   case  1: 
3448     if (isordered)
3449       return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
3450     else
3451       return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
3452   case  2: 
3453     if (isordered)
3454       return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
3455     else
3456       return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
3457   case  3: 
3458     if (isordered)
3459       return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
3460     else
3461       return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
3462   case  4: 
3463     if (isordered)
3464       return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
3465     else
3466       return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
3467   case  5: 
3468     if (isordered)
3469       return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
3470     else
3471       return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
3472   case  6: 
3473     if (isordered)
3474       return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
3475     else
3476       return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
3477   case  7: return Context->getConstantIntTrue();
3478   }
3479 }
3480
3481 /// PredicatesFoldable - Return true if both predicates match sign or if at
3482 /// least one of them is an equality comparison (which is signless).
3483 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3484   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3485          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3486          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3487 }
3488
3489 namespace { 
3490 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3491 struct FoldICmpLogical {
3492   InstCombiner &IC;
3493   Value *LHS, *RHS;
3494   ICmpInst::Predicate pred;
3495   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3496     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3497       pred(ICI->getPredicate()) {}
3498   bool shouldApply(Value *V) const {
3499     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3500       if (PredicatesFoldable(pred, ICI->getPredicate()))
3501         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3502                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3503     return false;
3504   }
3505   Instruction *apply(Instruction &Log) const {
3506     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3507     if (ICI->getOperand(0) != LHS) {
3508       assert(ICI->getOperand(1) == LHS);
3509       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3510     }
3511
3512     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3513     unsigned LHSCode = getICmpCode(ICI);
3514     unsigned RHSCode = getICmpCode(RHSICI);
3515     unsigned Code;
3516     switch (Log.getOpcode()) {
3517     case Instruction::And: Code = LHSCode & RHSCode; break;
3518     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3519     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3520     default: LLVM_UNREACHABLE("Illegal logical opcode!"); return 0;
3521     }
3522
3523     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3524                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3525       
3526     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3527     if (Instruction *I = dyn_cast<Instruction>(RV))
3528       return I;
3529     // Otherwise, it's a constant boolean value...
3530     return IC.ReplaceInstUsesWith(Log, RV);
3531   }
3532 };
3533 } // end anonymous namespace
3534
3535 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3536 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3537 // guaranteed to be a binary operator.
3538 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3539                                     ConstantInt *OpRHS,
3540                                     ConstantInt *AndRHS,
3541                                     BinaryOperator &TheAnd) {
3542   Value *X = Op->getOperand(0);
3543   Constant *Together = 0;
3544   if (!Op->isShift())
3545     Together = Context->getConstantExprAnd(AndRHS, OpRHS);
3546
3547   switch (Op->getOpcode()) {
3548   case Instruction::Xor:
3549     if (Op->hasOneUse()) {
3550       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3551       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3552       InsertNewInstBefore(And, TheAnd);
3553       And->takeName(Op);
3554       return BinaryOperator::CreateXor(And, Together);
3555     }
3556     break;
3557   case Instruction::Or:
3558     if (Together == AndRHS) // (X | C) & C --> C
3559       return ReplaceInstUsesWith(TheAnd, AndRHS);
3560
3561     if (Op->hasOneUse() && Together != OpRHS) {
3562       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3563       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3564       InsertNewInstBefore(Or, TheAnd);
3565       Or->takeName(Op);
3566       return BinaryOperator::CreateAnd(Or, AndRHS);
3567     }
3568     break;
3569   case Instruction::Add:
3570     if (Op->hasOneUse()) {
3571       // Adding a one to a single bit bit-field should be turned into an XOR
3572       // of the bit.  First thing to check is to see if this AND is with a
3573       // single bit constant.
3574       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3575
3576       // If there is only one bit set...
3577       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3578         // Ok, at this point, we know that we are masking the result of the
3579         // ADD down to exactly one bit.  If the constant we are adding has
3580         // no bits set below this bit, then we can eliminate the ADD.
3581         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3582
3583         // Check to see if any bits below the one bit set in AndRHSV are set.
3584         if ((AddRHS & (AndRHSV-1)) == 0) {
3585           // If not, the only thing that can effect the output of the AND is
3586           // the bit specified by AndRHSV.  If that bit is set, the effect of
3587           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3588           // no effect.
3589           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3590             TheAnd.setOperand(0, X);
3591             return &TheAnd;
3592           } else {
3593             // Pull the XOR out of the AND.
3594             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3595             InsertNewInstBefore(NewAnd, TheAnd);
3596             NewAnd->takeName(Op);
3597             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3598           }
3599         }
3600       }
3601     }
3602     break;
3603
3604   case Instruction::Shl: {
3605     // We know that the AND will not produce any of the bits shifted in, so if
3606     // the anded constant includes them, clear them now!
3607     //
3608     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3609     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3610     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3611     ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShlMask);
3612
3613     if (CI->getValue() == ShlMask) { 
3614     // Masking out bits that the shift already masks
3615       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3616     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3617       TheAnd.setOperand(1, CI);
3618       return &TheAnd;
3619     }
3620     break;
3621   }
3622   case Instruction::LShr:
3623   {
3624     // We know that the AND will not produce any of the bits shifted in, so if
3625     // the anded constant includes them, clear them now!  This only applies to
3626     // unsigned shifts, because a signed shr may bring in set bits!
3627     //
3628     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3629     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3630     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3631     ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3632
3633     if (CI->getValue() == ShrMask) {   
3634     // Masking out bits that the shift already masks.
3635       return ReplaceInstUsesWith(TheAnd, Op);
3636     } else if (CI != AndRHS) {
3637       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3638       return &TheAnd;
3639     }
3640     break;
3641   }
3642   case Instruction::AShr:
3643     // Signed shr.
3644     // See if this is shifting in some sign extension, then masking it out
3645     // with an and.
3646     if (Op->hasOneUse()) {
3647       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3648       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3649       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3650       Constant *C = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3651       if (C == AndRHS) {          // Masking out bits shifted in.
3652         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3653         // Make the argument unsigned.
3654         Value *ShVal = Op->getOperand(0);
3655         ShVal = InsertNewInstBefore(
3656             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3657                                    Op->getName()), TheAnd);
3658         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3659       }
3660     }
3661     break;
3662   }
3663   return 0;
3664 }
3665
3666
3667 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3668 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3669 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3670 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3671 /// insert new instructions.
3672 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3673                                            bool isSigned, bool Inside, 
3674                                            Instruction &IB) {
3675   assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ? 
3676             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3677          "Lo is not <= Hi in range emission code!");
3678     
3679   if (Inside) {
3680     if (Lo == Hi)  // Trivially false.
3681       return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
3682
3683     // V >= Min && V < Hi --> V < Hi
3684     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3685       ICmpInst::Predicate pred = (isSigned ? 
3686         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3687       return new ICmpInst(*Context, pred, V, Hi);
3688     }
3689
3690     // Emit V-Lo <u Hi-Lo
3691     Constant *NegLo = Context->getConstantExprNeg(Lo);
3692     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3693     InsertNewInstBefore(Add, IB);
3694     Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
3695     return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
3696   }
3697
3698   if (Lo == Hi)  // Trivially true.
3699     return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
3700
3701   // V < Min || V >= Hi -> V > Hi-1
3702   Hi = SubOne(cast<ConstantInt>(Hi), Context);
3703   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3704     ICmpInst::Predicate pred = (isSigned ? 
3705         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3706     return new ICmpInst(*Context, pred, V, Hi);
3707   }
3708
3709   // Emit V-Lo >u Hi-1-Lo
3710   // Note that Hi has already had one subtracted from it, above.
3711   ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
3712   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3713   InsertNewInstBefore(Add, IB);
3714   Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
3715   return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
3716 }
3717
3718 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3719 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3720 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3721 // not, since all 1s are not contiguous.
3722 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3723   const APInt& V = Val->getValue();
3724   uint32_t BitWidth = Val->getType()->getBitWidth();
3725   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3726
3727   // look for the first zero bit after the run of ones
3728   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3729   // look for the first non-zero bit
3730   ME = V.getActiveBits(); 
3731   return true;
3732 }
3733
3734 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3735 /// where isSub determines whether the operator is a sub.  If we can fold one of
3736 /// the following xforms:
3737 /// 
3738 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3739 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3740 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3741 ///
3742 /// return (A +/- B).
3743 ///
3744 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3745                                         ConstantInt *Mask, bool isSub,
3746                                         Instruction &I) {
3747   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3748   if (!LHSI || LHSI->getNumOperands() != 2 ||
3749       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3750
3751   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3752
3753   switch (LHSI->getOpcode()) {
3754   default: return 0;
3755   case Instruction::And:
3756     if (Context->getConstantExprAnd(N, Mask) == Mask) {
3757       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3758       if ((Mask->getValue().countLeadingZeros() + 
3759            Mask->getValue().countPopulation()) == 
3760           Mask->getValue().getBitWidth())
3761         break;
3762
3763       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3764       // part, we don't need any explicit masks to take them out of A.  If that
3765       // is all N is, ignore it.
3766       uint32_t MB = 0, ME = 0;
3767       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3768         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3769         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3770         if (MaskedValueIsZero(RHS, Mask))
3771           break;
3772       }
3773     }
3774     return 0;
3775   case Instruction::Or:
3776   case Instruction::Xor:
3777     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3778     if ((Mask->getValue().countLeadingZeros() + 
3779          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3780         && Context->getConstantExprAnd(N, Mask)->isNullValue())
3781       break;
3782     return 0;
3783   }
3784   
3785   Instruction *New;
3786   if (isSub)
3787     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3788   else
3789     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3790   return InsertNewInstBefore(New, I);
3791 }
3792
3793 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3794 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3795                                           ICmpInst *LHS, ICmpInst *RHS) {
3796   Value *Val, *Val2;
3797   ConstantInt *LHSCst, *RHSCst;
3798   ICmpInst::Predicate LHSCC, RHSCC;
3799   
3800   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3801   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3802                          m_ConstantInt(LHSCst)), *Context) ||
3803       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3804                          m_ConstantInt(RHSCst)), *Context))
3805     return 0;
3806   
3807   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3808   // where C is a power of 2
3809   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3810       LHSCst->getValue().isPowerOf2()) {
3811     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3812     InsertNewInstBefore(NewOr, I);
3813     return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
3814   }
3815   
3816   // From here on, we only handle:
3817   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3818   if (Val != Val2) return 0;
3819   
3820   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3821   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3822       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3823       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3824       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3825     return 0;
3826   
3827   // We can't fold (ugt x, C) & (sgt x, C2).
3828   if (!PredicatesFoldable(LHSCC, RHSCC))
3829     return 0;
3830     
3831   // Ensure that the larger constant is on the RHS.
3832   bool ShouldSwap;
3833   if (ICmpInst::isSignedPredicate(LHSCC) ||
3834       (ICmpInst::isEquality(LHSCC) && 
3835        ICmpInst::isSignedPredicate(RHSCC)))
3836     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3837   else
3838     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3839     
3840   if (ShouldSwap) {
3841     std::swap(LHS, RHS);
3842     std::swap(LHSCst, RHSCst);
3843     std::swap(LHSCC, RHSCC);
3844   }
3845
3846   // At this point, we know we have have two icmp instructions
3847   // comparing a value against two constants and and'ing the result
3848   // together.  Because of the above check, we know that we only have
3849   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3850   // (from the FoldICmpLogical check above), that the two constants 
3851   // are not equal and that the larger constant is on the RHS
3852   assert(LHSCst != RHSCst && "Compares not folded above?");
3853
3854   switch (LHSCC) {
3855   default: LLVM_UNREACHABLE("Unknown integer condition code!");
3856   case ICmpInst::ICMP_EQ:
3857     switch (RHSCC) {
3858     default: LLVM_UNREACHABLE("Unknown integer condition code!");
3859     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3860     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3861     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3862       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3863     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3864     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3865     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3866       return ReplaceInstUsesWith(I, LHS);
3867     }
3868   case ICmpInst::ICMP_NE:
3869     switch (RHSCC) {
3870     default: LLVM_UNREACHABLE("Unknown integer condition code!");
3871     case ICmpInst::ICMP_ULT:
3872       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
3873         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
3874       break;                        // (X != 13 & X u< 15) -> no change
3875     case ICmpInst::ICMP_SLT:
3876       if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
3877         return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
3878       break;                        // (X != 13 & X s< 15) -> no change
3879     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3880     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3881     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3882       return ReplaceInstUsesWith(I, RHS);
3883     case ICmpInst::ICMP_NE:
3884       if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3885         Constant *AddCST = Context->getConstantExprNeg(LHSCst);
3886         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3887                                                      Val->getName()+".off");
3888         InsertNewInstBefore(Add, I);
3889         return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
3890                             Context->getConstantInt(Add->getType(), 1));
3891       }
3892       break;                        // (X != 13 & X != 15) -> no change
3893     }
3894     break;
3895   case ICmpInst::ICMP_ULT:
3896     switch (RHSCC) {
3897     default: LLVM_UNREACHABLE("Unknown integer condition code!");
3898     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3899     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3900       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3901     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3902       break;
3903     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3904     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3905       return ReplaceInstUsesWith(I, LHS);
3906     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3907       break;
3908     }
3909     break;
3910   case ICmpInst::ICMP_SLT:
3911     switch (RHSCC) {
3912     default: LLVM_UNREACHABLE("Unknown integer condition code!");
3913     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3914     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3915       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3916     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3917       break;
3918     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3919     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3920       return ReplaceInstUsesWith(I, LHS);
3921     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3922       break;
3923     }
3924     break;
3925   case ICmpInst::ICMP_UGT:
3926     switch (RHSCC) {
3927     default: LLVM_UNREACHABLE("Unknown integer condition code!");
3928     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3929     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3930       return ReplaceInstUsesWith(I, RHS);
3931     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3932       break;
3933     case ICmpInst::ICMP_NE:
3934       if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
3935         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3936       break;                        // (X u> 13 & X != 15) -> no change
3937     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3938       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3939                              RHSCst, false, true, I);
3940     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3941       break;
3942     }
3943     break;
3944   case ICmpInst::ICMP_SGT:
3945     switch (RHSCC) {
3946     default: LLVM_UNREACHABLE("Unknown integer condition code!");
3947     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3948     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3949       return ReplaceInstUsesWith(I, RHS);
3950     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3951       break;
3952     case ICmpInst::ICMP_NE:
3953       if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
3954         return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3955       break;                        // (X s> 13 & X != 15) -> no change
3956     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3957       return InsertRangeTest(Val, AddOne(LHSCst, Context),
3958                              RHSCst, true, true, I);
3959     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3960       break;
3961     }
3962     break;
3963   }
3964  
3965   return 0;
3966 }
3967
3968
3969 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3970   bool Changed = SimplifyCommutative(I);
3971   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3972
3973   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3974     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3975
3976   // and X, X = X
3977   if (Op0 == Op1)
3978     return ReplaceInstUsesWith(I, Op1);
3979
3980   // See if we can simplify any instructions used by the instruction whose sole 
3981   // purpose is to compute bits we don't care about.
3982   if (SimplifyDemandedInstructionBits(I))
3983     return &I;
3984   if (isa<VectorType>(I.getType())) {
3985     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3986       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3987         return ReplaceInstUsesWith(I, I.getOperand(0));
3988     } else if (isa<ConstantAggregateZero>(Op1)) {
3989       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3990     }
3991   }
3992
3993   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3994     const APInt& AndRHSMask = AndRHS->getValue();
3995     APInt NotAndRHS(~AndRHSMask);
3996
3997     // Optimize a variety of ((val OP C1) & C2) combinations...
3998     if (isa<BinaryOperator>(Op0)) {
3999       Instruction *Op0I = cast<Instruction>(Op0);
4000       Value *Op0LHS = Op0I->getOperand(0);
4001       Value *Op0RHS = Op0I->getOperand(1);
4002       switch (Op0I->getOpcode()) {
4003       case Instruction::Xor:
4004       case Instruction::Or:
4005         // If the mask is only needed on one incoming arm, push it up.
4006         if (Op0I->hasOneUse()) {
4007           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4008             // Not masking anything out for the LHS, move to RHS.
4009             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
4010                                                    Op0RHS->getName()+".masked");
4011             InsertNewInstBefore(NewRHS, I);
4012             return BinaryOperator::Create(
4013                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4014           }
4015           if (!isa<Constant>(Op0RHS) &&
4016               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4017             // Not masking anything out for the RHS, move to LHS.
4018             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
4019                                                    Op0LHS->getName()+".masked");
4020             InsertNewInstBefore(NewLHS, I);
4021             return BinaryOperator::Create(
4022                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4023           }
4024         }
4025
4026         break;
4027       case Instruction::Add:
4028         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4029         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4030         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4031         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4032           return BinaryOperator::CreateAnd(V, AndRHS);
4033         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4034           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4035         break;
4036
4037       case Instruction::Sub:
4038         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4039         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4040         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4041         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4042           return BinaryOperator::CreateAnd(V, AndRHS);
4043
4044         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4045         // has 1's for all bits that the subtraction with A might affect.
4046         if (Op0I->hasOneUse()) {
4047           uint32_t BitWidth = AndRHSMask.getBitWidth();
4048           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4049           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4050
4051           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4052           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4053               MaskedValueIsZero(Op0LHS, Mask)) {
4054             Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
4055             InsertNewInstBefore(NewNeg, I);
4056             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4057           }
4058         }
4059         break;
4060
4061       case Instruction::Shl:
4062       case Instruction::LShr:
4063         // (1 << x) & 1 --> zext(x == 0)
4064         // (1 >> x) & 1 --> zext(x == 0)
4065         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4066           Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4067                                     Op0RHS, Context->getNullValue(I.getType()));
4068           InsertNewInstBefore(NewICmp, I);
4069           return new ZExtInst(NewICmp, I.getType());
4070         }
4071         break;
4072       }
4073
4074       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4075         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4076           return Res;
4077     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4078       // If this is an integer truncation or change from signed-to-unsigned, and
4079       // if the source is an and/or with immediate, transform it.  This
4080       // frequently occurs for bitfield accesses.
4081       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4082         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4083             CastOp->getNumOperands() == 2)
4084           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4085             if (CastOp->getOpcode() == Instruction::And) {
4086               // Change: and (cast (and X, C1) to T), C2
4087               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4088               // This will fold the two constants together, which may allow 
4089               // other simplifications.
4090               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4091                 CastOp->getOperand(0), I.getType(), 
4092                 CastOp->getName()+".shrunk");
4093               NewCast = InsertNewInstBefore(NewCast, I);
4094               // trunc_or_bitcast(C1)&C2
4095               Constant *C3 =
4096                       Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4097               C3 = Context->getConstantExprAnd(C3, AndRHS);
4098               return BinaryOperator::CreateAnd(NewCast, C3);
4099             } else if (CastOp->getOpcode() == Instruction::Or) {
4100               // Change: and (cast (or X, C1) to T), C2
4101               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4102               Constant *C3 =
4103                       Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4104               if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4105                 // trunc(C1)&C2
4106                 return ReplaceInstUsesWith(I, AndRHS);
4107             }
4108           }
4109       }
4110     }
4111
4112     // Try to fold constant and into select arguments.
4113     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4114       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4115         return R;
4116     if (isa<PHINode>(Op0))
4117       if (Instruction *NV = FoldOpIntoPhi(I))
4118         return NV;
4119   }
4120
4121   Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4122   Value *Op1NotVal = dyn_castNotVal(Op1, Context);
4123
4124   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4125     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
4126
4127   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4128   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4129     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4130                                                I.getName()+".demorgan");
4131     InsertNewInstBefore(Or, I);
4132     return BinaryOperator::CreateNot(*Context, Or);
4133   }
4134   
4135   {
4136     Value *A = 0, *B = 0, *C = 0, *D = 0;
4137     if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
4138       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4139         return ReplaceInstUsesWith(I, Op1);
4140     
4141       // (A|B) & ~(A&B) -> A^B
4142       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4143         if ((A == C && B == D) || (A == D && B == C))
4144           return BinaryOperator::CreateXor(A, B);
4145       }
4146     }
4147     
4148     if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
4149       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4150         return ReplaceInstUsesWith(I, Op0);
4151
4152       // ~(A&B) & (A|B) -> A^B
4153       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
4154         if ((A == C && B == D) || (A == D && B == C))
4155           return BinaryOperator::CreateXor(A, B);
4156       }
4157     }
4158     
4159     if (Op0->hasOneUse() &&
4160         match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4161       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4162         I.swapOperands();     // Simplify below
4163         std::swap(Op0, Op1);
4164       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4165         cast<BinaryOperator>(Op0)->swapOperands();
4166         I.swapOperands();     // Simplify below
4167         std::swap(Op0, Op1);
4168       }
4169     }
4170
4171     if (Op1->hasOneUse() &&
4172         match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
4173       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4174         cast<BinaryOperator>(Op1)->swapOperands();
4175         std::swap(A, B);
4176       }
4177       if (A == Op0) {                                // A&(A^B) -> A & ~B
4178         Instruction *NotB = BinaryOperator::CreateNot(*Context, B, "tmp");
4179         InsertNewInstBefore(NotB, I);
4180         return BinaryOperator::CreateAnd(A, NotB);
4181       }
4182     }
4183
4184     // (A&((~A)|B)) -> A&B
4185     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4186         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
4187       return BinaryOperator::CreateAnd(A, Op1);
4188     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4189         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
4190       return BinaryOperator::CreateAnd(A, Op0);
4191   }
4192   
4193   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4194     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4195     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4196       return R;
4197
4198     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4199       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4200         return Res;
4201   }
4202
4203   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4204   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4205     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4206       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4207         const Type *SrcTy = Op0C->getOperand(0)->getType();
4208         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4209             // Only do this if the casts both really cause code to be generated.
4210             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4211                               I.getType(), TD) &&
4212             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4213                               I.getType(), TD)) {
4214           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4215                                                          Op1C->getOperand(0),
4216                                                          I.getName());
4217           InsertNewInstBefore(NewOp, I);
4218           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4219         }
4220       }
4221     
4222   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4223   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4224     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4225       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4226           SI0->getOperand(1) == SI1->getOperand(1) &&
4227           (SI0->hasOneUse() || SI1->hasOneUse())) {
4228         Instruction *NewOp =
4229           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4230                                                         SI1->getOperand(0),
4231                                                         SI0->getName()), I);
4232         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4233                                       SI1->getOperand(1));
4234       }
4235   }
4236
4237   // If and'ing two fcmp, try combine them into one.
4238   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4239     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4240       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4241           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4242         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4243         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4244           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4245             // If either of the constants are nans, then the whole thing returns
4246             // false.
4247             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4248               return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4249             return new FCmpInst(*Context, FCmpInst::FCMP_ORD, 
4250                                 LHS->getOperand(0), RHS->getOperand(0));
4251           }
4252       } else {
4253         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4254         FCmpInst::Predicate Op0CC, Op1CC;
4255         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4256                   m_Value(Op0RHS)), *Context) &&
4257             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4258                   m_Value(Op1RHS)), *Context)) {
4259           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4260             // Swap RHS operands to match LHS.
4261             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4262             std::swap(Op1LHS, Op1RHS);
4263           }
4264           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4265             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4266             if (Op0CC == Op1CC)
4267               return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4268                                   Op0LHS, Op0RHS);
4269             else if (Op0CC == FCmpInst::FCMP_FALSE ||
4270                      Op1CC == FCmpInst::FCMP_FALSE)
4271               return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4272             else if (Op0CC == FCmpInst::FCMP_TRUE)
4273               return ReplaceInstUsesWith(I, Op1);
4274             else if (Op1CC == FCmpInst::FCMP_TRUE)
4275               return ReplaceInstUsesWith(I, Op0);
4276             bool Op0Ordered;
4277             bool Op1Ordered;
4278             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4279             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4280             if (Op1Pred == 0) {
4281               std::swap(Op0, Op1);
4282               std::swap(Op0Pred, Op1Pred);
4283               std::swap(Op0Ordered, Op1Ordered);
4284             }
4285             if (Op0Pred == 0) {
4286               // uno && ueq -> uno && (uno || eq) -> ueq
4287               // ord && olt -> ord && (ord && lt) -> olt
4288               if (Op0Ordered == Op1Ordered)
4289                 return ReplaceInstUsesWith(I, Op1);
4290               // uno && oeq -> uno && (ord && eq) -> false
4291               // uno && ord -> false
4292               if (!Op0Ordered)
4293                 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4294               // ord && ueq -> ord && (uno || eq) -> oeq
4295               return cast<Instruction>(getFCmpValue(true, Op1Pred,
4296                                                     Op0LHS, Op0RHS, Context));
4297             }
4298           }
4299         }
4300       }
4301     }
4302   }
4303
4304   return Changed ? &I : 0;
4305 }
4306
4307 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4308 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4309 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4310 /// the expression came from the corresponding "byte swapped" byte in some other
4311 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4312 /// we know that the expression deposits the low byte of %X into the high byte
4313 /// of the bswap result and that all other bytes are zero.  This expression is
4314 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4315 /// match.
4316 ///
4317 /// This function returns true if the match was unsuccessful and false if so.
4318 /// On entry to the function the "OverallLeftShift" is a signed integer value
4319 /// indicating the number of bytes that the subexpression is later shifted.  For
4320 /// example, if the expression is later right shifted by 16 bits, the
4321 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4322 /// byte of ByteValues is actually being set.
4323 ///
4324 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4325 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4326 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4327 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4328 /// always in the local (OverallLeftShift) coordinate space.
4329 ///
4330 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4331                               SmallVector<Value*, 8> &ByteValues) {
4332   if (Instruction *I = dyn_cast<Instruction>(V)) {
4333     // If this is an or instruction, it may be an inner node of the bswap.
4334     if (I->getOpcode() == Instruction::Or) {
4335       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4336                                ByteValues) ||
4337              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4338                                ByteValues);
4339     }
4340   
4341     // If this is a logical shift by a constant multiple of 8, recurse with
4342     // OverallLeftShift and ByteMask adjusted.
4343     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4344       unsigned ShAmt = 
4345         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4346       // Ensure the shift amount is defined and of a byte value.
4347       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4348         return true;
4349
4350       unsigned ByteShift = ShAmt >> 3;
4351       if (I->getOpcode() == Instruction::Shl) {
4352         // X << 2 -> collect(X, +2)
4353         OverallLeftShift += ByteShift;
4354         ByteMask >>= ByteShift;
4355       } else {
4356         // X >>u 2 -> collect(X, -2)
4357         OverallLeftShift -= ByteShift;
4358         ByteMask <<= ByteShift;
4359         ByteMask &= (~0U >> (32-ByteValues.size()));
4360       }
4361
4362       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4363       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4364
4365       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4366                                ByteValues);
4367     }
4368
4369     // If this is a logical 'and' with a mask that clears bytes, clear the
4370     // corresponding bytes in ByteMask.
4371     if (I->getOpcode() == Instruction::And &&
4372         isa<ConstantInt>(I->getOperand(1))) {
4373       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4374       unsigned NumBytes = ByteValues.size();
4375       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4376       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4377       
4378       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4379         // If this byte is masked out by a later operation, we don't care what
4380         // the and mask is.
4381         if ((ByteMask & (1 << i)) == 0)
4382           continue;
4383         
4384         // If the AndMask is all zeros for this byte, clear the bit.
4385         APInt MaskB = AndMask & Byte;
4386         if (MaskB == 0) {
4387           ByteMask &= ~(1U << i);
4388           continue;
4389         }
4390         
4391         // If the AndMask is not all ones for this byte, it's not a bytezap.
4392         if (MaskB != Byte)
4393           return true;
4394
4395         // Otherwise, this byte is kept.
4396       }
4397
4398       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4399                                ByteValues);
4400     }
4401   }
4402   
4403   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4404   // the input value to the bswap.  Some observations: 1) if more than one byte
4405   // is demanded from this input, then it could not be successfully assembled
4406   // into a byteswap.  At least one of the two bytes would not be aligned with
4407   // their ultimate destination.
4408   if (!isPowerOf2_32(ByteMask)) return true;
4409   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4410   
4411   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4412   // is demanded, it needs to go into byte 0 of the result.  This means that the
4413   // byte needs to be shifted until it lands in the right byte bucket.  The
4414   // shift amount depends on the position: if the byte is coming from the high
4415   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4416   // low part, it must be shifted left.
4417   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4418   if (InputByteNo < ByteValues.size()/2) {
4419     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4420       return true;
4421   } else {
4422     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4423       return true;
4424   }
4425   
4426   // If the destination byte value is already defined, the values are or'd
4427   // together, which isn't a bswap (unless it's an or of the same bits).
4428   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4429     return true;
4430   ByteValues[DestByteNo] = V;
4431   return false;
4432 }
4433
4434 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4435 /// If so, insert the new bswap intrinsic and return it.
4436 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4437   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4438   if (!ITy || ITy->getBitWidth() % 16 || 
4439       // ByteMask only allows up to 32-byte values.
4440       ITy->getBitWidth() > 32*8) 
4441     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4442   
4443   /// ByteValues - For each byte of the result, we keep track of which value
4444   /// defines each byte.
4445   SmallVector<Value*, 8> ByteValues;
4446   ByteValues.resize(ITy->getBitWidth()/8);
4447     
4448   // Try to find all the pieces corresponding to the bswap.
4449   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4450   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4451     return 0;
4452   
4453   // Check to see if all of the bytes come from the same value.
4454   Value *V = ByteValues[0];
4455   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4456   
4457   // Check to make sure that all of the bytes come from the same value.
4458   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4459     if (ByteValues[i] != V)
4460       return 0;
4461   const Type *Tys[] = { ITy };
4462   Module *M = I.getParent()->getParent()->getParent();
4463   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4464   return CallInst::Create(F, V);
4465 }
4466
4467 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4468 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4469 /// we can simplify this expression to "cond ? C : D or B".
4470 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4471                                          Value *C, Value *D,
4472                                          LLVMContext *Context) {
4473   // If A is not a select of -1/0, this cannot match.
4474   Value *Cond = 0;
4475   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
4476     return 0;
4477
4478   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4479   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4480     return SelectInst::Create(Cond, C, B);
4481   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4482     return SelectInst::Create(Cond, C, B);
4483   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4484   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
4485     return SelectInst::Create(Cond, C, D);
4486   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
4487     return SelectInst::Create(Cond, C, D);
4488   return 0;
4489 }
4490
4491 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4492 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4493                                          ICmpInst *LHS, ICmpInst *RHS) {
4494   Value *Val, *Val2;
4495   ConstantInt *LHSCst, *RHSCst;
4496   ICmpInst::Predicate LHSCC, RHSCC;
4497   
4498   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4499   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4500              m_ConstantInt(LHSCst)), *Context) ||
4501       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4502              m_ConstantInt(RHSCst)), *Context))
4503     return 0;
4504   
4505   // From here on, we only handle:
4506   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4507   if (Val != Val2) return 0;
4508   
4509   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4510   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4511       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4512       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4513       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4514     return 0;
4515   
4516   // We can't fold (ugt x, C) | (sgt x, C2).
4517   if (!PredicatesFoldable(LHSCC, RHSCC))
4518     return 0;
4519   
4520   // Ensure that the larger constant is on the RHS.
4521   bool ShouldSwap;
4522   if (ICmpInst::isSignedPredicate(LHSCC) ||
4523       (ICmpInst::isEquality(LHSCC) && 
4524        ICmpInst::isSignedPredicate(RHSCC)))
4525     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4526   else
4527     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4528   
4529   if (ShouldSwap) {
4530     std::swap(LHS, RHS);
4531     std::swap(LHSCst, RHSCst);
4532     std::swap(LHSCC, RHSCC);
4533   }
4534   
4535   // At this point, we know we have have two icmp instructions
4536   // comparing a value against two constants and or'ing the result
4537   // together.  Because of the above check, we know that we only have
4538   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4539   // FoldICmpLogical check above), that the two constants are not
4540   // equal.
4541   assert(LHSCst != RHSCst && "Compares not folded above?");
4542
4543   switch (LHSCC) {
4544   default: LLVM_UNREACHABLE("Unknown integer condition code!");
4545   case ICmpInst::ICMP_EQ:
4546     switch (RHSCC) {
4547     default: LLVM_UNREACHABLE("Unknown integer condition code!");
4548     case ICmpInst::ICMP_EQ:
4549       if (LHSCst == SubOne(RHSCst, Context)) {
4550         // (X == 13 | X == 14) -> X-13 <u 2
4551         Constant *AddCST = Context->getConstantExprNeg(LHSCst);
4552         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4553                                                      Val->getName()+".off");
4554         InsertNewInstBefore(Add, I);
4555         AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
4556         return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
4557       }
4558       break;                         // (X == 13 | X == 15) -> no change
4559     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4560     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4561       break;
4562     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4563     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4564     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4565       return ReplaceInstUsesWith(I, RHS);
4566     }
4567     break;
4568   case ICmpInst::ICMP_NE:
4569     switch (RHSCC) {
4570     default: LLVM_UNREACHABLE("Unknown integer condition code!");
4571     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4572     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4573     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4574       return ReplaceInstUsesWith(I, LHS);
4575     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4576     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4577     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4578       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4579     }
4580     break;
4581   case ICmpInst::ICMP_ULT:
4582     switch (RHSCC) {
4583     default: LLVM_UNREACHABLE("Unknown integer condition code!");
4584     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4585       break;
4586     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4587       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4588       // this can cause overflow.
4589       if (RHSCst->isMaxValue(false))
4590         return ReplaceInstUsesWith(I, LHS);
4591       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4592                              false, false, I);
4593     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4594       break;
4595     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4596     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4597       return ReplaceInstUsesWith(I, RHS);
4598     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4599       break;
4600     }
4601     break;
4602   case ICmpInst::ICMP_SLT:
4603     switch (RHSCC) {
4604     default: LLVM_UNREACHABLE("Unknown integer condition code!");
4605     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4606       break;
4607     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4608       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4609       // this can cause overflow.
4610       if (RHSCst->isMaxValue(true))
4611         return ReplaceInstUsesWith(I, LHS);
4612       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4613                              true, false, I);
4614     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4615       break;
4616     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4617     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4618       return ReplaceInstUsesWith(I, RHS);
4619     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4620       break;
4621     }
4622     break;
4623   case ICmpInst::ICMP_UGT:
4624     switch (RHSCC) {
4625     default: LLVM_UNREACHABLE("Unknown integer condition code!");
4626     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4627     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4628       return ReplaceInstUsesWith(I, LHS);
4629     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4630       break;
4631     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4632     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4633       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4634     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4635       break;
4636     }
4637     break;
4638   case ICmpInst::ICMP_SGT:
4639     switch (RHSCC) {
4640     default: LLVM_UNREACHABLE("Unknown integer condition code!");
4641     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4642     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4643       return ReplaceInstUsesWith(I, LHS);
4644     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4645       break;
4646     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4647     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4648       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4649     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4650       break;
4651     }
4652     break;
4653   }
4654   return 0;
4655 }
4656
4657 /// FoldOrWithConstants - This helper function folds:
4658 ///
4659 ///     ((A | B) & C1) | (B & C2)
4660 ///
4661 /// into:
4662 /// 
4663 ///     (A & C1) | B
4664 ///
4665 /// when the XOR of the two constants is "all ones" (-1).
4666 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4667                                                Value *A, Value *B, Value *C) {
4668   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4669   if (!CI1) return 0;
4670
4671   Value *V1 = 0;
4672   ConstantInt *CI2 = 0;
4673   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
4674
4675   APInt Xor = CI1->getValue() ^ CI2->getValue();
4676   if (!Xor.isAllOnesValue()) return 0;
4677
4678   if (V1 == A || V1 == B) {
4679     Instruction *NewOp =
4680       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4681     return BinaryOperator::CreateOr(NewOp, V1);
4682   }
4683
4684   return 0;
4685 }
4686
4687 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4688   bool Changed = SimplifyCommutative(I);
4689   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4690
4691   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4692     return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4693
4694   // or X, X = X
4695   if (Op0 == Op1)
4696     return ReplaceInstUsesWith(I, Op0);
4697
4698   // See if we can simplify any instructions used by the instruction whose sole 
4699   // purpose is to compute bits we don't care about.
4700   if (SimplifyDemandedInstructionBits(I))
4701     return &I;
4702   if (isa<VectorType>(I.getType())) {
4703     if (isa<ConstantAggregateZero>(Op1)) {
4704       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4705     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4706       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4707         return ReplaceInstUsesWith(I, I.getOperand(1));
4708     }
4709   }
4710
4711   // or X, -1 == -1
4712   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4713     ConstantInt *C1 = 0; Value *X = 0;
4714     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4715     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) && 
4716         isOnlyUse(Op0)) {
4717       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4718       InsertNewInstBefore(Or, I);
4719       Or->takeName(Op0);
4720       return BinaryOperator::CreateAnd(Or, 
4721                Context->getConstantInt(RHS->getValue() | C1->getValue()));
4722     }
4723
4724     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4725     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) && 
4726         isOnlyUse(Op0)) {
4727       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4728       InsertNewInstBefore(Or, I);
4729       Or->takeName(Op0);
4730       return BinaryOperator::CreateXor(Or,
4731                  Context->getConstantInt(C1->getValue() & ~RHS->getValue()));
4732     }
4733
4734     // Try to fold constant and into select arguments.
4735     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4736       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4737         return R;
4738     if (isa<PHINode>(Op0))
4739       if (Instruction *NV = FoldOpIntoPhi(I))
4740         return NV;
4741   }
4742
4743   Value *A = 0, *B = 0;
4744   ConstantInt *C1 = 0, *C2 = 0;
4745
4746   if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
4747     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4748       return ReplaceInstUsesWith(I, Op1);
4749   if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
4750     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4751       return ReplaceInstUsesWith(I, Op0);
4752
4753   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4754   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4755   if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4756       match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4757       (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4758        match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
4759     if (Instruction *BSwap = MatchBSwap(I))
4760       return BSwap;
4761   }
4762   
4763   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4764   if (Op0->hasOneUse() &&
4765       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4766       MaskedValueIsZero(Op1, C1->getValue())) {
4767     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4768     InsertNewInstBefore(NOr, I);
4769     NOr->takeName(Op0);
4770     return BinaryOperator::CreateXor(NOr, C1);
4771   }
4772
4773   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4774   if (Op1->hasOneUse() &&
4775       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
4776       MaskedValueIsZero(Op0, C1->getValue())) {
4777     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4778     InsertNewInstBefore(NOr, I);
4779     NOr->takeName(Op0);
4780     return BinaryOperator::CreateXor(NOr, C1);
4781   }
4782
4783   // (A & C)|(B & D)
4784   Value *C = 0, *D = 0;
4785   if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4786       match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
4787     Value *V1 = 0, *V2 = 0, *V3 = 0;
4788     C1 = dyn_cast<ConstantInt>(C);
4789     C2 = dyn_cast<ConstantInt>(D);
4790     if (C1 && C2) {  // (A & C1)|(B & C2)
4791       // If we have: ((V + N) & C1) | (V & C2)
4792       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4793       // replace with V+N.
4794       if (C1->getValue() == ~C2->getValue()) {
4795         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4796             match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4797           // Add commutes, try both ways.
4798           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4799             return ReplaceInstUsesWith(I, A);
4800           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4801             return ReplaceInstUsesWith(I, A);
4802         }
4803         // Or commutes, try both ways.
4804         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4805             match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
4806           // Add commutes, try both ways.
4807           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4808             return ReplaceInstUsesWith(I, B);
4809           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4810             return ReplaceInstUsesWith(I, B);
4811         }
4812       }
4813       V1 = 0; V2 = 0; V3 = 0;
4814     }
4815     
4816     // Check to see if we have any common things being and'ed.  If so, find the
4817     // terms for V1 & (V2|V3).
4818     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4819       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4820         V1 = A, V2 = C, V3 = D;
4821       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4822         V1 = A, V2 = B, V3 = C;
4823       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4824         V1 = C, V2 = A, V3 = D;
4825       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4826         V1 = C, V2 = A, V3 = B;
4827       
4828       if (V1) {
4829         Value *Or =
4830           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4831         return BinaryOperator::CreateAnd(V1, Or);
4832       }
4833     }
4834
4835     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4836     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4837       return Match;
4838     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4839       return Match;
4840     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4841       return Match;
4842     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4843       return Match;
4844
4845     // ((A&~B)|(~A&B)) -> A^B
4846     if ((match(C, m_Not(m_Specific(D)), *Context) &&
4847          match(B, m_Not(m_Specific(A)), *Context)))
4848       return BinaryOperator::CreateXor(A, D);
4849     // ((~B&A)|(~A&B)) -> A^B
4850     if ((match(A, m_Not(m_Specific(D)), *Context) &&
4851          match(B, m_Not(m_Specific(C)), *Context)))
4852       return BinaryOperator::CreateXor(C, D);
4853     // ((A&~B)|(B&~A)) -> A^B
4854     if ((match(C, m_Not(m_Specific(B)), *Context) &&
4855          match(D, m_Not(m_Specific(A)), *Context)))
4856       return BinaryOperator::CreateXor(A, B);
4857     // ((~B&A)|(B&~A)) -> A^B
4858     if ((match(A, m_Not(m_Specific(B)), *Context) &&
4859          match(D, m_Not(m_Specific(C)), *Context)))
4860       return BinaryOperator::CreateXor(C, B);
4861   }
4862   
4863   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4864   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4865     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4866       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4867           SI0->getOperand(1) == SI1->getOperand(1) &&
4868           (SI0->hasOneUse() || SI1->hasOneUse())) {
4869         Instruction *NewOp =
4870         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4871                                                      SI1->getOperand(0),
4872                                                      SI0->getName()), I);
4873         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4874                                       SI1->getOperand(1));
4875       }
4876   }
4877
4878   // ((A|B)&1)|(B&-2) -> (A&1) | B
4879   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4880       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4881     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4882     if (Ret) return Ret;
4883   }
4884   // (B&-2)|((A|B)&1) -> (A&1) | B
4885   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4886       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
4887     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4888     if (Ret) return Ret;
4889   }
4890
4891   if (match(Op0, m_Not(m_Value(A)), *Context)) {   // ~A | Op1
4892     if (A == Op1)   // ~A | A == -1
4893       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4894   } else {
4895     A = 0;
4896   }
4897   // Note, A is still live here!
4898   if (match(Op1, m_Not(m_Value(B)), *Context)) {   // Op0 | ~B
4899     if (Op0 == B)
4900       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4901
4902     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4903     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4904       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4905                                               I.getName()+".demorgan"), I);
4906       return BinaryOperator::CreateNot(*Context, And);
4907     }
4908   }
4909
4910   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4911   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4912     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4913       return R;
4914
4915     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4916       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4917         return Res;
4918   }
4919     
4920   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4921   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4922     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4923       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4924         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4925             !isa<ICmpInst>(Op1C->getOperand(0))) {
4926           const Type *SrcTy = Op0C->getOperand(0)->getType();
4927           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4928               // Only do this if the casts both really cause code to be
4929               // generated.
4930               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4931                                 I.getType(), TD) &&
4932               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4933                                 I.getType(), TD)) {
4934             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4935                                                           Op1C->getOperand(0),
4936                                                           I.getName());
4937             InsertNewInstBefore(NewOp, I);
4938             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4939           }
4940         }
4941       }
4942   }
4943   
4944     
4945   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4946   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4947     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4948       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4949           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4950           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4951         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4952           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4953             // If either of the constants are nans, then the whole thing returns
4954             // true.
4955             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4956               return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4957             
4958             // Otherwise, no need to compare the two constants, compare the
4959             // rest.
4960             return new FCmpInst(*Context, FCmpInst::FCMP_UNO, 
4961                                 LHS->getOperand(0), RHS->getOperand(0));
4962           }
4963       } else {
4964         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4965         FCmpInst::Predicate Op0CC, Op1CC;
4966         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4967                   m_Value(Op0RHS)), *Context) &&
4968             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4969                   m_Value(Op1RHS)), *Context)) {
4970           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4971             // Swap RHS operands to match LHS.
4972             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4973             std::swap(Op1LHS, Op1RHS);
4974           }
4975           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4976             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4977             if (Op0CC == Op1CC)
4978               return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4979                                   Op0LHS, Op0RHS);
4980             else if (Op0CC == FCmpInst::FCMP_TRUE ||
4981                      Op1CC == FCmpInst::FCMP_TRUE)
4982               return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4983             else if (Op0CC == FCmpInst::FCMP_FALSE)
4984               return ReplaceInstUsesWith(I, Op1);
4985             else if (Op1CC == FCmpInst::FCMP_FALSE)
4986               return ReplaceInstUsesWith(I, Op0);
4987             bool Op0Ordered;
4988             bool Op1Ordered;
4989             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4990             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4991             if (Op0Ordered == Op1Ordered) {
4992               // If both are ordered or unordered, return a new fcmp with
4993               // or'ed predicates.
4994               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4995                                        Op0LHS, Op0RHS, Context);
4996               if (Instruction *I = dyn_cast<Instruction>(RV))
4997                 return I;
4998               // Otherwise, it's a constant boolean value...
4999               return ReplaceInstUsesWith(I, RV);
5000             }
5001           }
5002         }
5003       }
5004     }
5005   }
5006
5007   return Changed ? &I : 0;
5008 }
5009
5010 namespace {
5011
5012 // XorSelf - Implements: X ^ X --> 0
5013 struct XorSelf {
5014   Value *RHS;
5015   XorSelf(Value *rhs) : RHS(rhs) {}
5016   bool shouldApply(Value *LHS) const { return LHS == RHS; }
5017   Instruction *apply(BinaryOperator &Xor) const {
5018     return &Xor;
5019   }
5020 };
5021
5022 }
5023
5024 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5025   bool Changed = SimplifyCommutative(I);
5026   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5027
5028   if (isa<UndefValue>(Op1)) {
5029     if (isa<UndefValue>(Op0))
5030       // Handle undef ^ undef -> 0 special case. This is a common
5031       // idiom (misuse).
5032       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5033     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5034   }
5035
5036   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5037   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
5038     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5039     return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5040   }
5041   
5042   // See if we can simplify any instructions used by the instruction whose sole 
5043   // purpose is to compute bits we don't care about.
5044   if (SimplifyDemandedInstructionBits(I))
5045     return &I;
5046   if (isa<VectorType>(I.getType()))
5047     if (isa<ConstantAggregateZero>(Op1))
5048       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5049
5050   // Is this a ~ operation?
5051   if (Value *NotOp = dyn_castNotVal(&I, Context)) {
5052     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5053     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5054     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5055       if (Op0I->getOpcode() == Instruction::And || 
5056           Op0I->getOpcode() == Instruction::Or) {
5057         if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5058         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
5059           Instruction *NotY =
5060             BinaryOperator::CreateNot(*Context, Op0I->getOperand(1),
5061                                       Op0I->getOperand(1)->getName()+".not");
5062           InsertNewInstBefore(NotY, I);
5063           if (Op0I->getOpcode() == Instruction::And)
5064             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5065           else
5066             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5067         }
5068       }
5069     }
5070   }
5071   
5072   
5073   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5074     if (RHS == Context->getConstantIntTrue() && Op0->hasOneUse()) {
5075       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5076       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5077         return new ICmpInst(*Context, ICI->getInversePredicate(),
5078                             ICI->getOperand(0), ICI->getOperand(1));
5079
5080       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5081         return new FCmpInst(*Context, FCI->getInversePredicate(),
5082                             FCI->getOperand(0), FCI->getOperand(1));
5083     }
5084
5085     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5086     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5087       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5088         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5089           Instruction::CastOps Opcode = Op0C->getOpcode();
5090           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5091             if (RHS == Context->getConstantExprCast(Opcode, 
5092                                              Context->getConstantIntTrue(),
5093                                              Op0C->getDestTy())) {
5094               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5095                                      *Context,
5096                                      CI->getOpcode(), CI->getInversePredicate(),
5097                                      CI->getOperand(0), CI->getOperand(1)), I);
5098               NewCI->takeName(CI);
5099               return CastInst::Create(Opcode, NewCI, Op0C->getType());
5100             }
5101           }
5102         }
5103       }
5104     }
5105
5106     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5107       // ~(c-X) == X-c-1 == X+(-c-1)
5108       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5109         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5110           Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5111           Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
5112                                       Context->getConstantInt(I.getType(), 1));
5113           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5114         }
5115           
5116       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5117         if (Op0I->getOpcode() == Instruction::Add) {
5118           // ~(X-c) --> (-c-1)-X
5119           if (RHS->isAllOnesValue()) {
5120             Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
5121             return BinaryOperator::CreateSub(
5122                            Context->getConstantExprSub(NegOp0CI,
5123                                       Context->getConstantInt(I.getType(), 1)),
5124                                       Op0I->getOperand(0));
5125           } else if (RHS->getValue().isSignBit()) {
5126             // (X + C) ^ signbit -> (X + C + signbit)
5127             Constant *C =
5128                    Context->getConstantInt(RHS->getValue() + Op0CI->getValue());
5129             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5130
5131           }
5132         } else if (Op0I->getOpcode() == Instruction::Or) {
5133           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5134           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5135             Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
5136             // Anything in both C1 and C2 is known to be zero, remove it from
5137             // NewRHS.
5138             Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5139             NewRHS = Context->getConstantExprAnd(NewRHS, 
5140                                        Context->getConstantExprNot(CommonBits));
5141             AddToWorkList(Op0I);
5142             I.setOperand(0, Op0I->getOperand(0));
5143             I.setOperand(1, NewRHS);
5144             return &I;
5145           }
5146         }
5147       }
5148     }
5149
5150     // Try to fold constant and into select arguments.
5151     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5152       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5153         return R;
5154     if (isa<PHINode>(Op0))
5155       if (Instruction *NV = FoldOpIntoPhi(I))
5156         return NV;
5157   }
5158
5159   if (Value *X = dyn_castNotVal(Op0, Context))   // ~A ^ A == -1
5160     if (X == Op1)
5161       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5162
5163   if (Value *X = dyn_castNotVal(Op1, Context))   // A ^ ~A == -1
5164     if (X == Op0)
5165       return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5166
5167   
5168   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5169   if (Op1I) {
5170     Value *A, *B;
5171     if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
5172       if (A == Op0) {              // B^(B|A) == (A|B)^B
5173         Op1I->swapOperands();
5174         I.swapOperands();
5175         std::swap(Op0, Op1);
5176       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5177         I.swapOperands();     // Simplified below.
5178         std::swap(Op0, Op1);
5179       }
5180     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
5181       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5182     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
5183       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5184     } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) && 
5185                Op1I->hasOneUse()){
5186       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5187         Op1I->swapOperands();
5188         std::swap(A, B);
5189       }
5190       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5191         I.swapOperands();     // Simplified below.
5192         std::swap(Op0, Op1);
5193       }
5194     }
5195   }
5196   
5197   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5198   if (Op0I) {
5199     Value *A, *B;
5200     if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5201         Op0I->hasOneUse()) {
5202       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5203         std::swap(A, B);
5204       if (B == Op1) {                                // (A|B)^B == A & ~B
5205         Instruction *NotB =
5206           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, 
5207                                                         Op1, "tmp"), I);
5208         return BinaryOperator::CreateAnd(A, NotB);
5209       }
5210     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
5211       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5212     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
5213       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5214     } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) && 
5215                Op0I->hasOneUse()){
5216       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5217         std::swap(A, B);
5218       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5219           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5220         Instruction *N =
5221           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, A, "tmp"), I);
5222         return BinaryOperator::CreateAnd(N, Op1);
5223       }
5224     }
5225   }
5226   
5227   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5228   if (Op0I && Op1I && Op0I->isShift() && 
5229       Op0I->getOpcode() == Op1I->getOpcode() && 
5230       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5231       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5232     Instruction *NewOp =
5233       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5234                                                     Op1I->getOperand(0),
5235                                                     Op0I->getName()), I);
5236     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5237                                   Op1I->getOperand(1));
5238   }
5239     
5240   if (Op0I && Op1I) {
5241     Value *A, *B, *C, *D;
5242     // (A & B)^(A | B) -> A ^ B
5243     if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5244         match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
5245       if ((A == C && B == D) || (A == D && B == C)) 
5246         return BinaryOperator::CreateXor(A, B);
5247     }
5248     // (A | B)^(A & B) -> A ^ B
5249     if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5250         match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5251       if ((A == C && B == D) || (A == D && B == C)) 
5252         return BinaryOperator::CreateXor(A, B);
5253     }
5254     
5255     // (A & B)^(C & D)
5256     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5257         match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5258         match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
5259       // (X & Y)^(X & Y) -> (Y^Z) & X
5260       Value *X = 0, *Y = 0, *Z = 0;
5261       if (A == C)
5262         X = A, Y = B, Z = D;
5263       else if (A == D)
5264         X = A, Y = B, Z = C;
5265       else if (B == C)
5266         X = B, Y = A, Z = D;
5267       else if (B == D)
5268         X = B, Y = A, Z = C;
5269       
5270       if (X) {
5271         Instruction *NewOp =
5272         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5273         return BinaryOperator::CreateAnd(NewOp, X);
5274       }
5275     }
5276   }
5277     
5278   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5279   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5280     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
5281       return R;
5282
5283   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5284   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5285     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5286       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5287         const Type *SrcTy = Op0C->getOperand(0)->getType();
5288         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5289             // Only do this if the casts both really cause code to be generated.
5290             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5291                               I.getType(), TD) &&
5292             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5293                               I.getType(), TD)) {
5294           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5295                                                          Op1C->getOperand(0),
5296                                                          I.getName());
5297           InsertNewInstBefore(NewOp, I);
5298           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5299         }
5300       }
5301   }
5302
5303   return Changed ? &I : 0;
5304 }
5305
5306 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5307                                    LLVMContext *Context) {
5308   return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
5309 }
5310
5311 static bool HasAddOverflow(ConstantInt *Result,
5312                            ConstantInt *In1, ConstantInt *In2,
5313                            bool IsSigned) {
5314   if (IsSigned)
5315     if (In2->getValue().isNegative())
5316       return Result->getValue().sgt(In1->getValue());
5317     else
5318       return Result->getValue().slt(In1->getValue());
5319   else
5320     return Result->getValue().ult(In1->getValue());
5321 }
5322
5323 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5324 /// overflowed for this type.
5325 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5326                             Constant *In2, LLVMContext *Context,
5327                             bool IsSigned = false) {
5328   Result = Context->getConstantExprAdd(In1, In2);
5329
5330   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5331     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5332       Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5333       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5334                          ExtractElement(In1, Idx, Context),
5335                          ExtractElement(In2, Idx, Context),
5336                          IsSigned))
5337         return true;
5338     }
5339     return false;
5340   }
5341
5342   return HasAddOverflow(cast<ConstantInt>(Result),
5343                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5344                         IsSigned);
5345 }
5346
5347 static bool HasSubOverflow(ConstantInt *Result,
5348                            ConstantInt *In1, ConstantInt *In2,
5349                            bool IsSigned) {
5350   if (IsSigned)
5351     if (In2->getValue().isNegative())
5352       return Result->getValue().slt(In1->getValue());
5353     else
5354       return Result->getValue().sgt(In1->getValue());
5355   else
5356     return Result->getValue().ugt(In1->getValue());
5357 }
5358
5359 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5360 /// overflowed for this type.
5361 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5362                             Constant *In2, LLVMContext *Context,
5363                             bool IsSigned = false) {
5364   Result = Context->getConstantExprSub(In1, In2);
5365
5366   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5367     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5368       Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5369       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5370                          ExtractElement(In1, Idx, Context),
5371                          ExtractElement(In2, Idx, Context),
5372                          IsSigned))
5373         return true;
5374     }
5375     return false;
5376   }
5377
5378   return HasSubOverflow(cast<ConstantInt>(Result),
5379                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5380                         IsSigned);
5381 }
5382
5383 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5384 /// code necessary to compute the offset from the base pointer (without adding
5385 /// in the base pointer).  Return the result as a signed integer of intptr size.
5386 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5387   TargetData &TD = IC.getTargetData();
5388   gep_type_iterator GTI = gep_type_begin(GEP);
5389   const Type *IntPtrTy = TD.getIntPtrType();
5390   LLVMContext *Context = IC.getContext();
5391   Value *Result = Context->getNullValue(IntPtrTy);
5392
5393   // Build a mask for high order bits.
5394   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5395   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5396
5397   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5398        ++i, ++GTI) {
5399     Value *Op = *i;
5400     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5401     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5402       if (OpC->isZero()) continue;
5403       
5404       // Handle a struct index, which adds its field offset to the pointer.
5405       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5406         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5407         
5408         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5409           Result = 
5410              Context->getConstantInt(RC->getValue() + APInt(IntPtrWidth, Size));
5411         else
5412           Result = IC.InsertNewInstBefore(
5413                    BinaryOperator::CreateAdd(Result,
5414                                         Context->getConstantInt(IntPtrTy, Size),
5415                                              GEP->getName()+".offs"), I);
5416         continue;
5417       }
5418       
5419       Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5420       Constant *OC =
5421               Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5422       Scale = Context->getConstantExprMul(OC, Scale);
5423       if (Constant *RC = dyn_cast<Constant>(Result))
5424         Result = Context->getConstantExprAdd(RC, Scale);
5425       else {
5426         // Emit an add instruction.
5427         Result = IC.InsertNewInstBefore(
5428            BinaryOperator::CreateAdd(Result, Scale,
5429                                      GEP->getName()+".offs"), I);
5430       }
5431       continue;
5432     }
5433     // Convert to correct type.
5434     if (Op->getType() != IntPtrTy) {
5435       if (Constant *OpC = dyn_cast<Constant>(Op))
5436         Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
5437       else
5438         Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5439                                                                 true,
5440                                                       Op->getName()+".c"), I);
5441     }
5442     if (Size != 1) {
5443       Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5444       if (Constant *OpC = dyn_cast<Constant>(Op))
5445         Op = Context->getConstantExprMul(OpC, Scale);
5446       else    // We'll let instcombine(mul) convert this to a shl if possible.
5447         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5448                                                   GEP->getName()+".idx"), I);
5449     }
5450
5451     // Emit an add instruction.
5452     if (isa<Constant>(Op) && isa<Constant>(Result))
5453       Result = Context->getConstantExprAdd(cast<Constant>(Op),
5454                                     cast<Constant>(Result));
5455     else
5456       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5457                                                   GEP->getName()+".offs"), I);
5458   }
5459   return Result;
5460 }
5461
5462
5463 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5464 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
5465 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
5466 /// complex, and scales are involved.  The above expression would also be legal
5467 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
5468 /// later form is less amenable to optimization though, and we are allowed to
5469 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5470 ///
5471 /// If we can't emit an optimized form for this expression, this returns null.
5472 /// 
5473 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5474                                           InstCombiner &IC) {
5475   TargetData &TD = IC.getTargetData();
5476   gep_type_iterator GTI = gep_type_begin(GEP);
5477
5478   // Check to see if this gep only has a single variable index.  If so, and if
5479   // any constant indices are a multiple of its scale, then we can compute this
5480   // in terms of the scale of the variable index.  For example, if the GEP
5481   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5482   // because the expression will cross zero at the same point.
5483   unsigned i, e = GEP->getNumOperands();
5484   int64_t Offset = 0;
5485   for (i = 1; i != e; ++i, ++GTI) {
5486     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5487       // Compute the aggregate offset of constant indices.
5488       if (CI->isZero()) continue;
5489
5490       // Handle a struct index, which adds its field offset to the pointer.
5491       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5492         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5493       } else {
5494         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5495         Offset += Size*CI->getSExtValue();
5496       }
5497     } else {
5498       // Found our variable index.
5499       break;
5500     }
5501   }
5502   
5503   // If there are no variable indices, we must have a constant offset, just
5504   // evaluate it the general way.
5505   if (i == e) return 0;
5506   
5507   Value *VariableIdx = GEP->getOperand(i);
5508   // Determine the scale factor of the variable element.  For example, this is
5509   // 4 if the variable index is into an array of i32.
5510   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5511   
5512   // Verify that there are no other variable indices.  If so, emit the hard way.
5513   for (++i, ++GTI; i != e; ++i, ++GTI) {
5514     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5515     if (!CI) return 0;
5516    
5517     // Compute the aggregate offset of constant indices.
5518     if (CI->isZero()) continue;
5519     
5520     // Handle a struct index, which adds its field offset to the pointer.
5521     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5522       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5523     } else {
5524       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5525       Offset += Size*CI->getSExtValue();
5526     }
5527   }
5528   
5529   // Okay, we know we have a single variable index, which must be a
5530   // pointer/array/vector index.  If there is no offset, life is simple, return
5531   // the index.
5532   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5533   if (Offset == 0) {
5534     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5535     // we don't need to bother extending: the extension won't affect where the
5536     // computation crosses zero.
5537     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5538       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5539                                   VariableIdx->getNameStart(), &I);
5540     return VariableIdx;
5541   }
5542   
5543   // Otherwise, there is an index.  The computation we will do will be modulo
5544   // the pointer size, so get it.
5545   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5546   
5547   Offset &= PtrSizeMask;
5548   VariableScale &= PtrSizeMask;
5549
5550   // To do this transformation, any constant index must be a multiple of the
5551   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5552   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5553   // multiple of the variable scale.
5554   int64_t NewOffs = Offset / (int64_t)VariableScale;
5555   if (Offset != NewOffs*(int64_t)VariableScale)
5556     return 0;
5557
5558   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5559   const Type *IntPtrTy = TD.getIntPtrType();
5560   if (VariableIdx->getType() != IntPtrTy)
5561     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5562                                               true /*SExt*/, 
5563                                               VariableIdx->getNameStart(), &I);
5564   Constant *OffsetVal = IC.getContext()->getConstantInt(IntPtrTy, NewOffs);
5565   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5566 }
5567
5568
5569 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5570 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5571 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5572                                        ICmpInst::Predicate Cond,
5573                                        Instruction &I) {
5574   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5575
5576   // Look through bitcasts.
5577   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5578     RHS = BCI->getOperand(0);
5579
5580   Value *PtrBase = GEPLHS->getOperand(0);
5581   if (PtrBase == RHS) {
5582     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5583     // This transformation (ignoring the base and scales) is valid because we
5584     // know pointers can't overflow.  See if we can output an optimized form.
5585     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5586     
5587     // If not, synthesize the offset the hard way.
5588     if (Offset == 0)
5589       Offset = EmitGEPOffset(GEPLHS, I, *this);
5590     return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
5591                         Context->getNullValue(Offset->getType()));
5592   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5593     // If the base pointers are different, but the indices are the same, just
5594     // compare the base pointer.
5595     if (PtrBase != GEPRHS->getOperand(0)) {
5596       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5597       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5598                         GEPRHS->getOperand(0)->getType();
5599       if (IndicesTheSame)
5600         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5601           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5602             IndicesTheSame = false;
5603             break;
5604           }
5605
5606       // If all indices are the same, just compare the base pointers.
5607       if (IndicesTheSame)
5608         return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), 
5609                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5610
5611       // Otherwise, the base pointers are different and the indices are
5612       // different, bail out.
5613       return 0;
5614     }
5615
5616     // If one of the GEPs has all zero indices, recurse.
5617     bool AllZeros = true;
5618     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5619       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5620           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5621         AllZeros = false;
5622         break;
5623       }
5624     if (AllZeros)
5625       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5626                           ICmpInst::getSwappedPredicate(Cond), I);
5627
5628     // If the other GEP has all zero indices, recurse.
5629     AllZeros = true;
5630     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5631       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5632           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5633         AllZeros = false;
5634         break;
5635       }
5636     if (AllZeros)
5637       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5638
5639     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5640       // If the GEPs only differ by one index, compare it.
5641       unsigned NumDifferences = 0;  // Keep track of # differences.
5642       unsigned DiffOperand = 0;     // The operand that differs.
5643       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5644         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5645           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5646                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5647             // Irreconcilable differences.
5648             NumDifferences = 2;
5649             break;
5650           } else {
5651             if (NumDifferences++) break;
5652             DiffOperand = i;
5653           }
5654         }
5655
5656       if (NumDifferences == 0)   // SAME GEP?
5657         return ReplaceInstUsesWith(I, // No comparison is needed here.
5658                                    Context->getConstantInt(Type::Int1Ty,
5659                                              ICmpInst::isTrueWhenEqual(Cond)));
5660
5661       else if (NumDifferences == 1) {
5662         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5663         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5664         // Make sure we do a signed comparison here.
5665         return new ICmpInst(*Context,
5666                             ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5667       }
5668     }
5669
5670     // Only lower this if the icmp is the only user of the GEP or if we expect
5671     // the result to fold to a constant!
5672     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5673         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5674       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5675       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5676       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5677       return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
5678     }
5679   }
5680   return 0;
5681 }
5682
5683 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5684 ///
5685 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5686                                                 Instruction *LHSI,
5687                                                 Constant *RHSC) {
5688   if (!isa<ConstantFP>(RHSC)) return 0;
5689   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5690   
5691   // Get the width of the mantissa.  We don't want to hack on conversions that
5692   // might lose information from the integer, e.g. "i64 -> float"
5693   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5694   if (MantissaWidth == -1) return 0;  // Unknown.
5695   
5696   // Check to see that the input is converted from an integer type that is small
5697   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5698   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5699   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5700   
5701   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5702   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5703   if (LHSUnsigned)
5704     ++InputSize;
5705   
5706   // If the conversion would lose info, don't hack on this.
5707   if ((int)InputSize > MantissaWidth)
5708     return 0;
5709   
5710   // Otherwise, we can potentially simplify the comparison.  We know that it
5711   // will always come through as an integer value and we know the constant is
5712   // not a NAN (it would have been previously simplified).
5713   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5714   
5715   ICmpInst::Predicate Pred;
5716   switch (I.getPredicate()) {
5717   default: LLVM_UNREACHABLE("Unexpected predicate!");
5718   case FCmpInst::FCMP_UEQ:
5719   case FCmpInst::FCMP_OEQ:
5720     Pred = ICmpInst::ICMP_EQ;
5721     break;
5722   case FCmpInst::FCMP_UGT:
5723   case FCmpInst::FCMP_OGT:
5724     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5725     break;
5726   case FCmpInst::FCMP_UGE:
5727   case FCmpInst::FCMP_OGE:
5728     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5729     break;
5730   case FCmpInst::FCMP_ULT:
5731   case FCmpInst::FCMP_OLT:
5732     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5733     break;
5734   case FCmpInst::FCMP_ULE:
5735   case FCmpInst::FCMP_OLE:
5736     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5737     break;
5738   case FCmpInst::FCMP_UNE:
5739   case FCmpInst::FCMP_ONE:
5740     Pred = ICmpInst::ICMP_NE;
5741     break;
5742   case FCmpInst::FCMP_ORD:
5743     return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5744   case FCmpInst::FCMP_UNO:
5745     return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5746   }
5747   
5748   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5749   
5750   // Now we know that the APFloat is a normal number, zero or inf.
5751   
5752   // See if the FP constant is too large for the integer.  For example,
5753   // comparing an i8 to 300.0.
5754   unsigned IntWidth = IntTy->getScalarSizeInBits();
5755   
5756   if (!LHSUnsigned) {
5757     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5758     // and large values.
5759     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5760     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5761                           APFloat::rmNearestTiesToEven);
5762     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5763       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5764           Pred == ICmpInst::ICMP_SLE)
5765         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5766       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5767     }
5768   } else {
5769     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5770     // +INF and large values.
5771     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5772     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5773                           APFloat::rmNearestTiesToEven);
5774     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5775       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5776           Pred == ICmpInst::ICMP_ULE)
5777         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5778       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5779     }
5780   }
5781   
5782   if (!LHSUnsigned) {
5783     // See if the RHS value is < SignedMin.
5784     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5785     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5786                           APFloat::rmNearestTiesToEven);
5787     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5788       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5789           Pred == ICmpInst::ICMP_SGE)
5790         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5791       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5792     }
5793   }
5794
5795   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5796   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5797   // casting the FP value to the integer value and back, checking for equality.
5798   // Don't do this for zero, because -0.0 is not fractional.
5799   Constant *RHSInt = LHSUnsigned
5800     ? Context->getConstantExprFPToUI(RHSC, IntTy)
5801     : Context->getConstantExprFPToSI(RHSC, IntTy);
5802   if (!RHS.isZero()) {
5803     bool Equal = LHSUnsigned
5804       ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5805       : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
5806     if (!Equal) {
5807       // If we had a comparison against a fractional value, we have to adjust
5808       // the compare predicate and sometimes the value.  RHSC is rounded towards
5809       // zero at this point.
5810       switch (Pred) {
5811       default: LLVM_UNREACHABLE("Unexpected integer comparison!");
5812       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5813         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5814       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5815         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5816       case ICmpInst::ICMP_ULE:
5817         // (float)int <= 4.4   --> int <= 4
5818         // (float)int <= -4.4  --> false
5819         if (RHS.isNegative())
5820           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5821         break;
5822       case ICmpInst::ICMP_SLE:
5823         // (float)int <= 4.4   --> int <= 4
5824         // (float)int <= -4.4  --> int < -4
5825         if (RHS.isNegative())
5826           Pred = ICmpInst::ICMP_SLT;
5827         break;
5828       case ICmpInst::ICMP_ULT:
5829         // (float)int < -4.4   --> false
5830         // (float)int < 4.4    --> int <= 4
5831         if (RHS.isNegative())
5832           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5833         Pred = ICmpInst::ICMP_ULE;
5834         break;
5835       case ICmpInst::ICMP_SLT:
5836         // (float)int < -4.4   --> int < -4
5837         // (float)int < 4.4    --> int <= 4
5838         if (!RHS.isNegative())
5839           Pred = ICmpInst::ICMP_SLE;
5840         break;
5841       case ICmpInst::ICMP_UGT:
5842         // (float)int > 4.4    --> int > 4
5843         // (float)int > -4.4   --> true
5844         if (RHS.isNegative())
5845           return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5846         break;
5847       case ICmpInst::ICMP_SGT:
5848         // (float)int > 4.4    --> int > 4
5849         // (float)int > -4.4   --> int >= -4
5850         if (RHS.isNegative())
5851           Pred = ICmpInst::ICMP_SGE;
5852         break;
5853       case ICmpInst::ICMP_UGE:
5854         // (float)int >= -4.4   --> true
5855         // (float)int >= 4.4    --> int > 4
5856         if (!RHS.isNegative())
5857           return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5858         Pred = ICmpInst::ICMP_UGT;
5859         break;
5860       case ICmpInst::ICMP_SGE:
5861         // (float)int >= -4.4   --> int >= -4
5862         // (float)int >= 4.4    --> int > 4
5863         if (!RHS.isNegative())
5864           Pred = ICmpInst::ICMP_SGT;
5865         break;
5866       }
5867     }
5868   }
5869
5870   // Lower this FP comparison into an appropriate integer version of the
5871   // comparison.
5872   return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
5873 }
5874
5875 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5876   bool Changed = SimplifyCompare(I);
5877   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5878
5879   // Fold trivial predicates.
5880   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5881     return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5882   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5883     return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5884   
5885   // Simplify 'fcmp pred X, X'
5886   if (Op0 == Op1) {
5887     switch (I.getPredicate()) {
5888     default: LLVM_UNREACHABLE("Unknown predicate!");
5889     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5890     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5891     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5892       return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5893     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5894     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5895     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5896       return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5897       
5898     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5899     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5900     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5901     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5902       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5903       I.setPredicate(FCmpInst::FCMP_UNO);
5904       I.setOperand(1, Context->getNullValue(Op0->getType()));
5905       return &I;
5906       
5907     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5908     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5909     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5910     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5911       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5912       I.setPredicate(FCmpInst::FCMP_ORD);
5913       I.setOperand(1, Context->getNullValue(Op0->getType()));
5914       return &I;
5915     }
5916   }
5917     
5918   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5919     return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5920
5921   // Handle fcmp with constant RHS
5922   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5923     // If the constant is a nan, see if we can fold the comparison based on it.
5924     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5925       if (CFP->getValueAPF().isNaN()) {
5926         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5927           return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5928         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5929                "Comparison must be either ordered or unordered!");
5930         // True if unordered.
5931         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5932       }
5933     }
5934     
5935     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5936       switch (LHSI->getOpcode()) {
5937       case Instruction::PHI:
5938         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5939         // block.  If in the same block, we're encouraging jump threading.  If
5940         // not, we are just pessimizing the code by making an i1 phi.
5941         if (LHSI->getParent() == I.getParent())
5942           if (Instruction *NV = FoldOpIntoPhi(I))
5943             return NV;
5944         break;
5945       case Instruction::SIToFP:
5946       case Instruction::UIToFP:
5947         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5948           return NV;
5949         break;
5950       case Instruction::Select:
5951         // If either operand of the select is a constant, we can fold the
5952         // comparison into the select arms, which will cause one to be
5953         // constant folded and the select turned into a bitwise or.
5954         Value *Op1 = 0, *Op2 = 0;
5955         if (LHSI->hasOneUse()) {
5956           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5957             // Fold the known value into the constant operand.
5958             Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5959             // Insert a new FCmp of the other select operand.
5960             Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5961                                                       LHSI->getOperand(2), RHSC,
5962                                                       I.getName()), I);
5963           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5964             // Fold the known value into the constant operand.
5965             Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5966             // Insert a new FCmp of the other select operand.
5967             Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5968                                                       LHSI->getOperand(1), RHSC,
5969                                                       I.getName()), I);
5970           }
5971         }
5972
5973         if (Op1)
5974           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5975         break;
5976       }
5977   }
5978
5979   return Changed ? &I : 0;
5980 }
5981
5982 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5983   bool Changed = SimplifyCompare(I);
5984   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5985   const Type *Ty = Op0->getType();
5986
5987   // icmp X, X
5988   if (Op0 == Op1)
5989     return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty, 
5990                                                    I.isTrueWhenEqual()));
5991
5992   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5993     return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5994   
5995   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5996   // addresses never equal each other!  We already know that Op0 != Op1.
5997   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5998        isa<ConstantPointerNull>(Op0)) &&
5999       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
6000        isa<ConstantPointerNull>(Op1)))
6001     return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty, 
6002                                                    !I.isTrueWhenEqual()));
6003
6004   // icmp's with boolean values can always be turned into bitwise operations
6005   if (Ty == Type::Int1Ty) {
6006     switch (I.getPredicate()) {
6007     default: LLVM_UNREACHABLE("Invalid icmp instruction!");
6008     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
6009       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
6010       InsertNewInstBefore(Xor, I);
6011       return BinaryOperator::CreateNot(*Context, Xor);
6012     }
6013     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
6014       return BinaryOperator::CreateXor(Op0, Op1);
6015
6016     case ICmpInst::ICMP_UGT:
6017       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
6018       // FALL THROUGH
6019     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
6020       Instruction *Not = BinaryOperator::CreateNot(*Context,
6021                                                    Op0, I.getName()+"tmp");
6022       InsertNewInstBefore(Not, I);
6023       return BinaryOperator::CreateAnd(Not, Op1);
6024     }
6025     case ICmpInst::ICMP_SGT:
6026       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
6027       // FALL THROUGH
6028     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
6029       Instruction *Not = BinaryOperator::CreateNot(*Context, 
6030                                                    Op1, I.getName()+"tmp");
6031       InsertNewInstBefore(Not, I);
6032       return BinaryOperator::CreateAnd(Not, Op0);
6033     }
6034     case ICmpInst::ICMP_UGE:
6035       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6036       // FALL THROUGH
6037     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6038       Instruction *Not = BinaryOperator::CreateNot(*Context,
6039                                                    Op0, I.getName()+"tmp");
6040       InsertNewInstBefore(Not, I);
6041       return BinaryOperator::CreateOr(Not, Op1);
6042     }
6043     case ICmpInst::ICMP_SGE:
6044       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6045       // FALL THROUGH
6046     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6047       Instruction *Not = BinaryOperator::CreateNot(*Context,
6048                                                    Op1, I.getName()+"tmp");
6049       InsertNewInstBefore(Not, I);
6050       return BinaryOperator::CreateOr(Not, Op0);
6051     }
6052     }
6053   }
6054
6055   unsigned BitWidth = 0;
6056   if (TD)
6057     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6058   else if (Ty->isIntOrIntVector())
6059     BitWidth = Ty->getScalarSizeInBits();
6060
6061   bool isSignBit = false;
6062
6063   // See if we are doing a comparison with a constant.
6064   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6065     Value *A = 0, *B = 0;
6066     
6067     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6068     if (I.isEquality() && CI->isNullValue() &&
6069         match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
6070       // (icmp cond A B) if cond is equality
6071       return new ICmpInst(*Context, I.getPredicate(), A, B);
6072     }
6073     
6074     // If we have an icmp le or icmp ge instruction, turn it into the
6075     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6076     // them being folded in the code below.
6077     switch (I.getPredicate()) {
6078     default: break;
6079     case ICmpInst::ICMP_ULE:
6080       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
6081         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6082       return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6083                           AddOne(CI, Context));
6084     case ICmpInst::ICMP_SLE:
6085       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
6086         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6087       return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6088                           AddOne(CI, Context));
6089     case ICmpInst::ICMP_UGE:
6090       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
6091         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6092       return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6093                           SubOne(CI, Context));
6094     case ICmpInst::ICMP_SGE:
6095       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
6096         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6097       return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6098                           SubOne(CI, Context));
6099     }
6100     
6101     // If this comparison is a normal comparison, it demands all
6102     // bits, if it is a sign bit comparison, it only demands the sign bit.
6103     bool UnusedBit;
6104     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6105   }
6106
6107   // See if we can fold the comparison based on range information we can get
6108   // by checking whether bits are known to be zero or one in the input.
6109   if (BitWidth != 0) {
6110     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6111     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6112
6113     if (SimplifyDemandedBits(I.getOperandUse(0),
6114                              isSignBit ? APInt::getSignBit(BitWidth)
6115                                        : APInt::getAllOnesValue(BitWidth),
6116                              Op0KnownZero, Op0KnownOne, 0))
6117       return &I;
6118     if (SimplifyDemandedBits(I.getOperandUse(1),
6119                              APInt::getAllOnesValue(BitWidth),
6120                              Op1KnownZero, Op1KnownOne, 0))
6121       return &I;
6122
6123     // Given the known and unknown bits, compute a range that the LHS could be
6124     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6125     // EQ and NE we use unsigned values.
6126     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6127     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6128     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6129       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6130                                              Op0Min, Op0Max);
6131       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6132                                              Op1Min, Op1Max);
6133     } else {
6134       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6135                                                Op0Min, Op0Max);
6136       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6137                                                Op1Min, Op1Max);
6138     }
6139
6140     // If Min and Max are known to be the same, then SimplifyDemandedBits
6141     // figured out that the LHS is a constant.  Just constant fold this now so
6142     // that code below can assume that Min != Max.
6143     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6144       return new ICmpInst(*Context, I.getPredicate(),
6145                           Context->getConstantInt(Op0Min), Op1);
6146     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6147       return new ICmpInst(*Context, I.getPredicate(), Op0, 
6148                           Context->getConstantInt(Op1Min));
6149
6150     // Based on the range information we know about the LHS, see if we can
6151     // simplify this comparison.  For example, (x&4) < 8  is always true.
6152     switch (I.getPredicate()) {
6153     default: LLVM_UNREACHABLE("Unknown icmp opcode!");
6154     case ICmpInst::ICMP_EQ:
6155       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6156         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6157       break;
6158     case ICmpInst::ICMP_NE:
6159       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6160         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6161       break;
6162     case ICmpInst::ICMP_ULT:
6163       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6164         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6165       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6166         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6167       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6168         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6169       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6170         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6171           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6172                               SubOne(CI, Context));
6173
6174         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6175         if (CI->isMinValue(true))
6176           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6177                            Context->getAllOnesValue(Op0->getType()));
6178       }
6179       break;
6180     case ICmpInst::ICMP_UGT:
6181       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6182         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6183       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6184         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6185
6186       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6187         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6188       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6189         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6190           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6191                               AddOne(CI, Context));
6192
6193         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6194         if (CI->isMaxValue(true))
6195           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6196                               Context->getNullValue(Op0->getType()));
6197       }
6198       break;
6199     case ICmpInst::ICMP_SLT:
6200       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6201         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6202       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6203         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6204       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6205         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6206       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6207         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6208           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6209                               SubOne(CI, Context));
6210       }
6211       break;
6212     case ICmpInst::ICMP_SGT:
6213       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6214         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6215       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6216         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6217
6218       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6219         return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6220       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6221         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6222           return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6223                               AddOne(CI, Context));
6224       }
6225       break;
6226     case ICmpInst::ICMP_SGE:
6227       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6228       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6229         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6230       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6231         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6232       break;
6233     case ICmpInst::ICMP_SLE:
6234       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6235       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6236         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6237       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6238         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6239       break;
6240     case ICmpInst::ICMP_UGE:
6241       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6242       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6243         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6244       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6245         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6246       break;
6247     case ICmpInst::ICMP_ULE:
6248       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6249       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6250         return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6251       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6252         return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6253       break;
6254     }
6255
6256     // Turn a signed comparison into an unsigned one if both operands
6257     // are known to have the same sign.
6258     if (I.isSignedPredicate() &&
6259         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6260          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6261       return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
6262   }
6263
6264   // Test if the ICmpInst instruction is used exclusively by a select as
6265   // part of a minimum or maximum operation. If so, refrain from doing
6266   // any other folding. This helps out other analyses which understand
6267   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6268   // and CodeGen. And in this case, at least one of the comparison
6269   // operands has at least one user besides the compare (the select),
6270   // which would often largely negate the benefit of folding anyway.
6271   if (I.hasOneUse())
6272     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6273       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6274           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6275         return 0;
6276
6277   // See if we are doing a comparison between a constant and an instruction that
6278   // can be folded into the comparison.
6279   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6280     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6281     // instruction, see if that instruction also has constants so that the 
6282     // instruction can be folded into the icmp 
6283     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6284       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6285         return Res;
6286   }
6287
6288   // Handle icmp with constant (but not simple integer constant) RHS
6289   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6290     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6291       switch (LHSI->getOpcode()) {
6292       case Instruction::GetElementPtr:
6293         if (RHSC->isNullValue()) {
6294           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6295           bool isAllZeros = true;
6296           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6297             if (!isa<Constant>(LHSI->getOperand(i)) ||
6298                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6299               isAllZeros = false;
6300               break;
6301             }
6302           if (isAllZeros)
6303             return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
6304                     Context->getNullValue(LHSI->getOperand(0)->getType()));
6305         }
6306         break;
6307
6308       case Instruction::PHI:
6309         // Only fold icmp into the PHI if the phi and fcmp are in the same
6310         // block.  If in the same block, we're encouraging jump threading.  If
6311         // not, we are just pessimizing the code by making an i1 phi.
6312         if (LHSI->getParent() == I.getParent())
6313           if (Instruction *NV = FoldOpIntoPhi(I))
6314             return NV;
6315         break;
6316       case Instruction::Select: {
6317         // If either operand of the select is a constant, we can fold the
6318         // comparison into the select arms, which will cause one to be
6319         // constant folded and the select turned into a bitwise or.
6320         Value *Op1 = 0, *Op2 = 0;
6321         if (LHSI->hasOneUse()) {
6322           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6323             // Fold the known value into the constant operand.
6324             Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6325             // Insert a new ICmp of the other select operand.
6326             Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6327                                                    LHSI->getOperand(2), RHSC,
6328                                                    I.getName()), I);
6329           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6330             // Fold the known value into the constant operand.
6331             Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6332             // Insert a new ICmp of the other select operand.
6333             Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6334                                                    LHSI->getOperand(1), RHSC,
6335                                                    I.getName()), I);
6336           }
6337         }
6338
6339         if (Op1)
6340           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6341         break;
6342       }
6343       case Instruction::Malloc:
6344         // If we have (malloc != null), and if the malloc has a single use, we
6345         // can assume it is successful and remove the malloc.
6346         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6347           AddToWorkList(LHSI);
6348           return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
6349                                                          !I.isTrueWhenEqual()));
6350         }
6351         break;
6352       }
6353   }
6354
6355   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6356   if (User *GEP = dyn_castGetElementPtr(Op0))
6357     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6358       return NI;
6359   if (User *GEP = dyn_castGetElementPtr(Op1))
6360     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6361                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6362       return NI;
6363
6364   // Test to see if the operands of the icmp are casted versions of other
6365   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6366   // now.
6367   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6368     if (isa<PointerType>(Op0->getType()) && 
6369         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6370       // We keep moving the cast from the left operand over to the right
6371       // operand, where it can often be eliminated completely.
6372       Op0 = CI->getOperand(0);
6373
6374       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6375       // so eliminate it as well.
6376       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6377         Op1 = CI2->getOperand(0);
6378
6379       // If Op1 is a constant, we can fold the cast into the constant.
6380       if (Op0->getType() != Op1->getType()) {
6381         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6382           Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
6383         } else {
6384           // Otherwise, cast the RHS right before the icmp
6385           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6386         }
6387       }
6388       return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
6389     }
6390   }
6391   
6392   if (isa<CastInst>(Op0)) {
6393     // Handle the special case of: icmp (cast bool to X), <cst>
6394     // This comes up when you have code like
6395     //   int X = A < B;
6396     //   if (X) ...
6397     // For generality, we handle any zero-extension of any operand comparison
6398     // with a constant or another cast from the same type.
6399     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6400       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6401         return R;
6402   }
6403   
6404   // See if it's the same type of instruction on the left and right.
6405   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6406     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6407       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6408           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6409         switch (Op0I->getOpcode()) {
6410         default: break;
6411         case Instruction::Add:
6412         case Instruction::Sub:
6413         case Instruction::Xor:
6414           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6415             return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
6416                                 Op1I->getOperand(0));
6417           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6418           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6419             if (CI->getValue().isSignBit()) {
6420               ICmpInst::Predicate Pred = I.isSignedPredicate()
6421                                              ? I.getUnsignedPredicate()
6422                                              : I.getSignedPredicate();
6423               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6424                                   Op1I->getOperand(0));
6425             }
6426             
6427             if (CI->getValue().isMaxSignedValue()) {
6428               ICmpInst::Predicate Pred = I.isSignedPredicate()
6429                                              ? I.getUnsignedPredicate()
6430                                              : I.getSignedPredicate();
6431               Pred = I.getSwappedPredicate(Pred);
6432               return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6433                                   Op1I->getOperand(0));
6434             }
6435           }
6436           break;
6437         case Instruction::Mul:
6438           if (!I.isEquality())
6439             break;
6440
6441           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6442             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6443             // Mask = -1 >> count-trailing-zeros(Cst).
6444             if (!CI->isZero() && !CI->isOne()) {
6445               const APInt &AP = CI->getValue();
6446               ConstantInt *Mask = Context->getConstantInt(
6447                                       APInt::getLowBitsSet(AP.getBitWidth(),
6448                                                            AP.getBitWidth() -
6449                                                       AP.countTrailingZeros()));
6450               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6451                                                             Mask);
6452               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6453                                                             Mask);
6454               InsertNewInstBefore(And1, I);
6455               InsertNewInstBefore(And2, I);
6456               return new ICmpInst(*Context, I.getPredicate(), And1, And2);
6457             }
6458           }
6459           break;
6460         }
6461       }
6462     }
6463   }
6464   
6465   // ~x < ~y --> y < x
6466   { Value *A, *B;
6467     if (match(Op0, m_Not(m_Value(A)), *Context) &&
6468         match(Op1, m_Not(m_Value(B)), *Context))
6469       return new ICmpInst(*Context, I.getPredicate(), B, A);
6470   }
6471   
6472   if (I.isEquality()) {
6473     Value *A, *B, *C, *D;
6474     
6475     // -x == -y --> x == y
6476     if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6477         match(Op1, m_Neg(m_Value(B)), *Context))
6478       return new ICmpInst(*Context, I.getPredicate(), A, B);
6479     
6480     if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
6481       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6482         Value *OtherVal = A == Op1 ? B : A;
6483         return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6484                             Context->getNullValue(A->getType()));
6485       }
6486
6487       if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
6488         // A^c1 == C^c2 --> A == C^(c1^c2)
6489         ConstantInt *C1, *C2;
6490         if (match(B, m_ConstantInt(C1), *Context) &&
6491             match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
6492           Constant *NC = 
6493                        Context->getConstantInt(C1->getValue() ^ C2->getValue());
6494           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6495           return new ICmpInst(*Context, I.getPredicate(), A,
6496                               InsertNewInstBefore(Xor, I));
6497         }
6498         
6499         // A^B == A^D -> B == D
6500         if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6501         if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6502         if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6503         if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
6504       }
6505     }
6506     
6507     if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
6508         (A == Op0 || B == Op0)) {
6509       // A == (A^B)  ->  B == 0
6510       Value *OtherVal = A == Op0 ? B : A;
6511       return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6512                           Context->getNullValue(A->getType()));
6513     }
6514
6515     // (A-B) == A  ->  B == 0
6516     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
6517       return new ICmpInst(*Context, I.getPredicate(), B, 
6518                           Context->getNullValue(B->getType()));
6519
6520     // A == (A-B)  ->  B == 0
6521     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
6522       return new ICmpInst(*Context, I.getPredicate(), B,
6523                           Context->getNullValue(B->getType()));
6524     
6525     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6526     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6527         match(Op0, m_And(m_Value(A), m_Value(B)), *Context) && 
6528         match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
6529       Value *X = 0, *Y = 0, *Z = 0;
6530       
6531       if (A == C) {
6532         X = B; Y = D; Z = A;
6533       } else if (A == D) {
6534         X = B; Y = C; Z = A;
6535       } else if (B == C) {
6536         X = A; Y = D; Z = B;
6537       } else if (B == D) {
6538         X = A; Y = C; Z = B;
6539       }
6540       
6541       if (X) {   // Build (X^Y) & Z
6542         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6543         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6544         I.setOperand(0, Op1);
6545         I.setOperand(1, Context->getNullValue(Op1->getType()));
6546         return &I;
6547       }
6548     }
6549   }
6550   return Changed ? &I : 0;
6551 }
6552
6553
6554 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6555 /// and CmpRHS are both known to be integer constants.
6556 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6557                                           ConstantInt *DivRHS) {
6558   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6559   const APInt &CmpRHSV = CmpRHS->getValue();
6560   
6561   // FIXME: If the operand types don't match the type of the divide 
6562   // then don't attempt this transform. The code below doesn't have the
6563   // logic to deal with a signed divide and an unsigned compare (and
6564   // vice versa). This is because (x /s C1) <s C2  produces different 
6565   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6566   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6567   // work. :(  The if statement below tests that condition and bails 
6568   // if it finds it. 
6569   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6570   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6571     return 0;
6572   if (DivRHS->isZero())
6573     return 0; // The ProdOV computation fails on divide by zero.
6574   if (DivIsSigned && DivRHS->isAllOnesValue())
6575     return 0; // The overflow computation also screws up here
6576   if (DivRHS->isOne())
6577     return 0; // Not worth bothering, and eliminates some funny cases
6578               // with INT_MIN.
6579
6580   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6581   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6582   // C2 (CI). By solving for X we can turn this into a range check 
6583   // instead of computing a divide. 
6584   Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
6585
6586   // Determine if the product overflows by seeing if the product is
6587   // not equal to the divide. Make sure we do the same kind of divide
6588   // as in the LHS instruction that we're folding. 
6589   bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6590                  Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
6591
6592   // Get the ICmp opcode
6593   ICmpInst::Predicate Pred = ICI.getPredicate();
6594
6595   // Figure out the interval that is being checked.  For example, a comparison
6596   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6597   // Compute this interval based on the constants involved and the signedness of
6598   // the compare/divide.  This computes a half-open interval, keeping track of
6599   // whether either value in the interval overflows.  After analysis each
6600   // overflow variable is set to 0 if it's corresponding bound variable is valid
6601   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6602   int LoOverflow = 0, HiOverflow = 0;
6603   Constant *LoBound = 0, *HiBound = 0;
6604   
6605   if (!DivIsSigned) {  // udiv
6606     // e.g. X/5 op 3  --> [15, 20)
6607     LoBound = Prod;
6608     HiOverflow = LoOverflow = ProdOV;
6609     if (!HiOverflow)
6610       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6611   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6612     if (CmpRHSV == 0) {       // (X / pos) op 0
6613       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6614       LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS, 
6615                                                                     Context)));
6616       HiBound = DivRHS;
6617     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6618       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6619       HiOverflow = LoOverflow = ProdOV;
6620       if (!HiOverflow)
6621         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6622     } else {                       // (X / pos) op neg
6623       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6624       HiBound = AddOne(Prod, Context);
6625       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6626       if (!LoOverflow) {
6627         ConstantInt* DivNeg =
6628                          cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6629         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6630                                      true) ? -1 : 0;
6631        }
6632     }
6633   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6634     if (CmpRHSV == 0) {       // (X / neg) op 0
6635       // e.g. X/-5 op 0  --> [-4, 5)
6636       LoBound = AddOne(DivRHS, Context);
6637       HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6638       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6639         HiOverflow = 1;            // [INTMIN+1, overflow)
6640         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6641       }
6642     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6643       // e.g. X/-5 op 3  --> [-19, -14)
6644       HiBound = AddOne(Prod, Context);
6645       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6646       if (!LoOverflow)
6647         LoOverflow = AddWithOverflow(LoBound, HiBound,
6648                                      DivRHS, Context, true) ? -1 : 0;
6649     } else {                       // (X / neg) op neg
6650       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6651       LoOverflow = HiOverflow = ProdOV;
6652       if (!HiOverflow)
6653         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6654     }
6655     
6656     // Dividing by a negative swaps the condition.  LT <-> GT
6657     Pred = ICmpInst::getSwappedPredicate(Pred);
6658   }
6659
6660   Value *X = DivI->getOperand(0);
6661   switch (Pred) {
6662   default: LLVM_UNREACHABLE("Unhandled icmp opcode!");
6663   case ICmpInst::ICMP_EQ:
6664     if (LoOverflow && HiOverflow)
6665       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6666     else if (HiOverflow)
6667       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6668                           ICmpInst::ICMP_UGE, X, LoBound);
6669     else if (LoOverflow)
6670       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6671                           ICmpInst::ICMP_ULT, X, HiBound);
6672     else
6673       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6674   case ICmpInst::ICMP_NE:
6675     if (LoOverflow && HiOverflow)
6676       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6677     else if (HiOverflow)
6678       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT : 
6679                           ICmpInst::ICMP_ULT, X, LoBound);
6680     else if (LoOverflow)
6681       return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE : 
6682                           ICmpInst::ICMP_UGE, X, HiBound);
6683     else
6684       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6685   case ICmpInst::ICMP_ULT:
6686   case ICmpInst::ICMP_SLT:
6687     if (LoOverflow == +1)   // Low bound is greater than input range.
6688       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6689     if (LoOverflow == -1)   // Low bound is less than input range.
6690       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6691     return new ICmpInst(*Context, Pred, X, LoBound);
6692   case ICmpInst::ICMP_UGT:
6693   case ICmpInst::ICMP_SGT:
6694     if (HiOverflow == +1)       // High bound greater than input range.
6695       return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6696     else if (HiOverflow == -1)  // High bound less than input range.
6697       return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6698     if (Pred == ICmpInst::ICMP_UGT)
6699       return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
6700     else
6701       return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
6702   }
6703 }
6704
6705
6706 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6707 ///
6708 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6709                                                           Instruction *LHSI,
6710                                                           ConstantInt *RHS) {
6711   const APInt &RHSV = RHS->getValue();
6712   
6713   switch (LHSI->getOpcode()) {
6714   case Instruction::Trunc:
6715     if (ICI.isEquality() && LHSI->hasOneUse()) {
6716       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6717       // of the high bits truncated out of x are known.
6718       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6719              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6720       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6721       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6722       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6723       
6724       // If all the high bits are known, we can do this xform.
6725       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6726         // Pull in the high bits from known-ones set.
6727         APInt NewRHS(RHS->getValue());
6728         NewRHS.zext(SrcBits);
6729         NewRHS |= KnownOne;
6730         return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
6731                             Context->getConstantInt(NewRHS));
6732       }
6733     }
6734     break;
6735       
6736   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6737     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6738       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6739       // fold the xor.
6740       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6741           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6742         Value *CompareVal = LHSI->getOperand(0);
6743         
6744         // If the sign bit of the XorCST is not set, there is no change to
6745         // the operation, just stop using the Xor.
6746         if (!XorCST->getValue().isNegative()) {
6747           ICI.setOperand(0, CompareVal);
6748           AddToWorkList(LHSI);
6749           return &ICI;
6750         }
6751         
6752         // Was the old condition true if the operand is positive?
6753         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6754         
6755         // If so, the new one isn't.
6756         isTrueIfPositive ^= true;
6757         
6758         if (isTrueIfPositive)
6759           return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
6760                               SubOne(RHS, Context));
6761         else
6762           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
6763                               AddOne(RHS, Context));
6764       }
6765
6766       if (LHSI->hasOneUse()) {
6767         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6768         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6769           const APInt &SignBit = XorCST->getValue();
6770           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6771                                          ? ICI.getUnsignedPredicate()
6772                                          : ICI.getSignedPredicate();
6773           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6774                               Context->getConstantInt(RHSV ^ SignBit));
6775         }
6776
6777         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6778         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6779           const APInt &NotSignBit = XorCST->getValue();
6780           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6781                                          ? ICI.getUnsignedPredicate()
6782                                          : ICI.getSignedPredicate();
6783           Pred = ICI.getSwappedPredicate(Pred);
6784           return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6785                               Context->getConstantInt(RHSV ^ NotSignBit));
6786         }
6787       }
6788     }
6789     break;
6790   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6791     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6792         LHSI->getOperand(0)->hasOneUse()) {
6793       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6794       
6795       // If the LHS is an AND of a truncating cast, we can widen the
6796       // and/compare to be the input width without changing the value
6797       // produced, eliminating a cast.
6798       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6799         // We can do this transformation if either the AND constant does not
6800         // have its sign bit set or if it is an equality comparison. 
6801         // Extending a relational comparison when we're checking the sign
6802         // bit would not work.
6803         if (Cast->hasOneUse() &&
6804             (ICI.isEquality() ||
6805              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6806           uint32_t BitWidth = 
6807             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6808           APInt NewCST = AndCST->getValue();
6809           NewCST.zext(BitWidth);
6810           APInt NewCI = RHSV;
6811           NewCI.zext(BitWidth);
6812           Instruction *NewAnd = 
6813             BinaryOperator::CreateAnd(Cast->getOperand(0),
6814                                Context->getConstantInt(NewCST),LHSI->getName());
6815           InsertNewInstBefore(NewAnd, ICI);
6816           return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
6817                               Context->getConstantInt(NewCI));
6818         }
6819       }
6820       
6821       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6822       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6823       // happens a LOT in code produced by the C front-end, for bitfield
6824       // access.
6825       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6826       if (Shift && !Shift->isShift())
6827         Shift = 0;
6828       
6829       ConstantInt *ShAmt;
6830       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6831       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6832       const Type *AndTy = AndCST->getType();          // Type of the and.
6833       
6834       // We can fold this as long as we can't shift unknown bits
6835       // into the mask.  This can only happen with signed shift
6836       // rights, as they sign-extend.
6837       if (ShAmt) {
6838         bool CanFold = Shift->isLogicalShift();
6839         if (!CanFold) {
6840           // To test for the bad case of the signed shr, see if any
6841           // of the bits shifted in could be tested after the mask.
6842           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6843           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6844           
6845           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6846           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6847                AndCST->getValue()) == 0)
6848             CanFold = true;
6849         }
6850         
6851         if (CanFold) {
6852           Constant *NewCst;
6853           if (Shift->getOpcode() == Instruction::Shl)
6854             NewCst = Context->getConstantExprLShr(RHS, ShAmt);
6855           else
6856             NewCst = Context->getConstantExprShl(RHS, ShAmt);
6857           
6858           // Check to see if we are shifting out any of the bits being
6859           // compared.
6860           if (Context->getConstantExpr(Shift->getOpcode(),
6861                                        NewCst, ShAmt) != RHS) {
6862             // If we shifted bits out, the fold is not going to work out.
6863             // As a special case, check to see if this means that the
6864             // result is always true or false now.
6865             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6866               return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6867             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6868               return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6869           } else {
6870             ICI.setOperand(1, NewCst);
6871             Constant *NewAndCST;
6872             if (Shift->getOpcode() == Instruction::Shl)
6873               NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
6874             else
6875               NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
6876             LHSI->setOperand(1, NewAndCST);
6877             LHSI->setOperand(0, Shift->getOperand(0));
6878             AddToWorkList(Shift); // Shift is dead.
6879             AddUsesToWorkList(ICI);
6880             return &ICI;
6881           }
6882         }
6883       }
6884       
6885       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6886       // preferable because it allows the C<<Y expression to be hoisted out
6887       // of a loop if Y is invariant and X is not.
6888       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6889           ICI.isEquality() && !Shift->isArithmeticShift() &&
6890           !isa<Constant>(Shift->getOperand(0))) {
6891         // Compute C << Y.
6892         Value *NS;
6893         if (Shift->getOpcode() == Instruction::LShr) {
6894           NS = BinaryOperator::CreateShl(AndCST, 
6895                                          Shift->getOperand(1), "tmp");
6896         } else {
6897           // Insert a logical shift.
6898           NS = BinaryOperator::CreateLShr(AndCST,
6899                                           Shift->getOperand(1), "tmp");
6900         }
6901         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6902         
6903         // Compute X & (C << Y).
6904         Instruction *NewAnd = 
6905           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6906         InsertNewInstBefore(NewAnd, ICI);
6907         
6908         ICI.setOperand(0, NewAnd);
6909         return &ICI;
6910       }
6911     }
6912     break;
6913     
6914   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6915     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6916     if (!ShAmt) break;
6917     
6918     uint32_t TypeBits = RHSV.getBitWidth();
6919     
6920     // Check that the shift amount is in range.  If not, don't perform
6921     // undefined shifts.  When the shift is visited it will be
6922     // simplified.
6923     if (ShAmt->uge(TypeBits))
6924       break;
6925     
6926     if (ICI.isEquality()) {
6927       // If we are comparing against bits always shifted out, the
6928       // comparison cannot succeed.
6929       Constant *Comp =
6930         Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6931                                                                  ShAmt);
6932       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6933         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6934         Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
6935         return ReplaceInstUsesWith(ICI, Cst);
6936       }
6937       
6938       if (LHSI->hasOneUse()) {
6939         // Otherwise strength reduce the shift into an and.
6940         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6941         Constant *Mask =
6942           Context->getConstantInt(APInt::getLowBitsSet(TypeBits, 
6943                                                        TypeBits-ShAmtVal));
6944         
6945         Instruction *AndI =
6946           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6947                                     Mask, LHSI->getName()+".mask");
6948         Value *And = InsertNewInstBefore(AndI, ICI);
6949         return new ICmpInst(*Context, ICI.getPredicate(), And,
6950                             Context->getConstantInt(RHSV.lshr(ShAmtVal)));
6951       }
6952     }
6953     
6954     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6955     bool TrueIfSigned = false;
6956     if (LHSI->hasOneUse() &&
6957         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6958       // (X << 31) <s 0  --> (X&1) != 0
6959       Constant *Mask = Context->getConstantInt(APInt(TypeBits, 1) <<
6960                                            (TypeBits-ShAmt->getZExtValue()-1));
6961       Instruction *AndI =
6962         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6963                                   Mask, LHSI->getName()+".mask");
6964       Value *And = InsertNewInstBefore(AndI, ICI);
6965       
6966       return new ICmpInst(*Context,
6967                           TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6968                           And, Context->getNullValue(And->getType()));
6969     }
6970     break;
6971   }
6972     
6973   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6974   case Instruction::AShr: {
6975     // Only handle equality comparisons of shift-by-constant.
6976     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6977     if (!ShAmt || !ICI.isEquality()) break;
6978
6979     // Check that the shift amount is in range.  If not, don't perform
6980     // undefined shifts.  When the shift is visited it will be
6981     // simplified.
6982     uint32_t TypeBits = RHSV.getBitWidth();
6983     if (ShAmt->uge(TypeBits))
6984       break;
6985     
6986     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6987       
6988     // If we are comparing against bits always shifted out, the
6989     // comparison cannot succeed.
6990     APInt Comp = RHSV << ShAmtVal;
6991     if (LHSI->getOpcode() == Instruction::LShr)
6992       Comp = Comp.lshr(ShAmtVal);
6993     else
6994       Comp = Comp.ashr(ShAmtVal);
6995     
6996     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6997       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6998       Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
6999       return ReplaceInstUsesWith(ICI, Cst);
7000     }
7001     
7002     // Otherwise, check to see if the bits shifted out are known to be zero.
7003     // If so, we can compare against the unshifted value:
7004     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
7005     if (LHSI->hasOneUse() &&
7006         MaskedValueIsZero(LHSI->getOperand(0), 
7007                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
7008       return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
7009                           Context->getConstantExprShl(RHS, ShAmt));
7010     }
7011       
7012     if (LHSI->hasOneUse()) {
7013       // Otherwise strength reduce the shift into an and.
7014       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
7015       Constant *Mask = Context->getConstantInt(Val);
7016       
7017       Instruction *AndI =
7018         BinaryOperator::CreateAnd(LHSI->getOperand(0),
7019                                   Mask, LHSI->getName()+".mask");
7020       Value *And = InsertNewInstBefore(AndI, ICI);
7021       return new ICmpInst(*Context, ICI.getPredicate(), And,
7022                           Context->getConstantExprShl(RHS, ShAmt));
7023     }
7024     break;
7025   }
7026     
7027   case Instruction::SDiv:
7028   case Instruction::UDiv:
7029     // Fold: icmp pred ([us]div X, C1), C2 -> range test
7030     // Fold this div into the comparison, producing a range check. 
7031     // Determine, based on the divide type, what the range is being 
7032     // checked.  If there is an overflow on the low or high side, remember 
7033     // it, otherwise compute the range [low, hi) bounding the new value.
7034     // See: InsertRangeTest above for the kinds of replacements possible.
7035     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7036       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7037                                           DivRHS))
7038         return R;
7039     break;
7040
7041   case Instruction::Add:
7042     // Fold: icmp pred (add, X, C1), C2
7043
7044     if (!ICI.isEquality()) {
7045       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7046       if (!LHSC) break;
7047       const APInt &LHSV = LHSC->getValue();
7048
7049       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7050                             .subtract(LHSV);
7051
7052       if (ICI.isSignedPredicate()) {
7053         if (CR.getLower().isSignBit()) {
7054           return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7055                               Context->getConstantInt(CR.getUpper()));
7056         } else if (CR.getUpper().isSignBit()) {
7057           return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7058                               Context->getConstantInt(CR.getLower()));
7059         }
7060       } else {
7061         if (CR.getLower().isMinValue()) {
7062           return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7063                               Context->getConstantInt(CR.getUpper()));
7064         } else if (CR.getUpper().isMinValue()) {
7065           return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7066                               Context->getConstantInt(CR.getLower()));
7067         }
7068       }
7069     }
7070     break;
7071   }
7072   
7073   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7074   if (ICI.isEquality()) {
7075     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7076     
7077     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7078     // the second operand is a constant, simplify a bit.
7079     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7080       switch (BO->getOpcode()) {
7081       case Instruction::SRem:
7082         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7083         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7084           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7085           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7086             Instruction *NewRem =
7087               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
7088                                          BO->getName());
7089             InsertNewInstBefore(NewRem, ICI);
7090             return new ICmpInst(*Context, ICI.getPredicate(), NewRem, 
7091                                 Context->getNullValue(BO->getType()));
7092           }
7093         }
7094         break;
7095       case Instruction::Add:
7096         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7097         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7098           if (BO->hasOneUse())
7099             return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7100                                 Context->getConstantExprSub(RHS, BOp1C));
7101         } else if (RHSV == 0) {
7102           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7103           // efficiently invertible, or if the add has just this one use.
7104           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7105           
7106           if (Value *NegVal = dyn_castNegVal(BOp1, Context))
7107             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
7108           else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
7109             return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
7110           else if (BO->hasOneUse()) {
7111             Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
7112             InsertNewInstBefore(Neg, ICI);
7113             Neg->takeName(BO);
7114             return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
7115           }
7116         }
7117         break;
7118       case Instruction::Xor:
7119         // For the xor case, we can xor two constants together, eliminating
7120         // the explicit xor.
7121         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7122           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0), 
7123                               Context->getConstantExprXor(RHS, BOC));
7124         
7125         // FALLTHROUGH
7126       case Instruction::Sub:
7127         // Replace (([sub|xor] A, B) != 0) with (A != B)
7128         if (RHSV == 0)
7129           return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7130                               BO->getOperand(1));
7131         break;
7132         
7133       case Instruction::Or:
7134         // If bits are being or'd in that are not present in the constant we
7135         // are comparing against, then the comparison could never succeed!
7136         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7137           Constant *NotCI = Context->getConstantExprNot(RHS);
7138           if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7139             return ReplaceInstUsesWith(ICI,
7140                                        Context->getConstantInt(Type::Int1Ty, 
7141                                        isICMP_NE));
7142         }
7143         break;
7144         
7145       case Instruction::And:
7146         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7147           // If bits are being compared against that are and'd out, then the
7148           // comparison can never succeed!
7149           if ((RHSV & ~BOC->getValue()) != 0)
7150             return ReplaceInstUsesWith(ICI,
7151                                        Context->getConstantInt(Type::Int1Ty,
7152                                        isICMP_NE));
7153           
7154           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7155           if (RHS == BOC && RHSV.isPowerOf2())
7156             return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
7157                                 ICmpInst::ICMP_NE, LHSI,
7158                                 Context->getNullValue(RHS->getType()));
7159           
7160           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7161           if (BOC->getValue().isSignBit()) {
7162             Value *X = BO->getOperand(0);
7163             Constant *Zero = Context->getNullValue(X->getType());
7164             ICmpInst::Predicate pred = isICMP_NE ? 
7165               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7166             return new ICmpInst(*Context, pred, X, Zero);
7167           }
7168           
7169           // ((X & ~7) == 0) --> X < 8
7170           if (RHSV == 0 && isHighOnes(BOC)) {
7171             Value *X = BO->getOperand(0);
7172             Constant *NegX = Context->getConstantExprNeg(BOC);
7173             ICmpInst::Predicate pred = isICMP_NE ? 
7174               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7175             return new ICmpInst(*Context, pred, X, NegX);
7176           }
7177         }
7178       default: break;
7179       }
7180     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7181       // Handle icmp {eq|ne} <intrinsic>, intcst.
7182       if (II->getIntrinsicID() == Intrinsic::bswap) {
7183         AddToWorkList(II);
7184         ICI.setOperand(0, II->getOperand(1));
7185         ICI.setOperand(1, Context->getConstantInt(RHSV.byteSwap()));
7186         return &ICI;
7187       }
7188     }
7189   }
7190   return 0;
7191 }
7192
7193 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7194 /// We only handle extending casts so far.
7195 ///
7196 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7197   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7198   Value *LHSCIOp        = LHSCI->getOperand(0);
7199   const Type *SrcTy     = LHSCIOp->getType();
7200   const Type *DestTy    = LHSCI->getType();
7201   Value *RHSCIOp;
7202
7203   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7204   // integer type is the same size as the pointer type.
7205   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7206       getTargetData().getPointerSizeInBits() == 
7207          cast<IntegerType>(DestTy)->getBitWidth()) {
7208     Value *RHSOp = 0;
7209     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7210       RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
7211     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7212       RHSOp = RHSC->getOperand(0);
7213       // If the pointer types don't match, insert a bitcast.
7214       if (LHSCIOp->getType() != RHSOp->getType())
7215         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
7216     }
7217
7218     if (RHSOp)
7219       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
7220   }
7221   
7222   // The code below only handles extension cast instructions, so far.
7223   // Enforce this.
7224   if (LHSCI->getOpcode() != Instruction::ZExt &&
7225       LHSCI->getOpcode() != Instruction::SExt)
7226     return 0;
7227
7228   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7229   bool isSignedCmp = ICI.isSignedPredicate();
7230
7231   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7232     // Not an extension from the same type?
7233     RHSCIOp = CI->getOperand(0);
7234     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7235       return 0;
7236     
7237     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7238     // and the other is a zext), then we can't handle this.
7239     if (CI->getOpcode() != LHSCI->getOpcode())
7240       return 0;
7241
7242     // Deal with equality cases early.
7243     if (ICI.isEquality())
7244       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7245
7246     // A signed comparison of sign extended values simplifies into a
7247     // signed comparison.
7248     if (isSignedCmp && isSignedExt)
7249       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7250
7251     // The other three cases all fold into an unsigned comparison.
7252     return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7253   }
7254
7255   // If we aren't dealing with a constant on the RHS, exit early
7256   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7257   if (!CI)
7258     return 0;
7259
7260   // Compute the constant that would happen if we truncated to SrcTy then
7261   // reextended to DestTy.
7262   Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7263   Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7264                                                 Res1, DestTy);
7265
7266   // If the re-extended constant didn't change...
7267   if (Res2 == CI) {
7268     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7269     // For example, we might have:
7270     //    %A = sext i16 %X to i32
7271     //    %B = icmp ugt i32 %A, 1330
7272     // It is incorrect to transform this into 
7273     //    %B = icmp ugt i16 %X, 1330
7274     // because %A may have negative value. 
7275     //
7276     // However, we allow this when the compare is EQ/NE, because they are
7277     // signless.
7278     if (isSignedExt == isSignedCmp || ICI.isEquality())
7279       return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
7280     return 0;
7281   }
7282
7283   // The re-extended constant changed so the constant cannot be represented 
7284   // in the shorter type. Consequently, we cannot emit a simple comparison.
7285
7286   // First, handle some easy cases. We know the result cannot be equal at this
7287   // point so handle the ICI.isEquality() cases
7288   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7289     return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
7290   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7291     return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
7292
7293   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7294   // should have been folded away previously and not enter in here.
7295   Value *Result;
7296   if (isSignedCmp) {
7297     // We're performing a signed comparison.
7298     if (cast<ConstantInt>(CI)->getValue().isNegative())
7299       Result = Context->getConstantIntFalse();          // X < (small) --> false
7300     else
7301       Result = Context->getConstantIntTrue();           // X < (large) --> true
7302   } else {
7303     // We're performing an unsigned comparison.
7304     if (isSignedExt) {
7305       // We're performing an unsigned comp with a sign extended value.
7306       // This is true if the input is >= 0. [aka >s -1]
7307       Constant *NegOne = Context->getAllOnesValue(SrcTy);
7308       Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT, 
7309                                    LHSCIOp, NegOne, ICI.getName()), ICI);
7310     } else {
7311       // Unsigned extend & unsigned compare -> always true.
7312       Result = Context->getConstantIntTrue();
7313     }
7314   }
7315
7316   // Finally, return the value computed.
7317   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7318       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7319     return ReplaceInstUsesWith(ICI, Result);
7320
7321   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7322           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7323          "ICmp should be folded!");
7324   if (Constant *CI = dyn_cast<Constant>(Result))
7325     return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
7326   return BinaryOperator::CreateNot(*Context, Result);
7327 }
7328
7329 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7330   return commonShiftTransforms(I);
7331 }
7332
7333 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7334   return commonShiftTransforms(I);
7335 }
7336
7337 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7338   if (Instruction *R = commonShiftTransforms(I))
7339     return R;
7340   
7341   Value *Op0 = I.getOperand(0);
7342   
7343   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7344   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7345     if (CSI->isAllOnesValue())
7346       return ReplaceInstUsesWith(I, CSI);
7347
7348   // See if we can turn a signed shr into an unsigned shr.
7349   if (MaskedValueIsZero(Op0,
7350                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7351     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7352
7353   // Arithmetic shifting an all-sign-bit value is a no-op.
7354   unsigned NumSignBits = ComputeNumSignBits(Op0);
7355   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7356     return ReplaceInstUsesWith(I, Op0);
7357
7358   return 0;
7359 }
7360
7361 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7362   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7363   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7364
7365   // shl X, 0 == X and shr X, 0 == X
7366   // shl 0, X == 0 and shr 0, X == 0
7367   if (Op1 == Context->getNullValue(Op1->getType()) ||
7368       Op0 == Context->getNullValue(Op0->getType()))
7369     return ReplaceInstUsesWith(I, Op0);
7370   
7371   if (isa<UndefValue>(Op0)) {            
7372     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7373       return ReplaceInstUsesWith(I, Op0);
7374     else                                    // undef << X -> 0, undef >>u X -> 0
7375       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7376   }
7377   if (isa<UndefValue>(Op1)) {
7378     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7379       return ReplaceInstUsesWith(I, Op0);          
7380     else                                     // X << undef, X >>u undef -> 0
7381       return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7382   }
7383
7384   // See if we can fold away this shift.
7385   if (SimplifyDemandedInstructionBits(I))
7386     return &I;
7387
7388   // Try to fold constant and into select arguments.
7389   if (isa<Constant>(Op0))
7390     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7391       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7392         return R;
7393
7394   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7395     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7396       return Res;
7397   return 0;
7398 }
7399
7400 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7401                                                BinaryOperator &I) {
7402   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7403
7404   // See if we can simplify any instructions used by the instruction whose sole 
7405   // purpose is to compute bits we don't care about.
7406   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7407   
7408   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7409   // a signed shift.
7410   //
7411   if (Op1->uge(TypeBits)) {
7412     if (I.getOpcode() != Instruction::AShr)
7413       return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
7414     else {
7415       I.setOperand(1, Context->getConstantInt(I.getType(), TypeBits-1));
7416       return &I;
7417     }
7418   }
7419   
7420   // ((X*C1) << C2) == (X * (C1 << C2))
7421   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7422     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7423       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7424         return BinaryOperator::CreateMul(BO->getOperand(0),
7425                                         Context->getConstantExprShl(BOOp, Op1));
7426   
7427   // Try to fold constant and into select arguments.
7428   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7429     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7430       return R;
7431   if (isa<PHINode>(Op0))
7432     if (Instruction *NV = FoldOpIntoPhi(I))
7433       return NV;
7434   
7435   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7436   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7437     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7438     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7439     // place.  Don't try to do this transformation in this case.  Also, we
7440     // require that the input operand is a shift-by-constant so that we have
7441     // confidence that the shifts will get folded together.  We could do this
7442     // xform in more cases, but it is unlikely to be profitable.
7443     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7444         isa<ConstantInt>(TrOp->getOperand(1))) {
7445       // Okay, we'll do this xform.  Make the shift of shift.
7446       Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
7447       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7448                                                 I.getName());
7449       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7450
7451       // For logical shifts, the truncation has the effect of making the high
7452       // part of the register be zeros.  Emulate this by inserting an AND to
7453       // clear the top bits as needed.  This 'and' will usually be zapped by
7454       // other xforms later if dead.
7455       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7456       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7457       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7458       
7459       // The mask we constructed says what the trunc would do if occurring
7460       // between the shifts.  We want to know the effect *after* the second
7461       // shift.  We know that it is a logical shift by a constant, so adjust the
7462       // mask as appropriate.
7463       if (I.getOpcode() == Instruction::Shl)
7464         MaskV <<= Op1->getZExtValue();
7465       else {
7466         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7467         MaskV = MaskV.lshr(Op1->getZExtValue());
7468       }
7469
7470       Instruction *And =
7471         BinaryOperator::CreateAnd(NSh, Context->getConstantInt(MaskV), 
7472                                   TI->getName());
7473       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7474
7475       // Return the value truncated to the interesting size.
7476       return new TruncInst(And, I.getType());
7477     }
7478   }
7479   
7480   if (Op0->hasOneUse()) {
7481     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7482       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7483       Value *V1, *V2;
7484       ConstantInt *CC;
7485       switch (Op0BO->getOpcode()) {
7486         default: break;
7487         case Instruction::Add:
7488         case Instruction::And:
7489         case Instruction::Or:
7490         case Instruction::Xor: {
7491           // These operators commute.
7492           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7493           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7494               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7495                     m_Specific(Op1)), *Context)){
7496             Instruction *YS = BinaryOperator::CreateShl(
7497                                             Op0BO->getOperand(0), Op1,
7498                                             Op0BO->getName());
7499             InsertNewInstBefore(YS, I); // (Y << C)
7500             Instruction *X = 
7501               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7502                                      Op0BO->getOperand(1)->getName());
7503             InsertNewInstBefore(X, I);  // (X + (Y << C))
7504             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7505             return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7506                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7507           }
7508           
7509           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7510           Value *Op0BOOp1 = Op0BO->getOperand(1);
7511           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7512               match(Op0BOOp1, 
7513                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7514                           m_ConstantInt(CC)), *Context) &&
7515               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7516             Instruction *YS = BinaryOperator::CreateShl(
7517                                                      Op0BO->getOperand(0), Op1,
7518                                                      Op0BO->getName());
7519             InsertNewInstBefore(YS, I); // (Y << C)
7520             Instruction *XM =
7521               BinaryOperator::CreateAnd(V1,
7522                                         Context->getConstantExprShl(CC, Op1),
7523                                         V1->getName()+".mask");
7524             InsertNewInstBefore(XM, I); // X & (CC << C)
7525             
7526             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7527           }
7528         }
7529           
7530         // FALL THROUGH.
7531         case Instruction::Sub: {
7532           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7533           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7534               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7535                     m_Specific(Op1)), *Context)){
7536             Instruction *YS = BinaryOperator::CreateShl(
7537                                                      Op0BO->getOperand(1), Op1,
7538                                                      Op0BO->getName());
7539             InsertNewInstBefore(YS, I); // (Y << C)
7540             Instruction *X =
7541               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7542                                      Op0BO->getOperand(0)->getName());
7543             InsertNewInstBefore(X, I);  // (X + (Y << C))
7544             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7545             return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7546                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7547           }
7548           
7549           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7550           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7551               match(Op0BO->getOperand(0),
7552                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7553                           m_ConstantInt(CC)), *Context) && V2 == Op1 &&
7554               cast<BinaryOperator>(Op0BO->getOperand(0))
7555                   ->getOperand(0)->hasOneUse()) {
7556             Instruction *YS = BinaryOperator::CreateShl(
7557                                                      Op0BO->getOperand(1), Op1,
7558                                                      Op0BO->getName());
7559             InsertNewInstBefore(YS, I); // (Y << C)
7560             Instruction *XM =
7561               BinaryOperator::CreateAnd(V1, 
7562                                         Context->getConstantExprShl(CC, Op1),
7563                                         V1->getName()+".mask");
7564             InsertNewInstBefore(XM, I); // X & (CC << C)
7565             
7566             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7567           }
7568           
7569           break;
7570         }
7571       }
7572       
7573       
7574       // If the operand is an bitwise operator with a constant RHS, and the
7575       // shift is the only use, we can pull it out of the shift.
7576       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7577         bool isValid = true;     // Valid only for And, Or, Xor
7578         bool highBitSet = false; // Transform if high bit of constant set?
7579         
7580         switch (Op0BO->getOpcode()) {
7581           default: isValid = false; break;   // Do not perform transform!
7582           case Instruction::Add:
7583             isValid = isLeftShift;
7584             break;
7585           case Instruction::Or:
7586           case Instruction::Xor:
7587             highBitSet = false;
7588             break;
7589           case Instruction::And:
7590             highBitSet = true;
7591             break;
7592         }
7593         
7594         // If this is a signed shift right, and the high bit is modified
7595         // by the logical operation, do not perform the transformation.
7596         // The highBitSet boolean indicates the value of the high bit of
7597         // the constant which would cause it to be modified for this
7598         // operation.
7599         //
7600         if (isValid && I.getOpcode() == Instruction::AShr)
7601           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7602         
7603         if (isValid) {
7604           Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
7605           
7606           Instruction *NewShift =
7607             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7608           InsertNewInstBefore(NewShift, I);
7609           NewShift->takeName(Op0BO);
7610           
7611           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7612                                         NewRHS);
7613         }
7614       }
7615     }
7616   }
7617   
7618   // Find out if this is a shift of a shift by a constant.
7619   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7620   if (ShiftOp && !ShiftOp->isShift())
7621     ShiftOp = 0;
7622   
7623   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7624     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7625     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7626     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7627     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7628     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7629     Value *X = ShiftOp->getOperand(0);
7630     
7631     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7632     
7633     const IntegerType *Ty = cast<IntegerType>(I.getType());
7634     
7635     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7636     if (I.getOpcode() == ShiftOp->getOpcode()) {
7637       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7638       // saturates.
7639       if (AmtSum >= TypeBits) {
7640         if (I.getOpcode() != Instruction::AShr)
7641           return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7642         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7643       }
7644       
7645       return BinaryOperator::Create(I.getOpcode(), X,
7646                                     Context->getConstantInt(Ty, AmtSum));
7647     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7648                I.getOpcode() == Instruction::AShr) {
7649       if (AmtSum >= TypeBits)
7650         return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7651       
7652       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7653       return BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, AmtSum));
7654     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7655                I.getOpcode() == Instruction::LShr) {
7656       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7657       if (AmtSum >= TypeBits)
7658         AmtSum = TypeBits-1;
7659       
7660       Instruction *Shift =
7661         BinaryOperator::CreateAShr(X, Context->getConstantInt(Ty, AmtSum));
7662       InsertNewInstBefore(Shift, I);
7663
7664       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7665       return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7666     }
7667     
7668     // Okay, if we get here, one shift must be left, and the other shift must be
7669     // right.  See if the amounts are equal.
7670     if (ShiftAmt1 == ShiftAmt2) {
7671       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7672       if (I.getOpcode() == Instruction::Shl) {
7673         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7674         return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7675       }
7676       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7677       if (I.getOpcode() == Instruction::LShr) {
7678         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7679         return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7680       }
7681       // We can simplify ((X << C) >>s C) into a trunc + sext.
7682       // NOTE: we could do this for any C, but that would make 'unusual' integer
7683       // types.  For now, just stick to ones well-supported by the code
7684       // generators.
7685       const Type *SExtType = 0;
7686       switch (Ty->getBitWidth() - ShiftAmt1) {
7687       case 1  :
7688       case 8  :
7689       case 16 :
7690       case 32 :
7691       case 64 :
7692       case 128:
7693         SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
7694         break;
7695       default: break;
7696       }
7697       if (SExtType) {
7698         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7699         InsertNewInstBefore(NewTrunc, I);
7700         return new SExtInst(NewTrunc, Ty);
7701       }
7702       // Otherwise, we can't handle it yet.
7703     } else if (ShiftAmt1 < ShiftAmt2) {
7704       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7705       
7706       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7707       if (I.getOpcode() == Instruction::Shl) {
7708         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7709                ShiftOp->getOpcode() == Instruction::AShr);
7710         Instruction *Shift =
7711           BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7712         InsertNewInstBefore(Shift, I);
7713         
7714         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7715         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7716       }
7717       
7718       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7719       if (I.getOpcode() == Instruction::LShr) {
7720         assert(ShiftOp->getOpcode() == Instruction::Shl);
7721         Instruction *Shift =
7722           BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, ShiftDiff));
7723         InsertNewInstBefore(Shift, I);
7724         
7725         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7726         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7727       }
7728       
7729       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7730     } else {
7731       assert(ShiftAmt2 < ShiftAmt1);
7732       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7733
7734       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7735       if (I.getOpcode() == Instruction::Shl) {
7736         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7737                ShiftOp->getOpcode() == Instruction::AShr);
7738         Instruction *Shift =
7739           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7740                                  Context->getConstantInt(Ty, ShiftDiff));
7741         InsertNewInstBefore(Shift, I);
7742         
7743         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7744         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7745       }
7746       
7747       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7748       if (I.getOpcode() == Instruction::LShr) {
7749         assert(ShiftOp->getOpcode() == Instruction::Shl);
7750         Instruction *Shift =
7751           BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7752         InsertNewInstBefore(Shift, I);
7753         
7754         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7755         return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7756       }
7757       
7758       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7759     }
7760   }
7761   return 0;
7762 }
7763
7764
7765 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7766 /// expression.  If so, decompose it, returning some value X, such that Val is
7767 /// X*Scale+Offset.
7768 ///
7769 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7770                                         int &Offset, LLVMContext *Context) {
7771   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7772   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7773     Offset = CI->getZExtValue();
7774     Scale  = 0;
7775     return Context->getConstantInt(Type::Int32Ty, 0);
7776   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7777     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7778       if (I->getOpcode() == Instruction::Shl) {
7779         // This is a value scaled by '1 << the shift amt'.
7780         Scale = 1U << RHS->getZExtValue();
7781         Offset = 0;
7782         return I->getOperand(0);
7783       } else if (I->getOpcode() == Instruction::Mul) {
7784         // This value is scaled by 'RHS'.
7785         Scale = RHS->getZExtValue();
7786         Offset = 0;
7787         return I->getOperand(0);
7788       } else if (I->getOpcode() == Instruction::Add) {
7789         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7790         // where C1 is divisible by C2.
7791         unsigned SubScale;
7792         Value *SubVal = 
7793           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7794                                     Offset, Context);
7795         Offset += RHS->getZExtValue();
7796         Scale = SubScale;
7797         return SubVal;
7798       }
7799     }
7800   }
7801
7802   // Otherwise, we can't look past this.
7803   Scale = 1;
7804   Offset = 0;
7805   return Val;
7806 }
7807
7808
7809 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7810 /// try to eliminate the cast by moving the type information into the alloc.
7811 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7812                                                    AllocationInst &AI) {
7813   const PointerType *PTy = cast<PointerType>(CI.getType());
7814   
7815   // Remove any uses of AI that are dead.
7816   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7817   
7818   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7819     Instruction *User = cast<Instruction>(*UI++);
7820     if (isInstructionTriviallyDead(User)) {
7821       while (UI != E && *UI == User)
7822         ++UI; // If this instruction uses AI more than once, don't break UI.
7823       
7824       ++NumDeadInst;
7825       DOUT << "IC: DCE: " << *User;
7826       EraseInstFromFunction(*User);
7827     }
7828   }
7829   
7830   // Get the type really allocated and the type casted to.
7831   const Type *AllocElTy = AI.getAllocatedType();
7832   const Type *CastElTy = PTy->getElementType();
7833   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7834
7835   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7836   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7837   if (CastElTyAlign < AllocElTyAlign) return 0;
7838
7839   // If the allocation has multiple uses, only promote it if we are strictly
7840   // increasing the alignment of the resultant allocation.  If we keep it the
7841   // same, we open the door to infinite loops of various kinds.  (A reference
7842   // from a dbg.declare doesn't count as a use for this purpose.)
7843   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7844       CastElTyAlign == AllocElTyAlign) return 0;
7845
7846   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7847   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7848   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7849
7850   // See if we can satisfy the modulus by pulling a scale out of the array
7851   // size argument.
7852   unsigned ArraySizeScale;
7853   int ArrayOffset;
7854   Value *NumElements = // See if the array size is a decomposable linear expr.
7855     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7856                               ArrayOffset, Context);
7857  
7858   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7859   // do the xform.
7860   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7861       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7862
7863   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7864   Value *Amt = 0;
7865   if (Scale == 1) {
7866     Amt = NumElements;
7867   } else {
7868     // If the allocation size is constant, form a constant mul expression
7869     Amt = Context->getConstantInt(Type::Int32Ty, Scale);
7870     if (isa<ConstantInt>(NumElements))
7871       Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
7872                                  cast<ConstantInt>(Amt));
7873     // otherwise multiply the amount and the number of elements
7874     else {
7875       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7876       Amt = InsertNewInstBefore(Tmp, AI);
7877     }
7878   }
7879   
7880   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7881     Value *Off = Context->getConstantInt(Type::Int32Ty, Offset, true);
7882     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7883     Amt = InsertNewInstBefore(Tmp, AI);
7884   }
7885   
7886   AllocationInst *New;
7887   if (isa<MallocInst>(AI))
7888     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7889   else
7890     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7891   InsertNewInstBefore(New, AI);
7892   New->takeName(&AI);
7893   
7894   // If the allocation has one real use plus a dbg.declare, just remove the
7895   // declare.
7896   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7897     EraseInstFromFunction(*DI);
7898   }
7899   // If the allocation has multiple real uses, insert a cast and change all
7900   // things that used it to use the new cast.  This will also hack on CI, but it
7901   // will die soon.
7902   else if (!AI.hasOneUse()) {
7903     AddUsesToWorkList(AI);
7904     // New is the allocation instruction, pointer typed. AI is the original
7905     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7906     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7907     InsertNewInstBefore(NewCast, AI);
7908     AI.replaceAllUsesWith(NewCast);
7909   }
7910   return ReplaceInstUsesWith(CI, New);
7911 }
7912
7913 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7914 /// and return it as type Ty without inserting any new casts and without
7915 /// changing the computed value.  This is used by code that tries to decide
7916 /// whether promoting or shrinking integer operations to wider or smaller types
7917 /// will allow us to eliminate a truncate or extend.
7918 ///
7919 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7920 /// extension operation if Ty is larger.
7921 ///
7922 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7923 /// should return true if trunc(V) can be computed by computing V in the smaller
7924 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7925 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7926 /// efficiently truncated.
7927 ///
7928 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7929 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7930 /// the final result.
7931 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7932                                               unsigned CastOpc,
7933                                               int &NumCastsRemoved){
7934   // We can always evaluate constants in another type.
7935   if (isa<Constant>(V))
7936     return true;
7937   
7938   Instruction *I = dyn_cast<Instruction>(V);
7939   if (!I) return false;
7940   
7941   const Type *OrigTy = V->getType();
7942   
7943   // If this is an extension or truncate, we can often eliminate it.
7944   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7945     // If this is a cast from the destination type, we can trivially eliminate
7946     // it, and this will remove a cast overall.
7947     if (I->getOperand(0)->getType() == Ty) {
7948       // If the first operand is itself a cast, and is eliminable, do not count
7949       // this as an eliminable cast.  We would prefer to eliminate those two
7950       // casts first.
7951       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7952         ++NumCastsRemoved;
7953       return true;
7954     }
7955   }
7956
7957   // We can't extend or shrink something that has multiple uses: doing so would
7958   // require duplicating the instruction in general, which isn't profitable.
7959   if (!I->hasOneUse()) return false;
7960
7961   unsigned Opc = I->getOpcode();
7962   switch (Opc) {
7963   case Instruction::Add:
7964   case Instruction::Sub:
7965   case Instruction::Mul:
7966   case Instruction::And:
7967   case Instruction::Or:
7968   case Instruction::Xor:
7969     // These operators can all arbitrarily be extended or truncated.
7970     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7971                                       NumCastsRemoved) &&
7972            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7973                                       NumCastsRemoved);
7974
7975   case Instruction::Shl:
7976     // If we are truncating the result of this SHL, and if it's a shift of a
7977     // constant amount, we can always perform a SHL in a smaller type.
7978     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7979       uint32_t BitWidth = Ty->getScalarSizeInBits();
7980       if (BitWidth < OrigTy->getScalarSizeInBits() &&
7981           CI->getLimitedValue(BitWidth) < BitWidth)
7982         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7983                                           NumCastsRemoved);
7984     }
7985     break;
7986   case Instruction::LShr:
7987     // If this is a truncate of a logical shr, we can truncate it to a smaller
7988     // lshr iff we know that the bits we would otherwise be shifting in are
7989     // already zeros.
7990     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7991       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7992       uint32_t BitWidth = Ty->getScalarSizeInBits();
7993       if (BitWidth < OrigBitWidth &&
7994           MaskedValueIsZero(I->getOperand(0),
7995             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7996           CI->getLimitedValue(BitWidth) < BitWidth) {
7997         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7998                                           NumCastsRemoved);
7999       }
8000     }
8001     break;
8002   case Instruction::ZExt:
8003   case Instruction::SExt:
8004   case Instruction::Trunc:
8005     // If this is the same kind of case as our original (e.g. zext+zext), we
8006     // can safely replace it.  Note that replacing it does not reduce the number
8007     // of casts in the input.
8008     if (Opc == CastOpc)
8009       return true;
8010
8011     // sext (zext ty1), ty2 -> zext ty2
8012     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
8013       return true;
8014     break;
8015   case Instruction::Select: {
8016     SelectInst *SI = cast<SelectInst>(I);
8017     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8018                                       NumCastsRemoved) &&
8019            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8020                                       NumCastsRemoved);
8021   }
8022   case Instruction::PHI: {
8023     // We can change a phi if we can change all operands.
8024     PHINode *PN = cast<PHINode>(I);
8025     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8026       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8027                                       NumCastsRemoved))
8028         return false;
8029     return true;
8030   }
8031   default:
8032     // TODO: Can handle more cases here.
8033     break;
8034   }
8035   
8036   return false;
8037 }
8038
8039 /// EvaluateInDifferentType - Given an expression that 
8040 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8041 /// evaluate the expression.
8042 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
8043                                              bool isSigned) {
8044   if (Constant *C = dyn_cast<Constant>(V))
8045     return Context->getConstantExprIntegerCast(C, Ty,
8046                                                isSigned /*Sext or ZExt*/);
8047
8048   // Otherwise, it must be an instruction.
8049   Instruction *I = cast<Instruction>(V);
8050   Instruction *Res = 0;
8051   unsigned Opc = I->getOpcode();
8052   switch (Opc) {
8053   case Instruction::Add:
8054   case Instruction::Sub:
8055   case Instruction::Mul:
8056   case Instruction::And:
8057   case Instruction::Or:
8058   case Instruction::Xor:
8059   case Instruction::AShr:
8060   case Instruction::LShr:
8061   case Instruction::Shl: {
8062     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8063     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8064     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8065     break;
8066   }    
8067   case Instruction::Trunc:
8068   case Instruction::ZExt:
8069   case Instruction::SExt:
8070     // If the source type of the cast is the type we're trying for then we can
8071     // just return the source.  There's no need to insert it because it is not
8072     // new.
8073     if (I->getOperand(0)->getType() == Ty)
8074       return I->getOperand(0);
8075     
8076     // Otherwise, must be the same type of cast, so just reinsert a new one.
8077     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8078                            Ty);
8079     break;
8080   case Instruction::Select: {
8081     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8082     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8083     Res = SelectInst::Create(I->getOperand(0), True, False);
8084     break;
8085   }
8086   case Instruction::PHI: {
8087     PHINode *OPN = cast<PHINode>(I);
8088     PHINode *NPN = PHINode::Create(Ty);
8089     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8090       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8091       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8092     }
8093     Res = NPN;
8094     break;
8095   }
8096   default: 
8097     // TODO: Can handle more cases here.
8098     LLVM_UNREACHABLE("Unreachable!");
8099     break;
8100   }
8101   
8102   Res->takeName(I);
8103   return InsertNewInstBefore(Res, *I);
8104 }
8105
8106 /// @brief Implement the transforms common to all CastInst visitors.
8107 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8108   Value *Src = CI.getOperand(0);
8109
8110   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8111   // eliminate it now.
8112   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8113     if (Instruction::CastOps opc = 
8114         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8115       // The first cast (CSrc) is eliminable so we need to fix up or replace
8116       // the second cast (CI). CSrc will then have a good chance of being dead.
8117       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8118     }
8119   }
8120
8121   // If we are casting a select then fold the cast into the select
8122   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8123     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8124       return NV;
8125
8126   // If we are casting a PHI then fold the cast into the PHI
8127   if (isa<PHINode>(Src))
8128     if (Instruction *NV = FoldOpIntoPhi(CI))
8129       return NV;
8130   
8131   return 0;
8132 }
8133
8134 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8135 /// or not there is a sequence of GEP indices into the type that will land us at
8136 /// the specified offset.  If so, fill them into NewIndices and return the
8137 /// resultant element type, otherwise return null.
8138 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8139                                        SmallVectorImpl<Value*> &NewIndices,
8140                                        const TargetData *TD,
8141                                        LLVMContext *Context) {
8142   if (!Ty->isSized()) return 0;
8143   
8144   // Start with the index over the outer type.  Note that the type size
8145   // might be zero (even if the offset isn't zero) if the indexed type
8146   // is something like [0 x {int, int}]
8147   const Type *IntPtrTy = TD->getIntPtrType();
8148   int64_t FirstIdx = 0;
8149   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8150     FirstIdx = Offset/TySize;
8151     Offset -= FirstIdx*TySize;
8152     
8153     // Handle hosts where % returns negative instead of values [0..TySize).
8154     if (Offset < 0) {
8155       --FirstIdx;
8156       Offset += TySize;
8157       assert(Offset >= 0);
8158     }
8159     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8160   }
8161   
8162   NewIndices.push_back(Context->getConstantInt(IntPtrTy, FirstIdx));
8163     
8164   // Index into the types.  If we fail, set OrigBase to null.
8165   while (Offset) {
8166     // Indexing into tail padding between struct/array elements.
8167     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8168       return 0;
8169     
8170     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8171       const StructLayout *SL = TD->getStructLayout(STy);
8172       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8173              "Offset must stay within the indexed type");
8174       
8175       unsigned Elt = SL->getElementContainingOffset(Offset);
8176       NewIndices.push_back(Context->getConstantInt(Type::Int32Ty, Elt));
8177       
8178       Offset -= SL->getElementOffset(Elt);
8179       Ty = STy->getElementType(Elt);
8180     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8181       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8182       assert(EltSize && "Cannot index into a zero-sized array");
8183       NewIndices.push_back(Context->getConstantInt(IntPtrTy,Offset/EltSize));
8184       Offset %= EltSize;
8185       Ty = AT->getElementType();
8186     } else {
8187       // Otherwise, we can't index into the middle of this atomic type, bail.
8188       return 0;
8189     }
8190   }
8191   
8192   return Ty;
8193 }
8194
8195 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8196 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8197   Value *Src = CI.getOperand(0);
8198   
8199   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8200     // If casting the result of a getelementptr instruction with no offset, turn
8201     // this into a cast of the original pointer!
8202     if (GEP->hasAllZeroIndices()) {
8203       // Changing the cast operand is usually not a good idea but it is safe
8204       // here because the pointer operand is being replaced with another 
8205       // pointer operand so the opcode doesn't need to change.
8206       AddToWorkList(GEP);
8207       CI.setOperand(0, GEP->getOperand(0));
8208       return &CI;
8209     }
8210     
8211     // If the GEP has a single use, and the base pointer is a bitcast, and the
8212     // GEP computes a constant offset, see if we can convert these three
8213     // instructions into fewer.  This typically happens with unions and other
8214     // non-type-safe code.
8215     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8216       if (GEP->hasAllConstantIndices()) {
8217         // We are guaranteed to get a constant from EmitGEPOffset.
8218         ConstantInt *OffsetV =
8219                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8220         int64_t Offset = OffsetV->getSExtValue();
8221         
8222         // Get the base pointer input of the bitcast, and the type it points to.
8223         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8224         const Type *GEPIdxTy =
8225           cast<PointerType>(OrigBase->getType())->getElementType();
8226         SmallVector<Value*, 8> NewIndices;
8227         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8228           // If we were able to index down into an element, create the GEP
8229           // and bitcast the result.  This eliminates one bitcast, potentially
8230           // two.
8231           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
8232                                                         NewIndices.begin(),
8233                                                         NewIndices.end(), "");
8234           InsertNewInstBefore(NGEP, CI);
8235           NGEP->takeName(GEP);
8236           
8237           if (isa<BitCastInst>(CI))
8238             return new BitCastInst(NGEP, CI.getType());
8239           assert(isa<PtrToIntInst>(CI));
8240           return new PtrToIntInst(NGEP, CI.getType());
8241         }
8242       }      
8243     }
8244   }
8245     
8246   return commonCastTransforms(CI);
8247 }
8248
8249 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8250 /// type like i42.  We don't want to introduce operations on random non-legal
8251 /// integer types where they don't already exist in the code.  In the future,
8252 /// we should consider making this based off target-data, so that 32-bit targets
8253 /// won't get i64 operations etc.
8254 static bool isSafeIntegerType(const Type *Ty) {
8255   switch (Ty->getPrimitiveSizeInBits()) {
8256   case 8:
8257   case 16:
8258   case 32:
8259   case 64:
8260     return true;
8261   default: 
8262     return false;
8263   }
8264 }
8265
8266 /// Only the TRUNC, ZEXT, SEXT. This function implements the common transforms
8267 /// for all those cases.
8268 /// @brief Implement the transforms common to CastInst with integer operands
8269 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8270   if (Instruction *Result = commonCastTransforms(CI))
8271     return Result;
8272
8273   Value *Src = CI.getOperand(0);
8274   const Type *SrcTy = Src->getType();
8275   const Type *DestTy = CI.getType();
8276   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8277   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8278
8279   // See if we can simplify any instructions used by the LHS whose sole 
8280   // purpose is to compute bits we don't care about.
8281   if (SimplifyDemandedInstructionBits(CI))
8282     return &CI;
8283
8284   // If the source isn't an instruction or has more than one use then we
8285   // can't do anything more. 
8286   Instruction *SrcI = dyn_cast<Instruction>(Src);
8287   if (!SrcI || !Src->hasOneUse())
8288     return 0;
8289
8290   // Attempt to propagate the cast into the instruction for int->int casts.
8291   int NumCastsRemoved = 0;
8292   if (!isa<BitCastInst>(CI) &&
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       (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       case Instruction::BitCast:
8371         // Just replace this cast with the result.
8372         return ReplaceInstUsesWith(CI, Res);
8373       case Instruction::ZExt: {
8374         assert(SrcBitSize < DestBitSize && "Not a zext?");
8375
8376         // If the high bits are already zero, just replace this cast with the
8377         // result.
8378         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8379         if (MaskedValueIsZero(Res, Mask))
8380           return ReplaceInstUsesWith(CI, Res);
8381
8382         // We need to emit an AND to clear the high bits.
8383         Constant *C = Context->getConstantInt(APInt::getLowBitsSet(DestBitSize,
8384                                                             SrcBitSize));
8385         return BinaryOperator::CreateAnd(Res, C);
8386       }
8387       case Instruction::SExt: {
8388         // If the high bits are already filled with sign bit, just replace this
8389         // cast with the result.
8390         unsigned NumSignBits = ComputeNumSignBits(Res);
8391         if (NumSignBits > (DestBitSize - SrcBitSize))
8392           return ReplaceInstUsesWith(CI, Res);
8393
8394         // We need to emit a cast to truncate, then a cast to sext.
8395         return CastInst::Create(Instruction::SExt,
8396             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8397                              CI), DestTy);
8398       }
8399       }
8400     }
8401   }
8402   
8403   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8404   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8405
8406   switch (SrcI->getOpcode()) {
8407   case Instruction::Add:
8408   case Instruction::Mul:
8409   case Instruction::And:
8410   case Instruction::Or:
8411   case Instruction::Xor:
8412     // If we are discarding information, rewrite.
8413     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8414       // Don't insert two casts if they cannot be eliminated.  We allow 
8415       // two casts to be inserted if the sizes are the same.  This could 
8416       // only be converting signedness, which is a noop.
8417       if (DestBitSize == SrcBitSize || 
8418           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8419           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8420         Instruction::CastOps opcode = CI.getOpcode();
8421         Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8422         Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8423         return BinaryOperator::Create(
8424             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8425       }
8426     }
8427
8428     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8429     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8430         SrcI->getOpcode() == Instruction::Xor &&
8431         Op1 == Context->getConstantIntTrue() &&
8432         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8433       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8434       return BinaryOperator::CreateXor(New,
8435                                       Context->getConstantInt(CI.getType(), 1));
8436     }
8437     break;
8438   case Instruction::SDiv:
8439   case Instruction::UDiv:
8440   case Instruction::SRem:
8441   case Instruction::URem:
8442     // If we are just changing the sign, rewrite.
8443     if (DestBitSize == SrcBitSize) {
8444       // Don't insert two casts if they cannot be eliminated.  We allow 
8445       // two casts to be inserted if the sizes are the same.  This could 
8446       // only be converting signedness, which is a noop.
8447       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
8448           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8449         Value *Op0c = InsertCastBefore(Instruction::BitCast, 
8450                                        Op0, DestTy, *SrcI);
8451         Value *Op1c = InsertCastBefore(Instruction::BitCast, 
8452                                        Op1, DestTy, *SrcI);
8453         return BinaryOperator::Create(
8454           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8455       }
8456     }
8457     break;
8458
8459   case Instruction::Shl:
8460     // Allow changing the sign of the source operand.  Do not allow 
8461     // changing the size of the shift, UNLESS the shift amount is a 
8462     // constant.  We must not change variable sized shifts to a smaller 
8463     // size, because it is undefined to shift more bits out than exist 
8464     // in the value.
8465     if (DestBitSize == SrcBitSize ||
8466         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
8467       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8468           Instruction::BitCast : Instruction::Trunc);
8469       Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8470       Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8471       return BinaryOperator::CreateShl(Op0c, Op1c);
8472     }
8473     break;
8474   case Instruction::AShr:
8475     // If this is a signed shr, and if all bits shifted in are about to be
8476     // truncated off, turn it into an unsigned shr to allow greater
8477     // simplifications.
8478     if (DestBitSize < SrcBitSize &&
8479         isa<ConstantInt>(Op1)) {
8480       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
8481       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8482         // Insert the new logical shift right.
8483         return BinaryOperator::CreateLShr(Op0, Op1);
8484       }
8485     }
8486     break;
8487   }
8488   return 0;
8489 }
8490
8491 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8492   if (Instruction *Result = commonIntCastTransforms(CI))
8493     return Result;
8494   
8495   Value *Src = CI.getOperand(0);
8496   const Type *Ty = CI.getType();
8497   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8498   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8499
8500   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8501   if (DestBitWidth == 1 &&
8502       isa<VectorType>(Ty) == isa<VectorType>(Src->getType())) {
8503     Constant *One = Context->getConstantInt(Src->getType(), 1);
8504     Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8505     Value *Zero = Context->getNullValue(Src->getType());
8506     return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
8507   }
8508
8509   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8510   ConstantInt *ShAmtV = 0;
8511   Value *ShiftOp = 0;
8512   if (Src->hasOneUse() &&
8513       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
8514     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8515     
8516     // Get a mask for the bits shifting in.
8517     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8518     if (MaskedValueIsZero(ShiftOp, Mask)) {
8519       if (ShAmt >= DestBitWidth)        // All zeros.
8520         return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
8521       
8522       // Okay, we can shrink this.  Truncate the input, then return a new
8523       // shift.
8524       Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8525       Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
8526       return BinaryOperator::CreateLShr(V1, V2);
8527     }
8528   }
8529   
8530   return 0;
8531 }
8532
8533 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8534 /// in order to eliminate the icmp.
8535 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8536                                              bool DoXform) {
8537   // If we are just checking for a icmp eq of a single bit and zext'ing it
8538   // to an integer, then shift the bit to the appropriate place and then
8539   // cast to integer to avoid the comparison.
8540   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8541     const APInt &Op1CV = Op1C->getValue();
8542       
8543     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8544     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8545     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8546         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8547       if (!DoXform) return ICI;
8548
8549       Value *In = ICI->getOperand(0);
8550       Value *Sh = Context->getConstantInt(In->getType(),
8551                                    In->getType()->getScalarSizeInBits()-1);
8552       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8553                                                         In->getName()+".lobit"),
8554                                CI);
8555       if (In->getType() != CI.getType())
8556         In = CastInst::CreateIntegerCast(In, CI.getType(),
8557                                          false/*ZExt*/, "tmp", &CI);
8558
8559       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8560         Constant *One = Context->getConstantInt(In->getType(), 1);
8561         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8562                                                          In->getName()+".not"),
8563                                  CI);
8564       }
8565
8566       return ReplaceInstUsesWith(CI, In);
8567     }
8568       
8569       
8570       
8571     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8572     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8573     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8574     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8575     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8576     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8577     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8578     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8579     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8580         // This only works for EQ and NE
8581         ICI->isEquality()) {
8582       // If Op1C some other power of two, convert:
8583       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8584       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8585       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8586       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8587         
8588       APInt KnownZeroMask(~KnownZero);
8589       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8590         if (!DoXform) return ICI;
8591
8592         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8593         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8594           // (X&4) == 2 --> false
8595           // (X&4) != 2 --> true
8596           Constant *Res = Context->getConstantInt(Type::Int1Ty, isNE);
8597           Res = Context->getConstantExprZExt(Res, CI.getType());
8598           return ReplaceInstUsesWith(CI, Res);
8599         }
8600           
8601         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8602         Value *In = ICI->getOperand(0);
8603         if (ShiftAmt) {
8604           // Perform a logical shr by shiftamt.
8605           // Insert the shift to put the result in the low bit.
8606           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8607                               Context->getConstantInt(In->getType(), ShiftAmt),
8608                                                    In->getName()+".lobit"), CI);
8609         }
8610           
8611         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8612           Constant *One = Context->getConstantInt(In->getType(), 1);
8613           In = BinaryOperator::CreateXor(In, One, "tmp");
8614           InsertNewInstBefore(cast<Instruction>(In), CI);
8615         }
8616           
8617         if (CI.getType() == In->getType())
8618           return ReplaceInstUsesWith(CI, In);
8619         else
8620           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8621       }
8622     }
8623   }
8624
8625   return 0;
8626 }
8627
8628 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8629   // If one of the common conversion will work ..
8630   if (Instruction *Result = commonIntCastTransforms(CI))
8631     return Result;
8632
8633   Value *Src = CI.getOperand(0);
8634
8635   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8636   // types and if the sizes are just right we can convert this into a logical
8637   // 'and' which will be much cheaper than the pair of casts.
8638   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8639     // Get the sizes of the types involved.  We know that the intermediate type
8640     // will be smaller than A or C, but don't know the relation between A and C.
8641     Value *A = CSrc->getOperand(0);
8642     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8643     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8644     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8645     // If we're actually extending zero bits, then if
8646     // SrcSize <  DstSize: zext(a & mask)
8647     // SrcSize == DstSize: a & mask
8648     // SrcSize  > DstSize: trunc(a) & mask
8649     if (SrcSize < DstSize) {
8650       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8651       Constant *AndConst = Context->getConstantInt(A->getType(), AndValue);
8652       Instruction *And =
8653         BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8654       InsertNewInstBefore(And, CI);
8655       return new ZExtInst(And, CI.getType());
8656     } else if (SrcSize == DstSize) {
8657       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8658       return BinaryOperator::CreateAnd(A, Context->getConstantInt(A->getType(),
8659                                                            AndValue));
8660     } else if (SrcSize > DstSize) {
8661       Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8662       InsertNewInstBefore(Trunc, CI);
8663       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8664       return BinaryOperator::CreateAnd(Trunc, 
8665                                        Context->getConstantInt(Trunc->getType(),
8666                                                                AndValue));
8667     }
8668   }
8669
8670   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8671     return transformZExtICmp(ICI, CI);
8672
8673   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8674   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8675     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8676     // of the (zext icmp) will be transformed.
8677     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8678     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8679     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8680         (transformZExtICmp(LHS, CI, false) ||
8681          transformZExtICmp(RHS, CI, false))) {
8682       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8683       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8684       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8685     }
8686   }
8687
8688   // zext(trunc(t) & C) -> (t & zext(C)).
8689   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8690     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8691       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8692         Value *TI0 = TI->getOperand(0);
8693         if (TI0->getType() == CI.getType())
8694           return
8695             BinaryOperator::CreateAnd(TI0,
8696                                 Context->getConstantExprZExt(C, CI.getType()));
8697       }
8698
8699   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8700   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8701     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8702       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8703         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8704             And->getOperand(1) == C)
8705           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8706             Value *TI0 = TI->getOperand(0);
8707             if (TI0->getType() == CI.getType()) {
8708               Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
8709               Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8710               InsertNewInstBefore(NewAnd, *And);
8711               return BinaryOperator::CreateXor(NewAnd, ZC);
8712             }
8713           }
8714
8715   return 0;
8716 }
8717
8718 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8719   if (Instruction *I = commonIntCastTransforms(CI))
8720     return I;
8721   
8722   Value *Src = CI.getOperand(0);
8723   
8724   // Canonicalize sign-extend from i1 to a select.
8725   if (Src->getType() == Type::Int1Ty)
8726     return SelectInst::Create(Src,
8727                               Context->getAllOnesValue(CI.getType()),
8728                               Context->getNullValue(CI.getType()));
8729
8730   // See if the value being truncated is already sign extended.  If so, just
8731   // eliminate the trunc/sext pair.
8732   if (getOpcode(Src) == Instruction::Trunc) {
8733     Value *Op = cast<User>(Src)->getOperand(0);
8734     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8735     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8736     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8737     unsigned NumSignBits = ComputeNumSignBits(Op);
8738
8739     if (OpBits == DestBits) {
8740       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8741       // bits, it is already ready.
8742       if (NumSignBits > DestBits-MidBits)
8743         return ReplaceInstUsesWith(CI, Op);
8744     } else if (OpBits < DestBits) {
8745       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8746       // bits, just sext from i32.
8747       if (NumSignBits > OpBits-MidBits)
8748         return new SExtInst(Op, CI.getType(), "tmp");
8749     } else {
8750       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8751       // bits, just truncate to i32.
8752       if (NumSignBits > OpBits-MidBits)
8753         return new TruncInst(Op, CI.getType(), "tmp");
8754     }
8755   }
8756
8757   // If the input is a shl/ashr pair of a same constant, then this is a sign
8758   // extension from a smaller value.  If we could trust arbitrary bitwidth
8759   // integers, we could turn this into a truncate to the smaller bit and then
8760   // use a sext for the whole extension.  Since we don't, look deeper and check
8761   // for a truncate.  If the source and dest are the same type, eliminate the
8762   // trunc and extend and just do shifts.  For example, turn:
8763   //   %a = trunc i32 %i to i8
8764   //   %b = shl i8 %a, 6
8765   //   %c = ashr i8 %b, 6
8766   //   %d = sext i8 %c to i32
8767   // into:
8768   //   %a = shl i32 %i, 30
8769   //   %d = ashr i32 %a, 30
8770   Value *A = 0;
8771   ConstantInt *BA = 0, *CA = 0;
8772   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8773                         m_ConstantInt(CA)), *Context) &&
8774       BA == CA && isa<TruncInst>(A)) {
8775     Value *I = cast<TruncInst>(A)->getOperand(0);
8776     if (I->getType() == CI.getType()) {
8777       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8778       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8779       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8780       Constant *ShAmtV = Context->getConstantInt(CI.getType(), ShAmt);
8781       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8782                                                         CI.getName()), CI);
8783       return BinaryOperator::CreateAShr(I, ShAmtV);
8784     }
8785   }
8786   
8787   return 0;
8788 }
8789
8790 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8791 /// in the specified FP type without changing its value.
8792 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8793                               LLVMContext *Context) {
8794   bool losesInfo;
8795   APFloat F = CFP->getValueAPF();
8796   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8797   if (!losesInfo)
8798     return Context->getConstantFP(F);
8799   return 0;
8800 }
8801
8802 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8803 /// through it until we get the source value.
8804 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8805   if (Instruction *I = dyn_cast<Instruction>(V))
8806     if (I->getOpcode() == Instruction::FPExt)
8807       return LookThroughFPExtensions(I->getOperand(0), Context);
8808   
8809   // If this value is a constant, return the constant in the smallest FP type
8810   // that can accurately represent it.  This allows us to turn
8811   // (float)((double)X+2.0) into x+2.0f.
8812   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8813     if (CFP->getType() == Type::PPC_FP128Ty)
8814       return V;  // No constant folding of this.
8815     // See if the value can be truncated to float and then reextended.
8816     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8817       return V;
8818     if (CFP->getType() == Type::DoubleTy)
8819       return V;  // Won't shrink.
8820     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8821       return V;
8822     // Don't try to shrink to various long double types.
8823   }
8824   
8825   return V;
8826 }
8827
8828 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8829   if (Instruction *I = commonCastTransforms(CI))
8830     return I;
8831   
8832   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8833   // smaller than the destination type, we can eliminate the truncate by doing
8834   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8835   // many builtins (sqrt, etc).
8836   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8837   if (OpI && OpI->hasOneUse()) {
8838     switch (OpI->getOpcode()) {
8839     default: break;
8840     case Instruction::FAdd:
8841     case Instruction::FSub:
8842     case Instruction::FMul:
8843     case Instruction::FDiv:
8844     case Instruction::FRem:
8845       const Type *SrcTy = OpI->getType();
8846       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8847       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8848       if (LHSTrunc->getType() != SrcTy && 
8849           RHSTrunc->getType() != SrcTy) {
8850         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8851         // If the source types were both smaller than the destination type of
8852         // the cast, do this xform.
8853         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8854             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8855           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8856                                       CI.getType(), CI);
8857           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8858                                       CI.getType(), CI);
8859           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8860         }
8861       }
8862       break;  
8863     }
8864   }
8865   return 0;
8866 }
8867
8868 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8869   return commonCastTransforms(CI);
8870 }
8871
8872 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8873   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8874   if (OpI == 0)
8875     return commonCastTransforms(FI);
8876
8877   // fptoui(uitofp(X)) --> X
8878   // fptoui(sitofp(X)) --> X
8879   // This is safe if the intermediate type has enough bits in its mantissa to
8880   // accurately represent all values of X.  For example, do not do this with
8881   // i64->float->i64.  This is also safe for sitofp case, because any negative
8882   // 'X' value would cause an undefined result for the fptoui. 
8883   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8884       OpI->getOperand(0)->getType() == FI.getType() &&
8885       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8886                     OpI->getType()->getFPMantissaWidth())
8887     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8888
8889   return commonCastTransforms(FI);
8890 }
8891
8892 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8893   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8894   if (OpI == 0)
8895     return commonCastTransforms(FI);
8896   
8897   // fptosi(sitofp(X)) --> X
8898   // fptosi(uitofp(X)) --> X
8899   // This is safe if the intermediate type has enough bits in its mantissa to
8900   // accurately represent all values of X.  For example, do not do this with
8901   // i64->float->i64.  This is also safe for sitofp case, because any negative
8902   // 'X' value would cause an undefined result for the fptoui. 
8903   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8904       OpI->getOperand(0)->getType() == FI.getType() &&
8905       (int)FI.getType()->getScalarSizeInBits() <=
8906                     OpI->getType()->getFPMantissaWidth())
8907     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8908   
8909   return commonCastTransforms(FI);
8910 }
8911
8912 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8913   return commonCastTransforms(CI);
8914 }
8915
8916 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8917   return commonCastTransforms(CI);
8918 }
8919
8920 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8921   // If the destination integer type is smaller than the intptr_t type for
8922   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8923   // trunc to be exposed to other transforms.  Don't do this for extending
8924   // ptrtoint's, because we don't know if the target sign or zero extends its
8925   // pointers.
8926   if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8927     Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8928                                                     TD->getIntPtrType(),
8929                                                     "tmp"), CI);
8930     return new TruncInst(P, CI.getType());
8931   }
8932   
8933   return commonPointerCastTransforms(CI);
8934 }
8935
8936 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8937   // If the source integer type is larger than the intptr_t type for
8938   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8939   // allows the trunc to be exposed to other transforms.  Don't do this for
8940   // extending inttoptr's, because we don't know if the target sign or zero
8941   // extends to pointers.
8942   if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
8943       TD->getPointerSizeInBits()) {
8944     Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8945                                                  TD->getIntPtrType(),
8946                                                  "tmp"), CI);
8947     return new IntToPtrInst(P, CI.getType());
8948   }
8949   
8950   if (Instruction *I = commonCastTransforms(CI))
8951     return I;
8952   
8953   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8954   if (!DestPointee->isSized()) return 0;
8955
8956   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8957   ConstantInt *Cst;
8958   Value *X;
8959   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8960                                     m_ConstantInt(Cst)), *Context)) {
8961     // If the source and destination operands have the same type, see if this
8962     // is a single-index GEP.
8963     if (X->getType() == CI.getType()) {
8964       // Get the size of the pointee type.
8965       uint64_t Size = TD->getTypeAllocSize(DestPointee);
8966
8967       // Convert the constant to intptr type.
8968       APInt Offset = Cst->getValue();
8969       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8970
8971       // If Offset is evenly divisible by Size, we can do this xform.
8972       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8973         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8974         return GetElementPtrInst::Create(X, Context->getConstantInt(Offset));
8975       }
8976     }
8977     // TODO: Could handle other cases, e.g. where add is indexing into field of
8978     // struct etc.
8979   } else if (CI.getOperand(0)->hasOneUse() &&
8980              match(CI.getOperand(0), m_Add(m_Value(X),
8981                    m_ConstantInt(Cst)), *Context)) {
8982     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8983     // "inttoptr+GEP" instead of "add+intptr".
8984     
8985     // Get the size of the pointee type.
8986     uint64_t Size = TD->getTypeAllocSize(DestPointee);
8987     
8988     // Convert the constant to intptr type.
8989     APInt Offset = Cst->getValue();
8990     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8991     
8992     // If Offset is evenly divisible by Size, we can do this xform.
8993     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8994       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8995       
8996       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8997                                                             "tmp"), CI);
8998       return GetElementPtrInst::Create(P,
8999                                        Context->getConstantInt(Offset), "tmp");
9000     }
9001   }
9002   return 0;
9003 }
9004
9005 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
9006   // If the operands are integer typed then apply the integer transforms,
9007   // otherwise just apply the common ones.
9008   Value *Src = CI.getOperand(0);
9009   const Type *SrcTy = Src->getType();
9010   const Type *DestTy = CI.getType();
9011
9012   if (isa<PointerType>(SrcTy)) {
9013     if (Instruction *I = commonPointerCastTransforms(CI))
9014       return I;
9015   } else {
9016     if (Instruction *Result = commonCastTransforms(CI))
9017       return Result;
9018   }
9019
9020
9021   // Get rid of casts from one type to the same type. These are useless and can
9022   // be replaced by the operand.
9023   if (DestTy == Src->getType())
9024     return ReplaceInstUsesWith(CI, Src);
9025
9026   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
9027     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
9028     const Type *DstElTy = DstPTy->getElementType();
9029     const Type *SrcElTy = SrcPTy->getElementType();
9030     
9031     // If the address spaces don't match, don't eliminate the bitcast, which is
9032     // required for changing types.
9033     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9034       return 0;
9035     
9036     // If we are casting a malloc or alloca to a pointer to a type of the same
9037     // size, rewrite the allocation instruction to allocate the "right" type.
9038     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
9039       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9040         return V;
9041     
9042     // If the source and destination are pointers, and this cast is equivalent
9043     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
9044     // This can enhance SROA and other transforms that want type-safe pointers.
9045     Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
9046     unsigned NumZeros = 0;
9047     while (SrcElTy != DstElTy && 
9048            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9049            SrcElTy->getNumContainedTypes() /* not "{}" */) {
9050       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9051       ++NumZeros;
9052     }
9053
9054     // If we found a path from the src to dest, create the getelementptr now.
9055     if (SrcElTy == DstElTy) {
9056       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
9057       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
9058                                        ((Instruction*) NULL));
9059     }
9060   }
9061
9062   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9063     if (SVI->hasOneUse()) {
9064       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
9065       // a bitconvert to a vector with the same # elts.
9066       if (isa<VectorType>(DestTy) && 
9067           cast<VectorType>(DestTy)->getNumElements() ==
9068                 SVI->getType()->getNumElements() &&
9069           SVI->getType()->getNumElements() ==
9070             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9071         CastInst *Tmp;
9072         // If either of the operands is a cast from CI.getType(), then
9073         // evaluating the shuffle in the casted destination's type will allow
9074         // us to eliminate at least one cast.
9075         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
9076              Tmp->getOperand(0)->getType() == DestTy) ||
9077             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
9078              Tmp->getOperand(0)->getType() == DestTy)) {
9079           Value *LHS = InsertCastBefore(Instruction::BitCast,
9080                                         SVI->getOperand(0), DestTy, CI);
9081           Value *RHS = InsertCastBefore(Instruction::BitCast,
9082                                         SVI->getOperand(1), DestTy, CI);
9083           // Return a new shuffle vector.  Use the same element ID's, as we
9084           // know the vector types match #elts.
9085           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9086         }
9087       }
9088     }
9089   }
9090   return 0;
9091 }
9092
9093 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9094 ///   %C = or %A, %B
9095 ///   %D = select %cond, %C, %A
9096 /// into:
9097 ///   %C = select %cond, %B, 0
9098 ///   %D = or %A, %C
9099 ///
9100 /// Assuming that the specified instruction is an operand to the select, return
9101 /// a bitmask indicating which operands of this instruction are foldable if they
9102 /// equal the other incoming value of the select.
9103 ///
9104 static unsigned GetSelectFoldableOperands(Instruction *I) {
9105   switch (I->getOpcode()) {
9106   case Instruction::Add:
9107   case Instruction::Mul:
9108   case Instruction::And:
9109   case Instruction::Or:
9110   case Instruction::Xor:
9111     return 3;              // Can fold through either operand.
9112   case Instruction::Sub:   // Can only fold on the amount subtracted.
9113   case Instruction::Shl:   // Can only fold on the shift amount.
9114   case Instruction::LShr:
9115   case Instruction::AShr:
9116     return 1;
9117   default:
9118     return 0;              // Cannot fold
9119   }
9120 }
9121
9122 /// GetSelectFoldableConstant - For the same transformation as the previous
9123 /// function, return the identity constant that goes into the select.
9124 static Constant *GetSelectFoldableConstant(Instruction *I,
9125                                            LLVMContext *Context) {
9126   switch (I->getOpcode()) {
9127   default: LLVM_UNREACHABLE("This cannot happen!");
9128   case Instruction::Add:
9129   case Instruction::Sub:
9130   case Instruction::Or:
9131   case Instruction::Xor:
9132   case Instruction::Shl:
9133   case Instruction::LShr:
9134   case Instruction::AShr:
9135     return Context->getNullValue(I->getType());
9136   case Instruction::And:
9137     return Context->getAllOnesValue(I->getType());
9138   case Instruction::Mul:
9139     return Context->getConstantInt(I->getType(), 1);
9140   }
9141 }
9142
9143 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9144 /// have the same opcode and only one use each.  Try to simplify this.
9145 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9146                                           Instruction *FI) {
9147   if (TI->getNumOperands() == 1) {
9148     // If this is a non-volatile load or a cast from the same type,
9149     // merge.
9150     if (TI->isCast()) {
9151       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9152         return 0;
9153     } else {
9154       return 0;  // unknown unary op.
9155     }
9156
9157     // Fold this by inserting a select from the input values.
9158     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9159                                            FI->getOperand(0), SI.getName()+".v");
9160     InsertNewInstBefore(NewSI, SI);
9161     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9162                             TI->getType());
9163   }
9164
9165   // Only handle binary operators here.
9166   if (!isa<BinaryOperator>(TI))
9167     return 0;
9168
9169   // Figure out if the operations have any operands in common.
9170   Value *MatchOp, *OtherOpT, *OtherOpF;
9171   bool MatchIsOpZero;
9172   if (TI->getOperand(0) == FI->getOperand(0)) {
9173     MatchOp  = TI->getOperand(0);
9174     OtherOpT = TI->getOperand(1);
9175     OtherOpF = FI->getOperand(1);
9176     MatchIsOpZero = true;
9177   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9178     MatchOp  = TI->getOperand(1);
9179     OtherOpT = TI->getOperand(0);
9180     OtherOpF = FI->getOperand(0);
9181     MatchIsOpZero = false;
9182   } else if (!TI->isCommutative()) {
9183     return 0;
9184   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9185     MatchOp  = TI->getOperand(0);
9186     OtherOpT = TI->getOperand(1);
9187     OtherOpF = FI->getOperand(0);
9188     MatchIsOpZero = true;
9189   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9190     MatchOp  = TI->getOperand(1);
9191     OtherOpT = TI->getOperand(0);
9192     OtherOpF = FI->getOperand(1);
9193     MatchIsOpZero = true;
9194   } else {
9195     return 0;
9196   }
9197
9198   // If we reach here, they do have operations in common.
9199   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9200                                          OtherOpF, SI.getName()+".v");
9201   InsertNewInstBefore(NewSI, SI);
9202
9203   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9204     if (MatchIsOpZero)
9205       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9206     else
9207       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9208   }
9209   LLVM_UNREACHABLE("Shouldn't get here");
9210   return 0;
9211 }
9212
9213 static bool isSelect01(Constant *C1, Constant *C2) {
9214   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9215   if (!C1I)
9216     return false;
9217   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9218   if (!C2I)
9219     return false;
9220   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9221 }
9222
9223 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9224 /// facilitate further optimization.
9225 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9226                                             Value *FalseVal) {
9227   // See the comment above GetSelectFoldableOperands for a description of the
9228   // transformation we are doing here.
9229   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9230     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9231         !isa<Constant>(FalseVal)) {
9232       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9233         unsigned OpToFold = 0;
9234         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9235           OpToFold = 1;
9236         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9237           OpToFold = 2;
9238         }
9239
9240         if (OpToFold) {
9241           Constant *C = GetSelectFoldableConstant(TVI, Context);
9242           Value *OOp = TVI->getOperand(2-OpToFold);
9243           // Avoid creating select between 2 constants unless it's selecting
9244           // between 0 and 1.
9245           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9246             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9247             InsertNewInstBefore(NewSel, SI);
9248             NewSel->takeName(TVI);
9249             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9250               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9251             LLVM_UNREACHABLE("Unknown instruction!!");
9252           }
9253         }
9254       }
9255     }
9256   }
9257
9258   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9259     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9260         !isa<Constant>(TrueVal)) {
9261       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9262         unsigned OpToFold = 0;
9263         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9264           OpToFold = 1;
9265         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9266           OpToFold = 2;
9267         }
9268
9269         if (OpToFold) {
9270           Constant *C = GetSelectFoldableConstant(FVI, Context);
9271           Value *OOp = FVI->getOperand(2-OpToFold);
9272           // Avoid creating select between 2 constants unless it's selecting
9273           // between 0 and 1.
9274           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9275             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9276             InsertNewInstBefore(NewSel, SI);
9277             NewSel->takeName(FVI);
9278             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9279               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9280             LLVM_UNREACHABLE("Unknown instruction!!");
9281           }
9282         }
9283       }
9284     }
9285   }
9286
9287   return 0;
9288 }
9289
9290 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9291 /// ICmpInst as its first operand.
9292 ///
9293 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9294                                                    ICmpInst *ICI) {
9295   bool Changed = false;
9296   ICmpInst::Predicate Pred = ICI->getPredicate();
9297   Value *CmpLHS = ICI->getOperand(0);
9298   Value *CmpRHS = ICI->getOperand(1);
9299   Value *TrueVal = SI.getTrueValue();
9300   Value *FalseVal = SI.getFalseValue();
9301
9302   // Check cases where the comparison is with a constant that
9303   // can be adjusted to fit the min/max idiom. We may edit ICI in
9304   // place here, so make sure the select is the only user.
9305   if (ICI->hasOneUse())
9306     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9307       switch (Pred) {
9308       default: break;
9309       case ICmpInst::ICMP_ULT:
9310       case ICmpInst::ICMP_SLT: {
9311         // X < MIN ? T : F  -->  F
9312         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9313           return ReplaceInstUsesWith(SI, FalseVal);
9314         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9315         Constant *AdjustedRHS = SubOne(CI, Context);
9316         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9317             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9318           Pred = ICmpInst::getSwappedPredicate(Pred);
9319           CmpRHS = AdjustedRHS;
9320           std::swap(FalseVal, TrueVal);
9321           ICI->setPredicate(Pred);
9322           ICI->setOperand(1, CmpRHS);
9323           SI.setOperand(1, TrueVal);
9324           SI.setOperand(2, FalseVal);
9325           Changed = true;
9326         }
9327         break;
9328       }
9329       case ICmpInst::ICMP_UGT:
9330       case ICmpInst::ICMP_SGT: {
9331         // X > MAX ? T : F  -->  F
9332         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9333           return ReplaceInstUsesWith(SI, FalseVal);
9334         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9335         Constant *AdjustedRHS = AddOne(CI, Context);
9336         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9337             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9338           Pred = ICmpInst::getSwappedPredicate(Pred);
9339           CmpRHS = AdjustedRHS;
9340           std::swap(FalseVal, TrueVal);
9341           ICI->setPredicate(Pred);
9342           ICI->setOperand(1, CmpRHS);
9343           SI.setOperand(1, TrueVal);
9344           SI.setOperand(2, FalseVal);
9345           Changed = true;
9346         }
9347         break;
9348       }
9349       }
9350
9351       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9352       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9353       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9354       if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9355           match(FalseVal, m_ConstantInt<0>(), *Context))
9356         Pred = ICI->getPredicate();
9357       else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9358                match(FalseVal, m_ConstantInt<-1>(), *Context))
9359         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9360       
9361       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9362         // If we are just checking for a icmp eq of a single bit and zext'ing it
9363         // to an integer, then shift the bit to the appropriate place and then
9364         // cast to integer to avoid the comparison.
9365         const APInt &Op1CV = CI->getValue();
9366     
9367         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9368         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9369         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9370             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9371           Value *In = ICI->getOperand(0);
9372           Value *Sh = Context->getConstantInt(In->getType(),
9373                                        In->getType()->getScalarSizeInBits()-1);
9374           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9375                                                           In->getName()+".lobit"),
9376                                    *ICI);
9377           if (In->getType() != SI.getType())
9378             In = CastInst::CreateIntegerCast(In, SI.getType(),
9379                                              true/*SExt*/, "tmp", ICI);
9380     
9381           if (Pred == ICmpInst::ICMP_SGT)
9382             In = InsertNewInstBefore(BinaryOperator::CreateNot(*Context, In,
9383                                        In->getName()+".not"), *ICI);
9384     
9385           return ReplaceInstUsesWith(SI, In);
9386         }
9387       }
9388     }
9389
9390   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9391     // Transform (X == Y) ? X : Y  -> Y
9392     if (Pred == ICmpInst::ICMP_EQ)
9393       return ReplaceInstUsesWith(SI, FalseVal);
9394     // Transform (X != Y) ? X : Y  -> X
9395     if (Pred == ICmpInst::ICMP_NE)
9396       return ReplaceInstUsesWith(SI, TrueVal);
9397     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9398
9399   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9400     // Transform (X == Y) ? Y : X  -> X
9401     if (Pred == ICmpInst::ICMP_EQ)
9402       return ReplaceInstUsesWith(SI, FalseVal);
9403     // Transform (X != Y) ? Y : X  -> Y
9404     if (Pred == ICmpInst::ICMP_NE)
9405       return ReplaceInstUsesWith(SI, TrueVal);
9406     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9407   }
9408
9409   /// NOTE: if we wanted to, this is where to detect integer ABS
9410
9411   return Changed ? &SI : 0;
9412 }
9413
9414 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9415   Value *CondVal = SI.getCondition();
9416   Value *TrueVal = SI.getTrueValue();
9417   Value *FalseVal = SI.getFalseValue();
9418
9419   // select true, X, Y  -> X
9420   // select false, X, Y -> Y
9421   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9422     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9423
9424   // select C, X, X -> X
9425   if (TrueVal == FalseVal)
9426     return ReplaceInstUsesWith(SI, TrueVal);
9427
9428   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9429     return ReplaceInstUsesWith(SI, FalseVal);
9430   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9431     return ReplaceInstUsesWith(SI, TrueVal);
9432   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9433     if (isa<Constant>(TrueVal))
9434       return ReplaceInstUsesWith(SI, TrueVal);
9435     else
9436       return ReplaceInstUsesWith(SI, FalseVal);
9437   }
9438
9439   if (SI.getType() == Type::Int1Ty) {
9440     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9441       if (C->getZExtValue()) {
9442         // Change: A = select B, true, C --> A = or B, C
9443         return BinaryOperator::CreateOr(CondVal, FalseVal);
9444       } else {
9445         // Change: A = select B, false, C --> A = and !B, C
9446         Value *NotCond =
9447           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9448                                              "not."+CondVal->getName()), SI);
9449         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9450       }
9451     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9452       if (C->getZExtValue() == false) {
9453         // Change: A = select B, C, false --> A = and B, C
9454         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9455       } else {
9456         // Change: A = select B, C, true --> A = or !B, C
9457         Value *NotCond =
9458           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9459                                              "not."+CondVal->getName()), SI);
9460         return BinaryOperator::CreateOr(NotCond, TrueVal);
9461       }
9462     }
9463     
9464     // select a, b, a  -> a&b
9465     // select a, a, b  -> a|b
9466     if (CondVal == TrueVal)
9467       return BinaryOperator::CreateOr(CondVal, FalseVal);
9468     else if (CondVal == FalseVal)
9469       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9470   }
9471
9472   // Selecting between two integer constants?
9473   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9474     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9475       // select C, 1, 0 -> zext C to int
9476       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9477         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9478       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9479         // select C, 0, 1 -> zext !C to int
9480         Value *NotCond =
9481           InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
9482                                                "not."+CondVal->getName()), SI);
9483         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9484       }
9485
9486       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9487         // If one of the constants is zero (we know they can't both be) and we
9488         // have an icmp instruction with zero, and we have an 'and' with the
9489         // non-constant value, eliminate this whole mess.  This corresponds to
9490         // cases like this: ((X & 27) ? 27 : 0)
9491         if (TrueValC->isZero() || FalseValC->isZero())
9492           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9493               cast<Constant>(IC->getOperand(1))->isNullValue())
9494             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9495               if (ICA->getOpcode() == Instruction::And &&
9496                   isa<ConstantInt>(ICA->getOperand(1)) &&
9497                   (ICA->getOperand(1) == TrueValC ||
9498                    ICA->getOperand(1) == FalseValC) &&
9499                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9500                 // Okay, now we know that everything is set up, we just don't
9501                 // know whether we have a icmp_ne or icmp_eq and whether the 
9502                 // true or false val is the zero.
9503                 bool ShouldNotVal = !TrueValC->isZero();
9504                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9505                 Value *V = ICA;
9506                 if (ShouldNotVal)
9507                   V = InsertNewInstBefore(BinaryOperator::Create(
9508                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9509                 return ReplaceInstUsesWith(SI, V);
9510               }
9511       }
9512     }
9513
9514   // See if we are selecting two values based on a comparison of the two values.
9515   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9516     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9517       // Transform (X == Y) ? X : Y  -> Y
9518       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9519         // This is not safe in general for floating point:  
9520         // consider X== -0, Y== +0.
9521         // It becomes safe if either operand is a nonzero constant.
9522         ConstantFP *CFPt, *CFPf;
9523         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9524               !CFPt->getValueAPF().isZero()) ||
9525             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9526              !CFPf->getValueAPF().isZero()))
9527         return ReplaceInstUsesWith(SI, FalseVal);
9528       }
9529       // Transform (X != Y) ? X : Y  -> X
9530       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9531         return ReplaceInstUsesWith(SI, TrueVal);
9532       // NOTE: if we wanted to, this is where to detect MIN/MAX
9533
9534     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9535       // Transform (X == Y) ? Y : X  -> X
9536       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9537         // This is not safe in general for floating point:  
9538         // consider X== -0, Y== +0.
9539         // It becomes safe if either operand is a nonzero constant.
9540         ConstantFP *CFPt, *CFPf;
9541         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9542               !CFPt->getValueAPF().isZero()) ||
9543             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9544              !CFPf->getValueAPF().isZero()))
9545           return ReplaceInstUsesWith(SI, FalseVal);
9546       }
9547       // Transform (X != Y) ? Y : X  -> Y
9548       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9549         return ReplaceInstUsesWith(SI, TrueVal);
9550       // NOTE: if we wanted to, this is where to detect MIN/MAX
9551     }
9552     // NOTE: if we wanted to, this is where to detect ABS
9553   }
9554
9555   // See if we are selecting two values based on a comparison of the two values.
9556   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9557     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9558       return Result;
9559
9560   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9561     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9562       if (TI->hasOneUse() && FI->hasOneUse()) {
9563         Instruction *AddOp = 0, *SubOp = 0;
9564
9565         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9566         if (TI->getOpcode() == FI->getOpcode())
9567           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9568             return IV;
9569
9570         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9571         // even legal for FP.
9572         if ((TI->getOpcode() == Instruction::Sub &&
9573              FI->getOpcode() == Instruction::Add) ||
9574             (TI->getOpcode() == Instruction::FSub &&
9575              FI->getOpcode() == Instruction::FAdd)) {
9576           AddOp = FI; SubOp = TI;
9577         } else if ((FI->getOpcode() == Instruction::Sub &&
9578                     TI->getOpcode() == Instruction::Add) ||
9579                    (FI->getOpcode() == Instruction::FSub &&
9580                     TI->getOpcode() == Instruction::FAdd)) {
9581           AddOp = TI; SubOp = FI;
9582         }
9583
9584         if (AddOp) {
9585           Value *OtherAddOp = 0;
9586           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9587             OtherAddOp = AddOp->getOperand(1);
9588           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9589             OtherAddOp = AddOp->getOperand(0);
9590           }
9591
9592           if (OtherAddOp) {
9593             // So at this point we know we have (Y -> OtherAddOp):
9594             //        select C, (add X, Y), (sub X, Z)
9595             Value *NegVal;  // Compute -Z
9596             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9597               NegVal = Context->getConstantExprNeg(C);
9598             } else {
9599               NegVal = InsertNewInstBefore(
9600                     BinaryOperator::CreateNeg(*Context, SubOp->getOperand(1),
9601                                               "tmp"), SI);
9602             }
9603
9604             Value *NewTrueOp = OtherAddOp;
9605             Value *NewFalseOp = NegVal;
9606             if (AddOp != TI)
9607               std::swap(NewTrueOp, NewFalseOp);
9608             Instruction *NewSel =
9609               SelectInst::Create(CondVal, NewTrueOp,
9610                                  NewFalseOp, SI.getName() + ".p");
9611
9612             NewSel = InsertNewInstBefore(NewSel, SI);
9613             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9614           }
9615         }
9616       }
9617
9618   // See if we can fold the select into one of our operands.
9619   if (SI.getType()->isInteger()) {
9620     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9621     if (FoldI)
9622       return FoldI;
9623   }
9624
9625   if (BinaryOperator::isNot(CondVal)) {
9626     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9627     SI.setOperand(1, FalseVal);
9628     SI.setOperand(2, TrueVal);
9629     return &SI;
9630   }
9631
9632   return 0;
9633 }
9634
9635 /// EnforceKnownAlignment - If the specified pointer points to an object that
9636 /// we control, modify the object's alignment to PrefAlign. This isn't
9637 /// often possible though. If alignment is important, a more reliable approach
9638 /// is to simply align all global variables and allocation instructions to
9639 /// their preferred alignment from the beginning.
9640 ///
9641 static unsigned EnforceKnownAlignment(Value *V,
9642                                       unsigned Align, unsigned PrefAlign) {
9643
9644   User *U = dyn_cast<User>(V);
9645   if (!U) return Align;
9646
9647   switch (getOpcode(U)) {
9648   default: break;
9649   case Instruction::BitCast:
9650     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9651   case Instruction::GetElementPtr: {
9652     // If all indexes are zero, it is just the alignment of the base pointer.
9653     bool AllZeroOperands = true;
9654     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9655       if (!isa<Constant>(*i) ||
9656           !cast<Constant>(*i)->isNullValue()) {
9657         AllZeroOperands = false;
9658         break;
9659       }
9660
9661     if (AllZeroOperands) {
9662       // Treat this like a bitcast.
9663       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9664     }
9665     break;
9666   }
9667   }
9668
9669   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9670     // If there is a large requested alignment and we can, bump up the alignment
9671     // of the global.
9672     if (!GV->isDeclaration()) {
9673       if (GV->getAlignment() >= PrefAlign)
9674         Align = GV->getAlignment();
9675       else {
9676         GV->setAlignment(PrefAlign);
9677         Align = PrefAlign;
9678       }
9679     }
9680   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9681     // If there is a requested alignment and if this is an alloca, round up.  We
9682     // don't do this for malloc, because some systems can't respect the request.
9683     if (isa<AllocaInst>(AI)) {
9684       if (AI->getAlignment() >= PrefAlign)
9685         Align = AI->getAlignment();
9686       else {
9687         AI->setAlignment(PrefAlign);
9688         Align = PrefAlign;
9689       }
9690     }
9691   }
9692
9693   return Align;
9694 }
9695
9696 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9697 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9698 /// and it is more than the alignment of the ultimate object, see if we can
9699 /// increase the alignment of the ultimate object, making this check succeed.
9700 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9701                                                   unsigned PrefAlign) {
9702   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9703                       sizeof(PrefAlign) * CHAR_BIT;
9704   APInt Mask = APInt::getAllOnesValue(BitWidth);
9705   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9706   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9707   unsigned TrailZ = KnownZero.countTrailingOnes();
9708   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9709
9710   if (PrefAlign > Align)
9711     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9712   
9713     // We don't need to make any adjustment.
9714   return Align;
9715 }
9716
9717 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9718   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9719   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9720   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9721   unsigned CopyAlign = MI->getAlignment();
9722
9723   if (CopyAlign < MinAlign) {
9724     MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(), 
9725                                              MinAlign, false));
9726     return MI;
9727   }
9728   
9729   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9730   // load/store.
9731   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9732   if (MemOpLength == 0) return 0;
9733   
9734   // Source and destination pointer types are always "i8*" for intrinsic.  See
9735   // if the size is something we can handle with a single primitive load/store.
9736   // A single load+store correctly handles overlapping memory in the memmove
9737   // case.
9738   unsigned Size = MemOpLength->getZExtValue();
9739   if (Size == 0) return MI;  // Delete this mem transfer.
9740   
9741   if (Size > 8 || (Size&(Size-1)))
9742     return 0;  // If not 1/2/4/8 bytes, exit.
9743   
9744   // Use an integer load+store unless we can find something better.
9745   Type *NewPtrTy =
9746                 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
9747   
9748   // Memcpy forces the use of i8* for the source and destination.  That means
9749   // that if you're using memcpy to move one double around, you'll get a cast
9750   // from double* to i8*.  We'd much rather use a double load+store rather than
9751   // an i64 load+store, here because this improves the odds that the source or
9752   // dest address will be promotable.  See if we can find a better type than the
9753   // integer datatype.
9754   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9755     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9756     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9757       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9758       // down through these levels if so.
9759       while (!SrcETy->isSingleValueType()) {
9760         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9761           if (STy->getNumElements() == 1)
9762             SrcETy = STy->getElementType(0);
9763           else
9764             break;
9765         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9766           if (ATy->getNumElements() == 1)
9767             SrcETy = ATy->getElementType();
9768           else
9769             break;
9770         } else
9771           break;
9772       }
9773       
9774       if (SrcETy->isSingleValueType())
9775         NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
9776     }
9777   }
9778   
9779   
9780   // If the memcpy/memmove provides better alignment info than we can
9781   // infer, use it.
9782   SrcAlign = std::max(SrcAlign, CopyAlign);
9783   DstAlign = std::max(DstAlign, CopyAlign);
9784   
9785   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9786   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9787   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9788   InsertNewInstBefore(L, *MI);
9789   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9790
9791   // Set the size of the copy to 0, it will be deleted on the next iteration.
9792   MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
9793   return MI;
9794 }
9795
9796 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9797   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9798   if (MI->getAlignment() < Alignment) {
9799     MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9800                                              Alignment, false));
9801     return MI;
9802   }
9803   
9804   // Extract the length and alignment and fill if they are constant.
9805   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9806   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9807   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9808     return 0;
9809   uint64_t Len = LenC->getZExtValue();
9810   Alignment = MI->getAlignment();
9811   
9812   // If the length is zero, this is a no-op
9813   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9814   
9815   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9816   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9817     const Type *ITy = Context->getIntegerType(Len*8);  // n=1 -> i8.
9818     
9819     Value *Dest = MI->getDest();
9820     Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
9821
9822     // Alignment 0 is identity for alignment 1 for memset, but not store.
9823     if (Alignment == 0) Alignment = 1;
9824     
9825     // Extract the fill value and store.
9826     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9827     InsertNewInstBefore(new StoreInst(Context->getConstantInt(ITy, Fill),
9828                                       Dest, false, Alignment), *MI);
9829     
9830     // Set the size of the copy to 0, it will be deleted on the next iteration.
9831     MI->setLength(Context->getNullValue(LenC->getType()));
9832     return MI;
9833   }
9834
9835   return 0;
9836 }
9837
9838
9839 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9840 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9841 /// the heavy lifting.
9842 ///
9843 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9844   // If the caller function is nounwind, mark the call as nounwind, even if the
9845   // callee isn't.
9846   if (CI.getParent()->getParent()->doesNotThrow() &&
9847       !CI.doesNotThrow()) {
9848     CI.setDoesNotThrow();
9849     return &CI;
9850   }
9851   
9852   
9853   
9854   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9855   if (!II) return visitCallSite(&CI);
9856   
9857   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9858   // visitCallSite.
9859   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9860     bool Changed = false;
9861
9862     // memmove/cpy/set of zero bytes is a noop.
9863     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9864       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9865
9866       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9867         if (CI->getZExtValue() == 1) {
9868           // Replace the instruction with just byte operations.  We would
9869           // transform other cases to loads/stores, but we don't know if
9870           // alignment is sufficient.
9871         }
9872     }
9873
9874     // If we have a memmove and the source operation is a constant global,
9875     // then the source and dest pointers can't alias, so we can change this
9876     // into a call to memcpy.
9877     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9878       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9879         if (GVSrc->isConstant()) {
9880           Module *M = CI.getParent()->getParent()->getParent();
9881           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9882           const Type *Tys[1];
9883           Tys[0] = CI.getOperand(3)->getType();
9884           CI.setOperand(0, 
9885                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9886           Changed = true;
9887         }
9888
9889       // memmove(x,x,size) -> noop.
9890       if (MMI->getSource() == MMI->getDest())
9891         return EraseInstFromFunction(CI);
9892     }
9893
9894     // If we can determine a pointer alignment that is bigger than currently
9895     // set, update the alignment.
9896     if (isa<MemTransferInst>(MI)) {
9897       if (Instruction *I = SimplifyMemTransfer(MI))
9898         return I;
9899     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9900       if (Instruction *I = SimplifyMemSet(MSI))
9901         return I;
9902     }
9903           
9904     if (Changed) return II;
9905   }
9906   
9907   switch (II->getIntrinsicID()) {
9908   default: break;
9909   case Intrinsic::bswap:
9910     // bswap(bswap(x)) -> x
9911     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9912       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9913         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9914     break;
9915   case Intrinsic::ppc_altivec_lvx:
9916   case Intrinsic::ppc_altivec_lvxl:
9917   case Intrinsic::x86_sse_loadu_ps:
9918   case Intrinsic::x86_sse2_loadu_pd:
9919   case Intrinsic::x86_sse2_loadu_dq:
9920     // Turn PPC lvx     -> load if the pointer is known aligned.
9921     // Turn X86 loadups -> load if the pointer is known aligned.
9922     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9923       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9924                                    Context->getPointerTypeUnqual(II->getType()),
9925                                        CI);
9926       return new LoadInst(Ptr);
9927     }
9928     break;
9929   case Intrinsic::ppc_altivec_stvx:
9930   case Intrinsic::ppc_altivec_stvxl:
9931     // Turn stvx -> store if the pointer is known aligned.
9932     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9933       const Type *OpPtrTy = 
9934         Context->getPointerTypeUnqual(II->getOperand(1)->getType());
9935       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9936       return new StoreInst(II->getOperand(1), Ptr);
9937     }
9938     break;
9939   case Intrinsic::x86_sse_storeu_ps:
9940   case Intrinsic::x86_sse2_storeu_pd:
9941   case Intrinsic::x86_sse2_storeu_dq:
9942     // Turn X86 storeu -> store if the pointer is known aligned.
9943     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9944       const Type *OpPtrTy = 
9945         Context->getPointerTypeUnqual(II->getOperand(2)->getType());
9946       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9947       return new StoreInst(II->getOperand(2), Ptr);
9948     }
9949     break;
9950     
9951   case Intrinsic::x86_sse_cvttss2si: {
9952     // These intrinsics only demands the 0th element of its input vector.  If
9953     // we can simplify the input based on that, do so now.
9954     unsigned VWidth =
9955       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9956     APInt DemandedElts(VWidth, 1);
9957     APInt UndefElts(VWidth, 0);
9958     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9959                                               UndefElts)) {
9960       II->setOperand(1, V);
9961       return II;
9962     }
9963     break;
9964   }
9965     
9966   case Intrinsic::ppc_altivec_vperm:
9967     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9968     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9969       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9970       
9971       // Check that all of the elements are integer constants or undefs.
9972       bool AllEltsOk = true;
9973       for (unsigned i = 0; i != 16; ++i) {
9974         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9975             !isa<UndefValue>(Mask->getOperand(i))) {
9976           AllEltsOk = false;
9977           break;
9978         }
9979       }
9980       
9981       if (AllEltsOk) {
9982         // Cast the input vectors to byte vectors.
9983         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9984         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9985         Value *Result = Context->getUndef(Op0->getType());
9986         
9987         // Only extract each element once.
9988         Value *ExtractedElts[32];
9989         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9990         
9991         for (unsigned i = 0; i != 16; ++i) {
9992           if (isa<UndefValue>(Mask->getOperand(i)))
9993             continue;
9994           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9995           Idx &= 31;  // Match the hardware behavior.
9996           
9997           if (ExtractedElts[Idx] == 0) {
9998             Instruction *Elt = 
9999               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
10000             InsertNewInstBefore(Elt, CI);
10001             ExtractedElts[Idx] = Elt;
10002           }
10003         
10004           // Insert this value into the result vector.
10005           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
10006                                              i, "tmp");
10007           InsertNewInstBefore(cast<Instruction>(Result), CI);
10008         }
10009         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
10010       }
10011     }
10012     break;
10013
10014   case Intrinsic::stackrestore: {
10015     // If the save is right next to the restore, remove the restore.  This can
10016     // happen when variable allocas are DCE'd.
10017     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10018       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10019         BasicBlock::iterator BI = SS;
10020         if (&*++BI == II)
10021           return EraseInstFromFunction(CI);
10022       }
10023     }
10024     
10025     // Scan down this block to see if there is another stack restore in the
10026     // same block without an intervening call/alloca.
10027     BasicBlock::iterator BI = II;
10028     TerminatorInst *TI = II->getParent()->getTerminator();
10029     bool CannotRemove = false;
10030     for (++BI; &*BI != TI; ++BI) {
10031       if (isa<AllocaInst>(BI)) {
10032         CannotRemove = true;
10033         break;
10034       }
10035       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10036         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10037           // If there is a stackrestore below this one, remove this one.
10038           if (II->getIntrinsicID() == Intrinsic::stackrestore)
10039             return EraseInstFromFunction(CI);
10040           // Otherwise, ignore the intrinsic.
10041         } else {
10042           // If we found a non-intrinsic call, we can't remove the stack
10043           // restore.
10044           CannotRemove = true;
10045           break;
10046         }
10047       }
10048     }
10049     
10050     // If the stack restore is in a return/unwind block and if there are no
10051     // allocas or calls between the restore and the return, nuke the restore.
10052     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10053       return EraseInstFromFunction(CI);
10054     break;
10055   }
10056   }
10057
10058   return visitCallSite(II);
10059 }
10060
10061 // InvokeInst simplification
10062 //
10063 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10064   return visitCallSite(&II);
10065 }
10066
10067 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
10068 /// passed through the varargs area, we can eliminate the use of the cast.
10069 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10070                                          const CastInst * const CI,
10071                                          const TargetData * const TD,
10072                                          const int ix) {
10073   if (!CI->isLosslessCast())
10074     return false;
10075
10076   // The size of ByVal arguments is derived from the type, so we
10077   // can't change to a type with a different size.  If the size were
10078   // passed explicitly we could avoid this check.
10079   if (!CS.paramHasAttr(ix, Attribute::ByVal))
10080     return true;
10081
10082   const Type* SrcTy = 
10083             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10084   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10085   if (!SrcTy->isSized() || !DstTy->isSized())
10086     return false;
10087   if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10088     return false;
10089   return true;
10090 }
10091
10092 // visitCallSite - Improvements for call and invoke instructions.
10093 //
10094 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10095   bool Changed = false;
10096
10097   // If the callee is a constexpr cast of a function, attempt to move the cast
10098   // to the arguments of the call/invoke.
10099   if (transformConstExprCastCall(CS)) return 0;
10100
10101   Value *Callee = CS.getCalledValue();
10102
10103   if (Function *CalleeF = dyn_cast<Function>(Callee))
10104     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10105       Instruction *OldCall = CS.getInstruction();
10106       // If the call and callee calling conventions don't match, this call must
10107       // be unreachable, as the call is undefined.
10108       new StoreInst(Context->getConstantIntTrue(),
10109                 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), 
10110                                   OldCall);
10111       if (!OldCall->use_empty())
10112         OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
10113       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10114         return EraseInstFromFunction(*OldCall);
10115       return 0;
10116     }
10117
10118   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10119     // This instruction is not reachable, just remove it.  We insert a store to
10120     // undef so that we know that this code is not reachable, despite the fact
10121     // that we can't modify the CFG here.
10122     new StoreInst(Context->getConstantIntTrue(),
10123                Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10124                   CS.getInstruction());
10125
10126     if (!CS.getInstruction()->use_empty())
10127       CS.getInstruction()->
10128         replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
10129
10130     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10131       // Don't break the CFG, insert a dummy cond branch.
10132       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10133                          Context->getConstantIntTrue(), II);
10134     }
10135     return EraseInstFromFunction(*CS.getInstruction());
10136   }
10137
10138   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10139     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10140       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10141         return transformCallThroughTrampoline(CS);
10142
10143   const PointerType *PTy = cast<PointerType>(Callee->getType());
10144   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10145   if (FTy->isVarArg()) {
10146     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10147     // See if we can optimize any arguments passed through the varargs area of
10148     // the call.
10149     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10150            E = CS.arg_end(); I != E; ++I, ++ix) {
10151       CastInst *CI = dyn_cast<CastInst>(*I);
10152       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10153         *I = CI->getOperand(0);
10154         Changed = true;
10155       }
10156     }
10157   }
10158
10159   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10160     // Inline asm calls cannot throw - mark them 'nounwind'.
10161     CS.setDoesNotThrow();
10162     Changed = true;
10163   }
10164
10165   return Changed ? CS.getInstruction() : 0;
10166 }
10167
10168 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10169 // attempt to move the cast to the arguments of the call/invoke.
10170 //
10171 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10172   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10173   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10174   if (CE->getOpcode() != Instruction::BitCast || 
10175       !isa<Function>(CE->getOperand(0)))
10176     return false;
10177   Function *Callee = cast<Function>(CE->getOperand(0));
10178   Instruction *Caller = CS.getInstruction();
10179   const AttrListPtr &CallerPAL = CS.getAttributes();
10180
10181   // Okay, this is a cast from a function to a different type.  Unless doing so
10182   // would cause a type conversion of one of our arguments, change this call to
10183   // be a direct call with arguments casted to the appropriate types.
10184   //
10185   const FunctionType *FT = Callee->getFunctionType();
10186   const Type *OldRetTy = Caller->getType();
10187   const Type *NewRetTy = FT->getReturnType();
10188
10189   if (isa<StructType>(NewRetTy))
10190     return false; // TODO: Handle multiple return values.
10191
10192   // Check to see if we are changing the return type...
10193   if (OldRetTy != NewRetTy) {
10194     if (Callee->isDeclaration() &&
10195         // Conversion is ok if changing from one pointer type to another or from
10196         // a pointer to an integer of the same size.
10197         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
10198           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
10199       return false;   // Cannot transform this return value.
10200
10201     if (!Caller->use_empty() &&
10202         // void -> non-void is handled specially
10203         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
10204       return false;   // Cannot transform this return value.
10205
10206     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10207       Attributes RAttrs = CallerPAL.getRetAttributes();
10208       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10209         return false;   // Attribute not compatible with transformed value.
10210     }
10211
10212     // If the callsite is an invoke instruction, and the return value is used by
10213     // a PHI node in a successor, we cannot change the return type of the call
10214     // because there is no place to put the cast instruction (without breaking
10215     // the critical edge).  Bail out in this case.
10216     if (!Caller->use_empty())
10217       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10218         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10219              UI != E; ++UI)
10220           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10221             if (PN->getParent() == II->getNormalDest() ||
10222                 PN->getParent() == II->getUnwindDest())
10223               return false;
10224   }
10225
10226   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10227   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10228
10229   CallSite::arg_iterator AI = CS.arg_begin();
10230   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10231     const Type *ParamTy = FT->getParamType(i);
10232     const Type *ActTy = (*AI)->getType();
10233
10234     if (!CastInst::isCastable(ActTy, ParamTy))
10235       return false;   // Cannot transform this parameter value.
10236
10237     if (CallerPAL.getParamAttributes(i + 1) 
10238         & Attribute::typeIncompatible(ParamTy))
10239       return false;   // Attribute not compatible with transformed value.
10240
10241     // Converting from one pointer type to another or between a pointer and an
10242     // integer of the same size is safe even if we do not have a body.
10243     bool isConvertible = ActTy == ParamTy ||
10244       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10245        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
10246     if (Callee->isDeclaration() && !isConvertible) return false;
10247   }
10248
10249   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10250       Callee->isDeclaration())
10251     return false;   // Do not delete arguments unless we have a function body.
10252
10253   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10254       !CallerPAL.isEmpty())
10255     // In this case we have more arguments than the new function type, but we
10256     // won't be dropping them.  Check that these extra arguments have attributes
10257     // that are compatible with being a vararg call argument.
10258     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10259       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10260         break;
10261       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10262       if (PAttrs & Attribute::VarArgsIncompatible)
10263         return false;
10264     }
10265
10266   // Okay, we decided that this is a safe thing to do: go ahead and start
10267   // inserting cast instructions as necessary...
10268   std::vector<Value*> Args;
10269   Args.reserve(NumActualArgs);
10270   SmallVector<AttributeWithIndex, 8> attrVec;
10271   attrVec.reserve(NumCommonArgs);
10272
10273   // Get any return attributes.
10274   Attributes RAttrs = CallerPAL.getRetAttributes();
10275
10276   // If the return value is not being used, the type may not be compatible
10277   // with the existing attributes.  Wipe out any problematic attributes.
10278   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10279
10280   // Add the new return attributes.
10281   if (RAttrs)
10282     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10283
10284   AI = CS.arg_begin();
10285   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10286     const Type *ParamTy = FT->getParamType(i);
10287     if ((*AI)->getType() == ParamTy) {
10288       Args.push_back(*AI);
10289     } else {
10290       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10291           false, ParamTy, false);
10292       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10293       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10294     }
10295
10296     // Add any parameter attributes.
10297     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10298       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10299   }
10300
10301   // If the function takes more arguments than the call was taking, add them
10302   // now...
10303   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10304     Args.push_back(Context->getNullValue(FT->getParamType(i)));
10305
10306   // If we are removing arguments to the function, emit an obnoxious warning...
10307   if (FT->getNumParams() < NumActualArgs) {
10308     if (!FT->isVarArg()) {
10309       cerr << "WARNING: While resolving call to function '"
10310            << Callee->getName() << "' arguments were dropped!\n";
10311     } else {
10312       // Add all of the arguments in their promoted form to the arg list...
10313       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10314         const Type *PTy = getPromotedType((*AI)->getType());
10315         if (PTy != (*AI)->getType()) {
10316           // Must promote to pass through va_arg area!
10317           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
10318                                                                 PTy, false);
10319           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10320           InsertNewInstBefore(Cast, *Caller);
10321           Args.push_back(Cast);
10322         } else {
10323           Args.push_back(*AI);
10324         }
10325
10326         // Add any parameter attributes.
10327         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10328           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10329       }
10330     }
10331   }
10332
10333   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10334     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10335
10336   if (NewRetTy == Type::VoidTy)
10337     Caller->setName("");   // Void type should not have a name.
10338
10339   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
10340
10341   Instruction *NC;
10342   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10343     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10344                             Args.begin(), Args.end(),
10345                             Caller->getName(), Caller);
10346     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10347     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10348   } else {
10349     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10350                           Caller->getName(), Caller);
10351     CallInst *CI = cast<CallInst>(Caller);
10352     if (CI->isTailCall())
10353       cast<CallInst>(NC)->setTailCall();
10354     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10355     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10356   }
10357
10358   // Insert a cast of the return type as necessary.
10359   Value *NV = NC;
10360   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10361     if (NV->getType() != Type::VoidTy) {
10362       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10363                                                             OldRetTy, false);
10364       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10365
10366       // If this is an invoke instruction, we should insert it after the first
10367       // non-phi, instruction in the normal successor block.
10368       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10369         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10370         InsertNewInstBefore(NC, *I);
10371       } else {
10372         // Otherwise, it's a call, just insert cast right after the call instr
10373         InsertNewInstBefore(NC, *Caller);
10374       }
10375       AddUsersToWorkList(*Caller);
10376     } else {
10377       NV = Context->getUndef(Caller->getType());
10378     }
10379   }
10380
10381   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10382     Caller->replaceAllUsesWith(NV);
10383   Caller->eraseFromParent();
10384   RemoveFromWorkList(Caller);
10385   return true;
10386 }
10387
10388 // transformCallThroughTrampoline - Turn a call to a function created by the
10389 // init_trampoline intrinsic into a direct call to the underlying function.
10390 //
10391 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10392   Value *Callee = CS.getCalledValue();
10393   const PointerType *PTy = cast<PointerType>(Callee->getType());
10394   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10395   const AttrListPtr &Attrs = CS.getAttributes();
10396
10397   // If the call already has the 'nest' attribute somewhere then give up -
10398   // otherwise 'nest' would occur twice after splicing in the chain.
10399   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10400     return 0;
10401
10402   IntrinsicInst *Tramp =
10403     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10404
10405   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10406   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10407   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10408
10409   const AttrListPtr &NestAttrs = NestF->getAttributes();
10410   if (!NestAttrs.isEmpty()) {
10411     unsigned NestIdx = 1;
10412     const Type *NestTy = 0;
10413     Attributes NestAttr = Attribute::None;
10414
10415     // Look for a parameter marked with the 'nest' attribute.
10416     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10417          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10418       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10419         // Record the parameter type and any other attributes.
10420         NestTy = *I;
10421         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10422         break;
10423       }
10424
10425     if (NestTy) {
10426       Instruction *Caller = CS.getInstruction();
10427       std::vector<Value*> NewArgs;
10428       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10429
10430       SmallVector<AttributeWithIndex, 8> NewAttrs;
10431       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10432
10433       // Insert the nest argument into the call argument list, which may
10434       // mean appending it.  Likewise for attributes.
10435
10436       // Add any result attributes.
10437       if (Attributes Attr = Attrs.getRetAttributes())
10438         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10439
10440       {
10441         unsigned Idx = 1;
10442         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10443         do {
10444           if (Idx == NestIdx) {
10445             // Add the chain argument and attributes.
10446             Value *NestVal = Tramp->getOperand(3);
10447             if (NestVal->getType() != NestTy)
10448               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10449             NewArgs.push_back(NestVal);
10450             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10451           }
10452
10453           if (I == E)
10454             break;
10455
10456           // Add the original argument and attributes.
10457           NewArgs.push_back(*I);
10458           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10459             NewAttrs.push_back
10460               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10461
10462           ++Idx, ++I;
10463         } while (1);
10464       }
10465
10466       // Add any function attributes.
10467       if (Attributes Attr = Attrs.getFnAttributes())
10468         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10469
10470       // The trampoline may have been bitcast to a bogus type (FTy).
10471       // Handle this by synthesizing a new function type, equal to FTy
10472       // with the chain parameter inserted.
10473
10474       std::vector<const Type*> NewTypes;
10475       NewTypes.reserve(FTy->getNumParams()+1);
10476
10477       // Insert the chain's type into the list of parameter types, which may
10478       // mean appending it.
10479       {
10480         unsigned Idx = 1;
10481         FunctionType::param_iterator I = FTy->param_begin(),
10482           E = FTy->param_end();
10483
10484         do {
10485           if (Idx == NestIdx)
10486             // Add the chain's type.
10487             NewTypes.push_back(NestTy);
10488
10489           if (I == E)
10490             break;
10491
10492           // Add the original type.
10493           NewTypes.push_back(*I);
10494
10495           ++Idx, ++I;
10496         } while (1);
10497       }
10498
10499       // Replace the trampoline call with a direct call.  Let the generic
10500       // code sort out any function type mismatches.
10501       FunctionType *NewFTy =
10502                        Context->getFunctionType(FTy->getReturnType(), NewTypes, 
10503                                                 FTy->isVarArg());
10504       Constant *NewCallee =
10505         NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10506         NestF : Context->getConstantExprBitCast(NestF, 
10507                                          Context->getPointerTypeUnqual(NewFTy));
10508       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
10509
10510       Instruction *NewCaller;
10511       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10512         NewCaller = InvokeInst::Create(NewCallee,
10513                                        II->getNormalDest(), II->getUnwindDest(),
10514                                        NewArgs.begin(), NewArgs.end(),
10515                                        Caller->getName(), Caller);
10516         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10517         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10518       } else {
10519         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10520                                      Caller->getName(), Caller);
10521         if (cast<CallInst>(Caller)->isTailCall())
10522           cast<CallInst>(NewCaller)->setTailCall();
10523         cast<CallInst>(NewCaller)->
10524           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10525         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10526       }
10527       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10528         Caller->replaceAllUsesWith(NewCaller);
10529       Caller->eraseFromParent();
10530       RemoveFromWorkList(Caller);
10531       return 0;
10532     }
10533   }
10534
10535   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10536   // parameter, there is no need to adjust the argument list.  Let the generic
10537   // code sort out any function type mismatches.
10538   Constant *NewCallee =
10539     NestF->getType() == PTy ? NestF : 
10540                               Context->getConstantExprBitCast(NestF, PTy);
10541   CS.setCalledFunction(NewCallee);
10542   return CS.getInstruction();
10543 }
10544
10545 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10546 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10547 /// and a single binop.
10548 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10549   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10550   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10551   unsigned Opc = FirstInst->getOpcode();
10552   Value *LHSVal = FirstInst->getOperand(0);
10553   Value *RHSVal = FirstInst->getOperand(1);
10554     
10555   const Type *LHSType = LHSVal->getType();
10556   const Type *RHSType = RHSVal->getType();
10557   
10558   // Scan to see if all operands are the same opcode, all have one use, and all
10559   // kill their operands (i.e. the operands have one use).
10560   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10561     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10562     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10563         // Verify type of the LHS matches so we don't fold cmp's of different
10564         // types or GEP's with different index types.
10565         I->getOperand(0)->getType() != LHSType ||
10566         I->getOperand(1)->getType() != RHSType)
10567       return 0;
10568
10569     // If they are CmpInst instructions, check their predicates
10570     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10571       if (cast<CmpInst>(I)->getPredicate() !=
10572           cast<CmpInst>(FirstInst)->getPredicate())
10573         return 0;
10574     
10575     // Keep track of which operand needs a phi node.
10576     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10577     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10578   }
10579   
10580   // Otherwise, this is safe to transform!
10581   
10582   Value *InLHS = FirstInst->getOperand(0);
10583   Value *InRHS = FirstInst->getOperand(1);
10584   PHINode *NewLHS = 0, *NewRHS = 0;
10585   if (LHSVal == 0) {
10586     NewLHS = PHINode::Create(LHSType,
10587                              FirstInst->getOperand(0)->getName() + ".pn");
10588     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10589     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10590     InsertNewInstBefore(NewLHS, PN);
10591     LHSVal = NewLHS;
10592   }
10593   
10594   if (RHSVal == 0) {
10595     NewRHS = PHINode::Create(RHSType,
10596                              FirstInst->getOperand(1)->getName() + ".pn");
10597     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10598     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10599     InsertNewInstBefore(NewRHS, PN);
10600     RHSVal = NewRHS;
10601   }
10602   
10603   // Add all operands to the new PHIs.
10604   if (NewLHS || NewRHS) {
10605     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10606       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10607       if (NewLHS) {
10608         Value *NewInLHS = InInst->getOperand(0);
10609         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10610       }
10611       if (NewRHS) {
10612         Value *NewInRHS = InInst->getOperand(1);
10613         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10614       }
10615     }
10616   }
10617     
10618   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10619     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10620   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10621   return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10622                          LHSVal, RHSVal);
10623 }
10624
10625 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10626   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10627   
10628   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10629                                         FirstInst->op_end());
10630   // This is true if all GEP bases are allocas and if all indices into them are
10631   // constants.
10632   bool AllBasePointersAreAllocas = true;
10633   
10634   // Scan to see if all operands are the same opcode, all have one use, and all
10635   // kill their operands (i.e. the operands have one use).
10636   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10637     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10638     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10639       GEP->getNumOperands() != FirstInst->getNumOperands())
10640       return 0;
10641
10642     // Keep track of whether or not all GEPs are of alloca pointers.
10643     if (AllBasePointersAreAllocas &&
10644         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10645          !GEP->hasAllConstantIndices()))
10646       AllBasePointersAreAllocas = false;
10647     
10648     // Compare the operand lists.
10649     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10650       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10651         continue;
10652       
10653       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10654       // if one of the PHIs has a constant for the index.  The index may be
10655       // substantially cheaper to compute for the constants, so making it a
10656       // variable index could pessimize the path.  This also handles the case
10657       // for struct indices, which must always be constant.
10658       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10659           isa<ConstantInt>(GEP->getOperand(op)))
10660         return 0;
10661       
10662       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10663         return 0;
10664       FixedOperands[op] = 0;  // Needs a PHI.
10665     }
10666   }
10667   
10668   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10669   // bother doing this transformation.  At best, this will just save a bit of
10670   // offset calculation, but all the predecessors will have to materialize the
10671   // stack address into a register anyway.  We'd actually rather *clone* the
10672   // load up into the predecessors so that we have a load of a gep of an alloca,
10673   // which can usually all be folded into the load.
10674   if (AllBasePointersAreAllocas)
10675     return 0;
10676   
10677   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10678   // that is variable.
10679   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10680   
10681   bool HasAnyPHIs = false;
10682   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10683     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10684     Value *FirstOp = FirstInst->getOperand(i);
10685     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10686                                      FirstOp->getName()+".pn");
10687     InsertNewInstBefore(NewPN, PN);
10688     
10689     NewPN->reserveOperandSpace(e);
10690     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10691     OperandPhis[i] = NewPN;
10692     FixedOperands[i] = NewPN;
10693     HasAnyPHIs = true;
10694   }
10695
10696   
10697   // Add all operands to the new PHIs.
10698   if (HasAnyPHIs) {
10699     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10700       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10701       BasicBlock *InBB = PN.getIncomingBlock(i);
10702       
10703       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10704         if (PHINode *OpPhi = OperandPhis[op])
10705           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10706     }
10707   }
10708   
10709   Value *Base = FixedOperands[0];
10710   return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10711                                    FixedOperands.end());
10712 }
10713
10714
10715 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10716 /// sink the load out of the block that defines it.  This means that it must be
10717 /// obvious the value of the load is not changed from the point of the load to
10718 /// the end of the block it is in.
10719 ///
10720 /// Finally, it is safe, but not profitable, to sink a load targetting a
10721 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10722 /// to a register.
10723 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10724   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10725   
10726   for (++BBI; BBI != E; ++BBI)
10727     if (BBI->mayWriteToMemory())
10728       return false;
10729   
10730   // Check for non-address taken alloca.  If not address-taken already, it isn't
10731   // profitable to do this xform.
10732   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10733     bool isAddressTaken = false;
10734     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10735          UI != E; ++UI) {
10736       if (isa<LoadInst>(UI)) continue;
10737       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10738         // If storing TO the alloca, then the address isn't taken.
10739         if (SI->getOperand(1) == AI) continue;
10740       }
10741       isAddressTaken = true;
10742       break;
10743     }
10744     
10745     if (!isAddressTaken && AI->isStaticAlloca())
10746       return false;
10747   }
10748   
10749   // If this load is a load from a GEP with a constant offset from an alloca,
10750   // then we don't want to sink it.  In its present form, it will be
10751   // load [constant stack offset].  Sinking it will cause us to have to
10752   // materialize the stack addresses in each predecessor in a register only to
10753   // do a shared load from register in the successor.
10754   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10755     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10756       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10757         return false;
10758   
10759   return true;
10760 }
10761
10762
10763 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10764 // operator and they all are only used by the PHI, PHI together their
10765 // inputs, and do the operation once, to the result of the PHI.
10766 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10767   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10768
10769   // Scan the instruction, looking for input operations that can be folded away.
10770   // If all input operands to the phi are the same instruction (e.g. a cast from
10771   // the same type or "+42") we can pull the operation through the PHI, reducing
10772   // code size and simplifying code.
10773   Constant *ConstantOp = 0;
10774   const Type *CastSrcTy = 0;
10775   bool isVolatile = false;
10776   if (isa<CastInst>(FirstInst)) {
10777     CastSrcTy = FirstInst->getOperand(0)->getType();
10778   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10779     // Can fold binop, compare or shift here if the RHS is a constant, 
10780     // otherwise call FoldPHIArgBinOpIntoPHI.
10781     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10782     if (ConstantOp == 0)
10783       return FoldPHIArgBinOpIntoPHI(PN);
10784   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10785     isVolatile = LI->isVolatile();
10786     // We can't sink the load if the loaded value could be modified between the
10787     // load and the PHI.
10788     if (LI->getParent() != PN.getIncomingBlock(0) ||
10789         !isSafeAndProfitableToSinkLoad(LI))
10790       return 0;
10791     
10792     // If the PHI is of volatile loads and the load block has multiple
10793     // successors, sinking it would remove a load of the volatile value from
10794     // the path through the other successor.
10795     if (isVolatile &&
10796         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10797       return 0;
10798     
10799   } else if (isa<GetElementPtrInst>(FirstInst)) {
10800     return FoldPHIArgGEPIntoPHI(PN);
10801   } else {
10802     return 0;  // Cannot fold this operation.
10803   }
10804
10805   // Check to see if all arguments are the same operation.
10806   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10807     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10808     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10809     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10810       return 0;
10811     if (CastSrcTy) {
10812       if (I->getOperand(0)->getType() != CastSrcTy)
10813         return 0;  // Cast operation must match.
10814     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10815       // We can't sink the load if the loaded value could be modified between 
10816       // the load and the PHI.
10817       if (LI->isVolatile() != isVolatile ||
10818           LI->getParent() != PN.getIncomingBlock(i) ||
10819           !isSafeAndProfitableToSinkLoad(LI))
10820         return 0;
10821       
10822       // If the PHI is of volatile loads and the load block has multiple
10823       // successors, sinking it would remove a load of the volatile value from
10824       // the path through the other successor.
10825       if (isVolatile &&
10826           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10827         return 0;
10828       
10829     } else if (I->getOperand(1) != ConstantOp) {
10830       return 0;
10831     }
10832   }
10833
10834   // Okay, they are all the same operation.  Create a new PHI node of the
10835   // correct type, and PHI together all of the LHS's of the instructions.
10836   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10837                                    PN.getName()+".in");
10838   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10839
10840   Value *InVal = FirstInst->getOperand(0);
10841   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10842
10843   // Add all operands to the new PHI.
10844   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10845     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10846     if (NewInVal != InVal)
10847       InVal = 0;
10848     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10849   }
10850
10851   Value *PhiVal;
10852   if (InVal) {
10853     // The new PHI unions all of the same values together.  This is really
10854     // common, so we handle it intelligently here for compile-time speed.
10855     PhiVal = InVal;
10856     delete NewPN;
10857   } else {
10858     InsertNewInstBefore(NewPN, PN);
10859     PhiVal = NewPN;
10860   }
10861
10862   // Insert and return the new operation.
10863   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10864     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10865   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10866     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10867   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10868     return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(), 
10869                            PhiVal, ConstantOp);
10870   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10871   
10872   // If this was a volatile load that we are merging, make sure to loop through
10873   // and mark all the input loads as non-volatile.  If we don't do this, we will
10874   // insert a new volatile load and the old ones will not be deletable.
10875   if (isVolatile)
10876     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10877       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10878   
10879   return new LoadInst(PhiVal, "", isVolatile);
10880 }
10881
10882 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10883 /// that is dead.
10884 static bool DeadPHICycle(PHINode *PN,
10885                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10886   if (PN->use_empty()) return true;
10887   if (!PN->hasOneUse()) return false;
10888
10889   // Remember this node, and if we find the cycle, return.
10890   if (!PotentiallyDeadPHIs.insert(PN))
10891     return true;
10892   
10893   // Don't scan crazily complex things.
10894   if (PotentiallyDeadPHIs.size() == 16)
10895     return false;
10896
10897   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10898     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10899
10900   return false;
10901 }
10902
10903 /// PHIsEqualValue - Return true if this phi node is always equal to
10904 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10905 ///   z = some value; x = phi (y, z); y = phi (x, z)
10906 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10907                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10908   // See if we already saw this PHI node.
10909   if (!ValueEqualPHIs.insert(PN))
10910     return true;
10911   
10912   // Don't scan crazily complex things.
10913   if (ValueEqualPHIs.size() == 16)
10914     return false;
10915  
10916   // Scan the operands to see if they are either phi nodes or are equal to
10917   // the value.
10918   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10919     Value *Op = PN->getIncomingValue(i);
10920     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10921       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10922         return false;
10923     } else if (Op != NonPhiInVal)
10924       return false;
10925   }
10926   
10927   return true;
10928 }
10929
10930
10931 // PHINode simplification
10932 //
10933 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10934   // If LCSSA is around, don't mess with Phi nodes
10935   if (MustPreserveLCSSA) return 0;
10936   
10937   if (Value *V = PN.hasConstantValue())
10938     return ReplaceInstUsesWith(PN, V);
10939
10940   // If all PHI operands are the same operation, pull them through the PHI,
10941   // reducing code size.
10942   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10943       isa<Instruction>(PN.getIncomingValue(1)) &&
10944       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10945       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10946       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10947       // than themselves more than once.
10948       PN.getIncomingValue(0)->hasOneUse())
10949     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10950       return Result;
10951
10952   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10953   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10954   // PHI)... break the cycle.
10955   if (PN.hasOneUse()) {
10956     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10957     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10958       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10959       PotentiallyDeadPHIs.insert(&PN);
10960       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10961         return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10962     }
10963    
10964     // If this phi has a single use, and if that use just computes a value for
10965     // the next iteration of a loop, delete the phi.  This occurs with unused
10966     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10967     // common case here is good because the only other things that catch this
10968     // are induction variable analysis (sometimes) and ADCE, which is only run
10969     // late.
10970     if (PHIUser->hasOneUse() &&
10971         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10972         PHIUser->use_back() == &PN) {
10973       return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10974     }
10975   }
10976
10977   // We sometimes end up with phi cycles that non-obviously end up being the
10978   // same value, for example:
10979   //   z = some value; x = phi (y, z); y = phi (x, z)
10980   // where the phi nodes don't necessarily need to be in the same block.  Do a
10981   // quick check to see if the PHI node only contains a single non-phi value, if
10982   // so, scan to see if the phi cycle is actually equal to that value.
10983   {
10984     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10985     // Scan for the first non-phi operand.
10986     while (InValNo != NumOperandVals && 
10987            isa<PHINode>(PN.getIncomingValue(InValNo)))
10988       ++InValNo;
10989
10990     if (InValNo != NumOperandVals) {
10991       Value *NonPhiInVal = PN.getOperand(InValNo);
10992       
10993       // Scan the rest of the operands to see if there are any conflicts, if so
10994       // there is no need to recursively scan other phis.
10995       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10996         Value *OpVal = PN.getIncomingValue(InValNo);
10997         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10998           break;
10999       }
11000       
11001       // If we scanned over all operands, then we have one unique value plus
11002       // phi values.  Scan PHI nodes to see if they all merge in each other or
11003       // the value.
11004       if (InValNo == NumOperandVals) {
11005         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11006         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11007           return ReplaceInstUsesWith(PN, NonPhiInVal);
11008       }
11009     }
11010   }
11011   return 0;
11012 }
11013
11014 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
11015                                    Instruction *InsertPoint,
11016                                    InstCombiner *IC) {
11017   unsigned PtrSize = DTy->getScalarSizeInBits();
11018   unsigned VTySize = V->getType()->getScalarSizeInBits();
11019   // We must cast correctly to the pointer type. Ensure that we
11020   // sign extend the integer value if it is smaller as this is
11021   // used for address computation.
11022   Instruction::CastOps opcode = 
11023      (VTySize < PtrSize ? Instruction::SExt :
11024       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
11025   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
11026 }
11027
11028
11029 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
11030   Value *PtrOp = GEP.getOperand(0);
11031   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
11032   // If so, eliminate the noop.
11033   if (GEP.getNumOperands() == 1)
11034     return ReplaceInstUsesWith(GEP, PtrOp);
11035
11036   if (isa<UndefValue>(GEP.getOperand(0)))
11037     return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
11038
11039   bool HasZeroPointerIndex = false;
11040   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11041     HasZeroPointerIndex = C->isNullValue();
11042
11043   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11044     return ReplaceInstUsesWith(GEP, PtrOp);
11045
11046   // Eliminate unneeded casts for indices.
11047   bool MadeChange = false;
11048   
11049   gep_type_iterator GTI = gep_type_begin(GEP);
11050   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11051        i != e; ++i, ++GTI) {
11052     if (isa<SequentialType>(*GTI)) {
11053       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
11054         if (CI->getOpcode() == Instruction::ZExt ||
11055             CI->getOpcode() == Instruction::SExt) {
11056           const Type *SrcTy = CI->getOperand(0)->getType();
11057           // We can eliminate a cast from i32 to i64 iff the target 
11058           // is a 32-bit pointer target.
11059           if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
11060             MadeChange = true;
11061             *i = CI->getOperand(0);
11062           }
11063         }
11064       }
11065       // If we are using a wider index than needed for this platform, shrink it
11066       // to what we need.  If narrower, sign-extend it to what we need.
11067       // If the incoming value needs a cast instruction,
11068       // insert it.  This explicit cast can make subsequent optimizations more
11069       // obvious.
11070       Value *Op = *i;
11071       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
11072         if (Constant *C = dyn_cast<Constant>(Op)) {
11073           *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
11074           MadeChange = true;
11075         } else {
11076           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11077                                 GEP);
11078           *i = Op;
11079           MadeChange = true;
11080         }
11081       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
11082         if (Constant *C = dyn_cast<Constant>(Op)) {
11083           *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
11084           MadeChange = true;
11085         } else {
11086           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11087                                 GEP);
11088           *i = Op;
11089           MadeChange = true;
11090         }
11091       }
11092     }
11093   }
11094   if (MadeChange) return &GEP;
11095
11096   // Combine Indices - If the source pointer to this getelementptr instruction
11097   // is a getelementptr instruction, combine the indices of the two
11098   // getelementptr instructions into a single instruction.
11099   //
11100   SmallVector<Value*, 8> SrcGEPOperands;
11101   if (User *Src = dyn_castGetElementPtr(PtrOp))
11102     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
11103
11104   if (!SrcGEPOperands.empty()) {
11105     // Note that if our source is a gep chain itself that we wait for that
11106     // chain to be resolved before we perform this transformation.  This
11107     // avoids us creating a TON of code in some cases.
11108     //
11109     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11110         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11111       return 0;   // Wait until our source is folded to completion.
11112
11113     SmallVector<Value*, 8> Indices;
11114
11115     // Find out whether the last index in the source GEP is a sequential idx.
11116     bool EndsWithSequential = false;
11117     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11118            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11119       EndsWithSequential = !isa<StructType>(*I);
11120
11121     // Can we combine the two pointer arithmetics offsets?
11122     if (EndsWithSequential) {
11123       // Replace: gep (gep %P, long B), long A, ...
11124       // With:    T = long A+B; gep %P, T, ...
11125       //
11126       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
11127       if (SO1 == Context->getNullValue(SO1->getType())) {
11128         Sum = GO1;
11129       } else if (GO1 == Context->getNullValue(GO1->getType())) {
11130         Sum = SO1;
11131       } else {
11132         // If they aren't the same type, convert both to an integer of the
11133         // target's pointer size.
11134         if (SO1->getType() != GO1->getType()) {
11135           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
11136             SO1 =
11137                 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
11138           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
11139             GO1 =
11140                 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
11141           } else {
11142             unsigned PS = TD->getPointerSizeInBits();
11143             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
11144               // Convert GO1 to SO1's type.
11145               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11146
11147             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
11148               // Convert SO1 to GO1's type.
11149               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11150             } else {
11151               const Type *PT = TD->getIntPtrType();
11152               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11153               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11154             }
11155           }
11156         }
11157         if (isa<Constant>(SO1) && isa<Constant>(GO1))
11158           Sum = Context->getConstantExprAdd(cast<Constant>(SO1), 
11159                                             cast<Constant>(GO1));
11160         else {
11161           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11162           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11163         }
11164       }
11165
11166       // Recycle the GEP we already have if possible.
11167       if (SrcGEPOperands.size() == 2) {
11168         GEP.setOperand(0, SrcGEPOperands[0]);
11169         GEP.setOperand(1, Sum);
11170         return &GEP;
11171       } else {
11172         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11173                        SrcGEPOperands.end()-1);
11174         Indices.push_back(Sum);
11175         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11176       }
11177     } else if (isa<Constant>(*GEP.idx_begin()) &&
11178                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11179                SrcGEPOperands.size() != 1) {
11180       // Otherwise we can do the fold if the first index of the GEP is a zero
11181       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11182                      SrcGEPOperands.end());
11183       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11184     }
11185
11186     if (!Indices.empty())
11187       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11188                                        Indices.end(), GEP.getName());
11189
11190   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11191     // GEP of global variable.  If all of the indices for this GEP are
11192     // constants, we can promote this to a constexpr instead of an instruction.
11193
11194     // Scan for nonconstants...
11195     SmallVector<Constant*, 8> Indices;
11196     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11197     for (; I != E && isa<Constant>(*I); ++I)
11198       Indices.push_back(cast<Constant>(*I));
11199
11200     if (I == E) {  // If they are all constants...
11201       Constant *CE = Context->getConstantExprGetElementPtr(GV,
11202                                                     &Indices[0],Indices.size());
11203
11204       // Replace all uses of the GEP with the new constexpr...
11205       return ReplaceInstUsesWith(GEP, CE);
11206     }
11207   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
11208     if (!isa<PointerType>(X->getType())) {
11209       // Not interesting.  Source pointer must be a cast from pointer.
11210     } else if (HasZeroPointerIndex) {
11211       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11212       // into     : GEP [10 x i8]* X, i32 0, ...
11213       //
11214       // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11215       //           into     : GEP i8* X, ...
11216       // 
11217       // This occurs when the program declares an array extern like "int X[];"
11218       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11219       const PointerType *XTy = cast<PointerType>(X->getType());
11220       if (const ArrayType *CATy =
11221           dyn_cast<ArrayType>(CPTy->getElementType())) {
11222         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11223         if (CATy->getElementType() == XTy->getElementType()) {
11224           // -> GEP i8* X, ...
11225           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11226           return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11227                                            GEP.getName());
11228         } else if (const ArrayType *XATy =
11229                  dyn_cast<ArrayType>(XTy->getElementType())) {
11230           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11231           if (CATy->getElementType() == XATy->getElementType()) {
11232             // -> GEP [10 x i8]* X, i32 0, ...
11233             // At this point, we know that the cast source type is a pointer
11234             // to an array of the same type as the destination pointer
11235             // array.  Because the array type is never stepped over (there
11236             // is a leading zero) we can fold the cast into this GEP.
11237             GEP.setOperand(0, X);
11238             return &GEP;
11239           }
11240         }
11241       }
11242     } else if (GEP.getNumOperands() == 2) {
11243       // Transform things like:
11244       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11245       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11246       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11247       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11248       if (isa<ArrayType>(SrcElTy) &&
11249           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11250           TD->getTypeAllocSize(ResElTy)) {
11251         Value *Idx[2];
11252         Idx[0] = Context->getNullValue(Type::Int32Ty);
11253         Idx[1] = GEP.getOperand(1);
11254         Value *V = InsertNewInstBefore(
11255                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
11256         // V and GEP are both pointer types --> BitCast
11257         return new BitCastInst(V, GEP.getType());
11258       }
11259       
11260       // Transform things like:
11261       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11262       //   (where tmp = 8*tmp2) into:
11263       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11264       
11265       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
11266         uint64_t ArrayEltSize =
11267             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11268         
11269         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11270         // allow either a mul, shift, or constant here.
11271         Value *NewIdx = 0;
11272         ConstantInt *Scale = 0;
11273         if (ArrayEltSize == 1) {
11274           NewIdx = GEP.getOperand(1);
11275           Scale = 
11276                Context->getConstantInt(cast<IntegerType>(NewIdx->getType()), 1);
11277         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11278           NewIdx = Context->getConstantInt(CI->getType(), 1);
11279           Scale = CI;
11280         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11281           if (Inst->getOpcode() == Instruction::Shl &&
11282               isa<ConstantInt>(Inst->getOperand(1))) {
11283             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11284             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11285             Scale = Context->getConstantInt(cast<IntegerType>(Inst->getType()),
11286                                      1ULL << ShAmtVal);
11287             NewIdx = Inst->getOperand(0);
11288           } else if (Inst->getOpcode() == Instruction::Mul &&
11289                      isa<ConstantInt>(Inst->getOperand(1))) {
11290             Scale = cast<ConstantInt>(Inst->getOperand(1));
11291             NewIdx = Inst->getOperand(0);
11292           }
11293         }
11294         
11295         // If the index will be to exactly the right offset with the scale taken
11296         // out, perform the transformation. Note, we don't know whether Scale is
11297         // signed or not. We'll use unsigned version of division/modulo
11298         // operation after making sure Scale doesn't have the sign bit set.
11299         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11300             Scale->getZExtValue() % ArrayEltSize == 0) {
11301           Scale = Context->getConstantInt(Scale->getType(),
11302                                    Scale->getZExtValue() / ArrayEltSize);
11303           if (Scale->getZExtValue() != 1) {
11304             Constant *C =
11305                    Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
11306                                                        false /*ZExt*/);
11307             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11308             NewIdx = InsertNewInstBefore(Sc, GEP);
11309           }
11310
11311           // Insert the new GEP instruction.
11312           Value *Idx[2];
11313           Idx[0] = Context->getNullValue(Type::Int32Ty);
11314           Idx[1] = NewIdx;
11315           Instruction *NewGEP =
11316             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11317           NewGEP = InsertNewInstBefore(NewGEP, GEP);
11318           // The NewGEP must be pointer typed, so must the old one -> BitCast
11319           return new BitCastInst(NewGEP, GEP.getType());
11320         }
11321       }
11322     }
11323   }
11324   
11325   /// See if we can simplify:
11326   ///   X = bitcast A to B*
11327   ///   Y = gep X, <...constant indices...>
11328   /// into a gep of the original struct.  This is important for SROA and alias
11329   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11330   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11331     if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11332       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11333       // a constant back from EmitGEPOffset.
11334       ConstantInt *OffsetV =
11335                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11336       int64_t Offset = OffsetV->getSExtValue();
11337       
11338       // If this GEP instruction doesn't move the pointer, just replace the GEP
11339       // with a bitcast of the real input to the dest type.
11340       if (Offset == 0) {
11341         // If the bitcast is of an allocation, and the allocation will be
11342         // converted to match the type of the cast, don't touch this.
11343         if (isa<AllocationInst>(BCI->getOperand(0))) {
11344           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11345           if (Instruction *I = visitBitCast(*BCI)) {
11346             if (I != BCI) {
11347               I->takeName(BCI);
11348               BCI->getParent()->getInstList().insert(BCI, I);
11349               ReplaceInstUsesWith(*BCI, I);
11350             }
11351             return &GEP;
11352           }
11353         }
11354         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11355       }
11356       
11357       // Otherwise, if the offset is non-zero, we need to find out if there is a
11358       // field at Offset in 'A's type.  If so, we can pull the cast through the
11359       // GEP.
11360       SmallVector<Value*, 8> NewIndices;
11361       const Type *InTy =
11362         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11363       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11364         Instruction *NGEP =
11365            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11366                                      NewIndices.end());
11367         if (NGEP->getType() == GEP.getType()) return NGEP;
11368         InsertNewInstBefore(NGEP, GEP);
11369         NGEP->takeName(&GEP);
11370         return new BitCastInst(NGEP, GEP.getType());
11371       }
11372     }
11373   }    
11374     
11375   return 0;
11376 }
11377
11378 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11379   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11380   if (AI.isArrayAllocation()) {  // Check C != 1
11381     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11382       const Type *NewTy = 
11383         Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
11384       AllocationInst *New = 0;
11385
11386       // Create and insert the replacement instruction...
11387       if (isa<MallocInst>(AI))
11388         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11389       else {
11390         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11391         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11392       }
11393
11394       InsertNewInstBefore(New, AI);
11395
11396       // Scan to the end of the allocation instructions, to skip over a block of
11397       // allocas if possible...also skip interleaved debug info
11398       //
11399       BasicBlock::iterator It = New;
11400       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11401
11402       // Now that I is pointing to the first non-allocation-inst in the block,
11403       // insert our getelementptr instruction...
11404       //
11405       Value *NullIdx = Context->getNullValue(Type::Int32Ty);
11406       Value *Idx[2];
11407       Idx[0] = NullIdx;
11408       Idx[1] = NullIdx;
11409       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11410                                            New->getName()+".sub", It);
11411
11412       // Now make everything use the getelementptr instead of the original
11413       // allocation.
11414       return ReplaceInstUsesWith(AI, V);
11415     } else if (isa<UndefValue>(AI.getArraySize())) {
11416       return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11417     }
11418   }
11419
11420   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11421     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11422     // Note that we only do this for alloca's, because malloc should allocate
11423     // and return a unique pointer, even for a zero byte allocation.
11424     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11425       return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11426
11427     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11428     if (AI.getAlignment() == 0)
11429       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11430   }
11431
11432   return 0;
11433 }
11434
11435 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11436   Value *Op = FI.getOperand(0);
11437
11438   // free undef -> unreachable.
11439   if (isa<UndefValue>(Op)) {
11440     // Insert a new store to null because we cannot modify the CFG here.
11441     new StoreInst(Context->getConstantIntTrue(),
11442            Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
11443     return EraseInstFromFunction(FI);
11444   }
11445   
11446   // If we have 'free null' delete the instruction.  This can happen in stl code
11447   // when lots of inlining happens.
11448   if (isa<ConstantPointerNull>(Op))
11449     return EraseInstFromFunction(FI);
11450   
11451   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11452   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11453     FI.setOperand(0, CI->getOperand(0));
11454     return &FI;
11455   }
11456   
11457   // Change free (gep X, 0,0,0,0) into free(X)
11458   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11459     if (GEPI->hasAllZeroIndices()) {
11460       AddToWorkList(GEPI);
11461       FI.setOperand(0, GEPI->getOperand(0));
11462       return &FI;
11463     }
11464   }
11465   
11466   // Change free(malloc) into nothing, if the malloc has a single use.
11467   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11468     if (MI->hasOneUse()) {
11469       EraseInstFromFunction(FI);
11470       return EraseInstFromFunction(*MI);
11471     }
11472
11473   return 0;
11474 }
11475
11476
11477 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11478 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11479                                         const TargetData *TD) {
11480   User *CI = cast<User>(LI.getOperand(0));
11481   Value *CastOp = CI->getOperand(0);
11482   LLVMContext *Context = IC.getContext();
11483
11484   if (TD) {
11485     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11486       // Instead of loading constant c string, use corresponding integer value
11487       // directly if string length is small enough.
11488       std::string Str;
11489       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11490         unsigned len = Str.length();
11491         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11492         unsigned numBits = Ty->getPrimitiveSizeInBits();
11493         // Replace LI with immediate integer store.
11494         if ((numBits >> 3) == len + 1) {
11495           APInt StrVal(numBits, 0);
11496           APInt SingleChar(numBits, 0);
11497           if (TD->isLittleEndian()) {
11498             for (signed i = len-1; i >= 0; i--) {
11499               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11500               StrVal = (StrVal << 8) | SingleChar;
11501             }
11502           } else {
11503             for (unsigned i = 0; i < len; i++) {
11504               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11505               StrVal = (StrVal << 8) | SingleChar;
11506             }
11507             // Append NULL at the end.
11508             SingleChar = 0;
11509             StrVal = (StrVal << 8) | SingleChar;
11510           }
11511           Value *NL = Context->getConstantInt(StrVal);
11512           return IC.ReplaceInstUsesWith(LI, NL);
11513         }
11514       }
11515     }
11516   }
11517
11518   const PointerType *DestTy = cast<PointerType>(CI->getType());
11519   const Type *DestPTy = DestTy->getElementType();
11520   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11521
11522     // If the address spaces don't match, don't eliminate the cast.
11523     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11524       return 0;
11525
11526     const Type *SrcPTy = SrcTy->getElementType();
11527
11528     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11529          isa<VectorType>(DestPTy)) {
11530       // If the source is an array, the code below will not succeed.  Check to
11531       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11532       // constants.
11533       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11534         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11535           if (ASrcTy->getNumElements() != 0) {
11536             Value *Idxs[2];
11537             Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11538             CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
11539             SrcTy = cast<PointerType>(CastOp->getType());
11540             SrcPTy = SrcTy->getElementType();
11541           }
11542
11543       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11544             isa<VectorType>(SrcPTy)) &&
11545           // Do not allow turning this into a load of an integer, which is then
11546           // casted to a pointer, this pessimizes pointer analysis a lot.
11547           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11548           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11549                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11550
11551         // Okay, we are casting from one integer or pointer type to another of
11552         // the same size.  Instead of casting the pointer before the load, cast
11553         // the result of the loaded value.
11554         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11555                                                              CI->getName(),
11556                                                          LI.isVolatile()),LI);
11557         // Now cast the result of the load.
11558         return new BitCastInst(NewLoad, LI.getType());
11559       }
11560     }
11561   }
11562   return 0;
11563 }
11564
11565 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11566   Value *Op = LI.getOperand(0);
11567
11568   // Attempt to improve the alignment.
11569   unsigned KnownAlign =
11570     GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11571   if (KnownAlign >
11572       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11573                                 LI.getAlignment()))
11574     LI.setAlignment(KnownAlign);
11575
11576   // load (cast X) --> cast (load X) iff safe
11577   if (isa<CastInst>(Op))
11578     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11579       return Res;
11580
11581   // None of the following transforms are legal for volatile loads.
11582   if (LI.isVolatile()) return 0;
11583   
11584   // Do really simple store-to-load forwarding and load CSE, to catch cases
11585   // where there are several consequtive memory accesses to the same location,
11586   // separated by a few arithmetic operations.
11587   BasicBlock::iterator BBI = &LI;
11588   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11589     return ReplaceInstUsesWith(LI, AvailableVal);
11590
11591   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11592     const Value *GEPI0 = GEPI->getOperand(0);
11593     // TODO: Consider a target hook for valid address spaces for this xform.
11594     if (isa<ConstantPointerNull>(GEPI0) &&
11595         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11596       // Insert a new store to null instruction before the load to indicate
11597       // that this code is not reachable.  We do this instead of inserting
11598       // an unreachable instruction directly because we cannot modify the
11599       // CFG.
11600       new StoreInst(Context->getUndef(LI.getType()),
11601                     Context->getNullValue(Op->getType()), &LI);
11602       return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11603     }
11604   } 
11605
11606   if (Constant *C = dyn_cast<Constant>(Op)) {
11607     // load null/undef -> undef
11608     // TODO: Consider a target hook for valid address spaces for this xform.
11609     if (isa<UndefValue>(C) || (C->isNullValue() && 
11610         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11611       // Insert a new store to null instruction before the load to indicate that
11612       // this code is not reachable.  We do this instead of inserting an
11613       // unreachable instruction directly because we cannot modify the CFG.
11614       new StoreInst(Context->getUndef(LI.getType()),
11615                     Context->getNullValue(Op->getType()), &LI);
11616       return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11617     }
11618
11619     // Instcombine load (constant global) into the value loaded.
11620     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11621       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11622         return ReplaceInstUsesWith(LI, GV->getInitializer());
11623
11624     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11625     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11626       if (CE->getOpcode() == Instruction::GetElementPtr) {
11627         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11628           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11629             if (Constant *V = 
11630                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE, 
11631                                                       Context))
11632               return ReplaceInstUsesWith(LI, V);
11633         if (CE->getOperand(0)->isNullValue()) {
11634           // Insert a new store to null instruction before the load to indicate
11635           // that this code is not reachable.  We do this instead of inserting
11636           // an unreachable instruction directly because we cannot modify the
11637           // CFG.
11638           new StoreInst(Context->getUndef(LI.getType()),
11639                         Context->getNullValue(Op->getType()), &LI);
11640           return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11641         }
11642
11643       } else if (CE->isCast()) {
11644         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11645           return Res;
11646       }
11647     }
11648   }
11649     
11650   // If this load comes from anywhere in a constant global, and if the global
11651   // is all undef or zero, we know what it loads.
11652   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11653     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11654       if (GV->getInitializer()->isNullValue())
11655         return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
11656       else if (isa<UndefValue>(GV->getInitializer()))
11657         return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11658     }
11659   }
11660
11661   if (Op->hasOneUse()) {
11662     // Change select and PHI nodes to select values instead of addresses: this
11663     // helps alias analysis out a lot, allows many others simplifications, and
11664     // exposes redundancy in the code.
11665     //
11666     // Note that we cannot do the transformation unless we know that the
11667     // introduced loads cannot trap!  Something like this is valid as long as
11668     // the condition is always false: load (select bool %C, int* null, int* %G),
11669     // but it would not be valid if we transformed it to load from null
11670     // unconditionally.
11671     //
11672     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11673       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11674       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11675           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11676         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11677                                      SI->getOperand(1)->getName()+".val"), LI);
11678         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11679                                      SI->getOperand(2)->getName()+".val"), LI);
11680         return SelectInst::Create(SI->getCondition(), V1, V2);
11681       }
11682
11683       // load (select (cond, null, P)) -> load P
11684       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11685         if (C->isNullValue()) {
11686           LI.setOperand(0, SI->getOperand(2));
11687           return &LI;
11688         }
11689
11690       // load (select (cond, P, null)) -> load P
11691       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11692         if (C->isNullValue()) {
11693           LI.setOperand(0, SI->getOperand(1));
11694           return &LI;
11695         }
11696     }
11697   }
11698   return 0;
11699 }
11700
11701 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11702 /// when possible.  This makes it generally easy to do alias analysis and/or
11703 /// SROA/mem2reg of the memory object.
11704 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11705   User *CI = cast<User>(SI.getOperand(1));
11706   Value *CastOp = CI->getOperand(0);
11707   LLVMContext *Context = IC.getContext();
11708
11709   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11710   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11711   if (SrcTy == 0) return 0;
11712   
11713   const Type *SrcPTy = SrcTy->getElementType();
11714
11715   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11716     return 0;
11717   
11718   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11719   /// to its first element.  This allows us to handle things like:
11720   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11721   /// on 32-bit hosts.
11722   SmallVector<Value*, 4> NewGEPIndices;
11723   
11724   // If the source is an array, the code below will not succeed.  Check to
11725   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11726   // constants.
11727   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11728     // Index through pointer.
11729     Constant *Zero = Context->getNullValue(Type::Int32Ty);
11730     NewGEPIndices.push_back(Zero);
11731     
11732     while (1) {
11733       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11734         if (!STy->getNumElements()) /* Struct can be empty {} */
11735           break;
11736         NewGEPIndices.push_back(Zero);
11737         SrcPTy = STy->getElementType(0);
11738       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11739         NewGEPIndices.push_back(Zero);
11740         SrcPTy = ATy->getElementType();
11741       } else {
11742         break;
11743       }
11744     }
11745     
11746     SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
11747   }
11748
11749   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11750     return 0;
11751   
11752   // If the pointers point into different address spaces or if they point to
11753   // values with different sizes, we can't do the transformation.
11754   if (SrcTy->getAddressSpace() != 
11755         cast<PointerType>(CI->getType())->getAddressSpace() ||
11756       IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
11757       IC.getTargetData().getTypeSizeInBits(DestPTy))
11758     return 0;
11759
11760   // Okay, we are casting from one integer or pointer type to another of
11761   // the same size.  Instead of casting the pointer before 
11762   // the store, cast the value to be stored.
11763   Value *NewCast;
11764   Value *SIOp0 = SI.getOperand(0);
11765   Instruction::CastOps opcode = Instruction::BitCast;
11766   const Type* CastSrcTy = SIOp0->getType();
11767   const Type* CastDstTy = SrcPTy;
11768   if (isa<PointerType>(CastDstTy)) {
11769     if (CastSrcTy->isInteger())
11770       opcode = Instruction::IntToPtr;
11771   } else if (isa<IntegerType>(CastDstTy)) {
11772     if (isa<PointerType>(SIOp0->getType()))
11773       opcode = Instruction::PtrToInt;
11774   }
11775   
11776   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11777   // emit a GEP to index into its first field.
11778   if (!NewGEPIndices.empty()) {
11779     if (Constant *C = dyn_cast<Constant>(CastOp))
11780       CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0], 
11781                                               NewGEPIndices.size());
11782     else
11783       CastOp = IC.InsertNewInstBefore(
11784               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11785                                         NewGEPIndices.end()), SI);
11786   }
11787   
11788   if (Constant *C = dyn_cast<Constant>(SIOp0))
11789     NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
11790   else
11791     NewCast = IC.InsertNewInstBefore(
11792       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11793       SI);
11794   return new StoreInst(NewCast, CastOp);
11795 }
11796
11797 /// equivalentAddressValues - Test if A and B will obviously have the same
11798 /// value. This includes recognizing that %t0 and %t1 will have the same
11799 /// value in code like this:
11800 ///   %t0 = getelementptr \@a, 0, 3
11801 ///   store i32 0, i32* %t0
11802 ///   %t1 = getelementptr \@a, 0, 3
11803 ///   %t2 = load i32* %t1
11804 ///
11805 static bool equivalentAddressValues(Value *A, Value *B) {
11806   // Test if the values are trivially equivalent.
11807   if (A == B) return true;
11808   
11809   // Test if the values come form identical arithmetic instructions.
11810   if (isa<BinaryOperator>(A) ||
11811       isa<CastInst>(A) ||
11812       isa<PHINode>(A) ||
11813       isa<GetElementPtrInst>(A))
11814     if (Instruction *BI = dyn_cast<Instruction>(B))
11815       if (cast<Instruction>(A)->isIdenticalTo(BI))
11816         return true;
11817   
11818   // Otherwise they may not be equivalent.
11819   return false;
11820 }
11821
11822 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11823 // return the llvm.dbg.declare.
11824 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11825   if (!V->hasNUses(2))
11826     return 0;
11827   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11828        UI != E; ++UI) {
11829     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11830       return DI;
11831     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11832       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11833         return DI;
11834       }
11835   }
11836   return 0;
11837 }
11838
11839 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11840   Value *Val = SI.getOperand(0);
11841   Value *Ptr = SI.getOperand(1);
11842
11843   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11844     EraseInstFromFunction(SI);
11845     ++NumCombined;
11846     return 0;
11847   }
11848   
11849   // If the RHS is an alloca with a single use, zapify the store, making the
11850   // alloca dead.
11851   // If the RHS is an alloca with a two uses, the other one being a 
11852   // llvm.dbg.declare, zapify the store and the declare, making the
11853   // alloca dead.  We must do this to prevent declare's from affecting
11854   // codegen.
11855   if (!SI.isVolatile()) {
11856     if (Ptr->hasOneUse()) {
11857       if (isa<AllocaInst>(Ptr)) {
11858         EraseInstFromFunction(SI);
11859         ++NumCombined;
11860         return 0;
11861       }
11862       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11863         if (isa<AllocaInst>(GEP->getOperand(0))) {
11864           if (GEP->getOperand(0)->hasOneUse()) {
11865             EraseInstFromFunction(SI);
11866             ++NumCombined;
11867             return 0;
11868           }
11869           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11870             EraseInstFromFunction(*DI);
11871             EraseInstFromFunction(SI);
11872             ++NumCombined;
11873             return 0;
11874           }
11875         }
11876       }
11877     }
11878     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11879       EraseInstFromFunction(*DI);
11880       EraseInstFromFunction(SI);
11881       ++NumCombined;
11882       return 0;
11883     }
11884   }
11885
11886   // Attempt to improve the alignment.
11887   unsigned KnownAlign =
11888     GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11889   if (KnownAlign >
11890       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11891                                 SI.getAlignment()))
11892     SI.setAlignment(KnownAlign);
11893
11894   // Do really simple DSE, to catch cases where there are several consecutive
11895   // stores to the same location, separated by a few arithmetic operations. This
11896   // situation often occurs with bitfield accesses.
11897   BasicBlock::iterator BBI = &SI;
11898   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11899        --ScanInsts) {
11900     --BBI;
11901     // Don't count debug info directives, lest they affect codegen,
11902     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11903     // It is necessary for correctness to skip those that feed into a
11904     // llvm.dbg.declare, as these are not present when debugging is off.
11905     if (isa<DbgInfoIntrinsic>(BBI) ||
11906         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11907       ScanInsts++;
11908       continue;
11909     }    
11910     
11911     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11912       // Prev store isn't volatile, and stores to the same location?
11913       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11914                                                           SI.getOperand(1))) {
11915         ++NumDeadStore;
11916         ++BBI;
11917         EraseInstFromFunction(*PrevSI);
11918         continue;
11919       }
11920       break;
11921     }
11922     
11923     // If this is a load, we have to stop.  However, if the loaded value is from
11924     // the pointer we're loading and is producing the pointer we're storing,
11925     // then *this* store is dead (X = load P; store X -> P).
11926     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11927       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11928           !SI.isVolatile()) {
11929         EraseInstFromFunction(SI);
11930         ++NumCombined;
11931         return 0;
11932       }
11933       // Otherwise, this is a load from some other location.  Stores before it
11934       // may not be dead.
11935       break;
11936     }
11937     
11938     // Don't skip over loads or things that can modify memory.
11939     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11940       break;
11941   }
11942   
11943   
11944   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11945
11946   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11947   if (isa<ConstantPointerNull>(Ptr) &&
11948       cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11949     if (!isa<UndefValue>(Val)) {
11950       SI.setOperand(0, Context->getUndef(Val->getType()));
11951       if (Instruction *U = dyn_cast<Instruction>(Val))
11952         AddToWorkList(U);  // Dropped a use.
11953       ++NumCombined;
11954     }
11955     return 0;  // Do not modify these!
11956   }
11957
11958   // store undef, Ptr -> noop
11959   if (isa<UndefValue>(Val)) {
11960     EraseInstFromFunction(SI);
11961     ++NumCombined;
11962     return 0;
11963   }
11964
11965   // If the pointer destination is a cast, see if we can fold the cast into the
11966   // source instead.
11967   if (isa<CastInst>(Ptr))
11968     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11969       return Res;
11970   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11971     if (CE->isCast())
11972       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11973         return Res;
11974
11975   
11976   // If this store is the last instruction in the basic block (possibly
11977   // excepting debug info instructions and the pointer bitcasts that feed
11978   // into them), and if the block ends with an unconditional branch, try
11979   // to move it to the successor block.
11980   BBI = &SI; 
11981   do {
11982     ++BBI;
11983   } while (isa<DbgInfoIntrinsic>(BBI) ||
11984            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11985   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11986     if (BI->isUnconditional())
11987       if (SimplifyStoreAtEndOfBlock(SI))
11988         return 0;  // xform done!
11989   
11990   return 0;
11991 }
11992
11993 /// SimplifyStoreAtEndOfBlock - Turn things like:
11994 ///   if () { *P = v1; } else { *P = v2 }
11995 /// into a phi node with a store in the successor.
11996 ///
11997 /// Simplify things like:
11998 ///   *P = v1; if () { *P = v2; }
11999 /// into a phi node with a store in the successor.
12000 ///
12001 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12002   BasicBlock *StoreBB = SI.getParent();
12003   
12004   // Check to see if the successor block has exactly two incoming edges.  If
12005   // so, see if the other predecessor contains a store to the same location.
12006   // if so, insert a PHI node (if needed) and move the stores down.
12007   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
12008   
12009   // Determine whether Dest has exactly two predecessors and, if so, compute
12010   // the other predecessor.
12011   pred_iterator PI = pred_begin(DestBB);
12012   BasicBlock *OtherBB = 0;
12013   if (*PI != StoreBB)
12014     OtherBB = *PI;
12015   ++PI;
12016   if (PI == pred_end(DestBB))
12017     return false;
12018   
12019   if (*PI != StoreBB) {
12020     if (OtherBB)
12021       return false;
12022     OtherBB = *PI;
12023   }
12024   if (++PI != pred_end(DestBB))
12025     return false;
12026
12027   // Bail out if all the relevant blocks aren't distinct (this can happen,
12028   // for example, if SI is in an infinite loop)
12029   if (StoreBB == DestBB || OtherBB == DestBB)
12030     return false;
12031
12032   // Verify that the other block ends in a branch and is not otherwise empty.
12033   BasicBlock::iterator BBI = OtherBB->getTerminator();
12034   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12035   if (!OtherBr || BBI == OtherBB->begin())
12036     return false;
12037   
12038   // If the other block ends in an unconditional branch, check for the 'if then
12039   // else' case.  there is an instruction before the branch.
12040   StoreInst *OtherStore = 0;
12041   if (OtherBr->isUnconditional()) {
12042     --BBI;
12043     // Skip over debugging info.
12044     while (isa<DbgInfoIntrinsic>(BBI) ||
12045            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12046       if (BBI==OtherBB->begin())
12047         return false;
12048       --BBI;
12049     }
12050     // If this isn't a store, or isn't a store to the same location, bail out.
12051     OtherStore = dyn_cast<StoreInst>(BBI);
12052     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12053       return false;
12054   } else {
12055     // Otherwise, the other block ended with a conditional branch. If one of the
12056     // destinations is StoreBB, then we have the if/then case.
12057     if (OtherBr->getSuccessor(0) != StoreBB && 
12058         OtherBr->getSuccessor(1) != StoreBB)
12059       return false;
12060     
12061     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12062     // if/then triangle.  See if there is a store to the same ptr as SI that
12063     // lives in OtherBB.
12064     for (;; --BBI) {
12065       // Check to see if we find the matching store.
12066       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12067         if (OtherStore->getOperand(1) != SI.getOperand(1))
12068           return false;
12069         break;
12070       }
12071       // If we find something that may be using or overwriting the stored
12072       // value, or if we run out of instructions, we can't do the xform.
12073       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12074           BBI == OtherBB->begin())
12075         return false;
12076     }
12077     
12078     // In order to eliminate the store in OtherBr, we have to
12079     // make sure nothing reads or overwrites the stored value in
12080     // StoreBB.
12081     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12082       // FIXME: This should really be AA driven.
12083       if (I->mayReadFromMemory() || I->mayWriteToMemory())
12084         return false;
12085     }
12086   }
12087   
12088   // Insert a PHI node now if we need it.
12089   Value *MergedVal = OtherStore->getOperand(0);
12090   if (MergedVal != SI.getOperand(0)) {
12091     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12092     PN->reserveOperandSpace(2);
12093     PN->addIncoming(SI.getOperand(0), SI.getParent());
12094     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12095     MergedVal = InsertNewInstBefore(PN, DestBB->front());
12096   }
12097   
12098   // Advance to a place where it is safe to insert the new store and
12099   // insert it.
12100   BBI = DestBB->getFirstNonPHI();
12101   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12102                                     OtherStore->isVolatile()), *BBI);
12103   
12104   // Nuke the old stores.
12105   EraseInstFromFunction(SI);
12106   EraseInstFromFunction(*OtherStore);
12107   ++NumCombined;
12108   return true;
12109 }
12110
12111
12112 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12113   // Change br (not X), label True, label False to: br X, label False, True
12114   Value *X = 0;
12115   BasicBlock *TrueDest;
12116   BasicBlock *FalseDest;
12117   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
12118       !isa<Constant>(X)) {
12119     // Swap Destinations and condition...
12120     BI.setCondition(X);
12121     BI.setSuccessor(0, FalseDest);
12122     BI.setSuccessor(1, TrueDest);
12123     return &BI;
12124   }
12125
12126   // Cannonicalize fcmp_one -> fcmp_oeq
12127   FCmpInst::Predicate FPred; Value *Y;
12128   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
12129                              TrueDest, FalseDest), *Context))
12130     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12131          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12132       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12133       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
12134       Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
12135       NewSCC->takeName(I);
12136       // Swap Destinations and condition...
12137       BI.setCondition(NewSCC);
12138       BI.setSuccessor(0, FalseDest);
12139       BI.setSuccessor(1, TrueDest);
12140       RemoveFromWorkList(I);
12141       I->eraseFromParent();
12142       AddToWorkList(NewSCC);
12143       return &BI;
12144     }
12145
12146   // Cannonicalize icmp_ne -> icmp_eq
12147   ICmpInst::Predicate IPred;
12148   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12149                       TrueDest, FalseDest), *Context))
12150     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12151          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12152          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12153       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12154       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
12155       Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
12156       NewSCC->takeName(I);
12157       // Swap Destinations and condition...
12158       BI.setCondition(NewSCC);
12159       BI.setSuccessor(0, FalseDest);
12160       BI.setSuccessor(1, TrueDest);
12161       RemoveFromWorkList(I);
12162       I->eraseFromParent();;
12163       AddToWorkList(NewSCC);
12164       return &BI;
12165     }
12166
12167   return 0;
12168 }
12169
12170 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12171   Value *Cond = SI.getCondition();
12172   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12173     if (I->getOpcode() == Instruction::Add)
12174       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12175         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12176         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12177           SI.setOperand(i,
12178                    Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
12179                                                 AddRHS));
12180         SI.setOperand(0, I->getOperand(0));
12181         AddToWorkList(I);
12182         return &SI;
12183       }
12184   }
12185   return 0;
12186 }
12187
12188 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12189   Value *Agg = EV.getAggregateOperand();
12190
12191   if (!EV.hasIndices())
12192     return ReplaceInstUsesWith(EV, Agg);
12193
12194   if (Constant *C = dyn_cast<Constant>(Agg)) {
12195     if (isa<UndefValue>(C))
12196       return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
12197       
12198     if (isa<ConstantAggregateZero>(C))
12199       return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
12200
12201     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12202       // Extract the element indexed by the first index out of the constant
12203       Value *V = C->getOperand(*EV.idx_begin());
12204       if (EV.getNumIndices() > 1)
12205         // Extract the remaining indices out of the constant indexed by the
12206         // first index
12207         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12208       else
12209         return ReplaceInstUsesWith(EV, V);
12210     }
12211     return 0; // Can't handle other constants
12212   } 
12213   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12214     // We're extracting from an insertvalue instruction, compare the indices
12215     const unsigned *exti, *exte, *insi, *inse;
12216     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12217          exte = EV.idx_end(), inse = IV->idx_end();
12218          exti != exte && insi != inse;
12219          ++exti, ++insi) {
12220       if (*insi != *exti)
12221         // The insert and extract both reference distinctly different elements.
12222         // This means the extract is not influenced by the insert, and we can
12223         // replace the aggregate operand of the extract with the aggregate
12224         // operand of the insert. i.e., replace
12225         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12226         // %E = extractvalue { i32, { i32 } } %I, 0
12227         // with
12228         // %E = extractvalue { i32, { i32 } } %A, 0
12229         return ExtractValueInst::Create(IV->getAggregateOperand(),
12230                                         EV.idx_begin(), EV.idx_end());
12231     }
12232     if (exti == exte && insi == inse)
12233       // Both iterators are at the end: Index lists are identical. Replace
12234       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12235       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12236       // with "i32 42"
12237       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12238     if (exti == exte) {
12239       // The extract list is a prefix of the insert list. i.e. replace
12240       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12241       // %E = extractvalue { i32, { i32 } } %I, 1
12242       // with
12243       // %X = extractvalue { i32, { i32 } } %A, 1
12244       // %E = insertvalue { i32 } %X, i32 42, 0
12245       // by switching the order of the insert and extract (though the
12246       // insertvalue should be left in, since it may have other uses).
12247       Value *NewEV = InsertNewInstBefore(
12248         ExtractValueInst::Create(IV->getAggregateOperand(),
12249                                  EV.idx_begin(), EV.idx_end()),
12250         EV);
12251       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12252                                      insi, inse);
12253     }
12254     if (insi == inse)
12255       // The insert list is a prefix of the extract list
12256       // We can simply remove the common indices from the extract and make it
12257       // operate on the inserted value instead of the insertvalue result.
12258       // i.e., replace
12259       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12260       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12261       // with
12262       // %E extractvalue { i32 } { i32 42 }, 0
12263       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12264                                       exti, exte);
12265   }
12266   // Can't simplify extracts from other values. Note that nested extracts are
12267   // already simplified implicitely by the above (extract ( extract (insert) )
12268   // will be translated into extract ( insert ( extract ) ) first and then just
12269   // the value inserted, if appropriate).
12270   return 0;
12271 }
12272
12273 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12274 /// is to leave as a vector operation.
12275 static bool CheapToScalarize(Value *V, bool isConstant) {
12276   if (isa<ConstantAggregateZero>(V)) 
12277     return true;
12278   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12279     if (isConstant) return true;
12280     // If all elts are the same, we can extract.
12281     Constant *Op0 = C->getOperand(0);
12282     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12283       if (C->getOperand(i) != Op0)
12284         return false;
12285     return true;
12286   }
12287   Instruction *I = dyn_cast<Instruction>(V);
12288   if (!I) return false;
12289   
12290   // Insert element gets simplified to the inserted element or is deleted if
12291   // this is constant idx extract element and its a constant idx insertelt.
12292   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12293       isa<ConstantInt>(I->getOperand(2)))
12294     return true;
12295   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12296     return true;
12297   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12298     if (BO->hasOneUse() &&
12299         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12300          CheapToScalarize(BO->getOperand(1), isConstant)))
12301       return true;
12302   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12303     if (CI->hasOneUse() &&
12304         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12305          CheapToScalarize(CI->getOperand(1), isConstant)))
12306       return true;
12307   
12308   return false;
12309 }
12310
12311 /// Read and decode a shufflevector mask.
12312 ///
12313 /// It turns undef elements into values that are larger than the number of
12314 /// elements in the input.
12315 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12316   unsigned NElts = SVI->getType()->getNumElements();
12317   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12318     return std::vector<unsigned>(NElts, 0);
12319   if (isa<UndefValue>(SVI->getOperand(2)))
12320     return std::vector<unsigned>(NElts, 2*NElts);
12321
12322   std::vector<unsigned> Result;
12323   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12324   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12325     if (isa<UndefValue>(*i))
12326       Result.push_back(NElts*2);  // undef -> 8
12327     else
12328       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12329   return Result;
12330 }
12331
12332 /// FindScalarElement - Given a vector and an element number, see if the scalar
12333 /// value is already around as a register, for example if it were inserted then
12334 /// extracted from the vector.
12335 static Value *FindScalarElement(Value *V, unsigned EltNo,
12336                                 LLVMContext *Context) {
12337   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12338   const VectorType *PTy = cast<VectorType>(V->getType());
12339   unsigned Width = PTy->getNumElements();
12340   if (EltNo >= Width)  // Out of range access.
12341     return Context->getUndef(PTy->getElementType());
12342   
12343   if (isa<UndefValue>(V))
12344     return Context->getUndef(PTy->getElementType());
12345   else if (isa<ConstantAggregateZero>(V))
12346     return Context->getNullValue(PTy->getElementType());
12347   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12348     return CP->getOperand(EltNo);
12349   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12350     // If this is an insert to a variable element, we don't know what it is.
12351     if (!isa<ConstantInt>(III->getOperand(2))) 
12352       return 0;
12353     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12354     
12355     // If this is an insert to the element we are looking for, return the
12356     // inserted value.
12357     if (EltNo == IIElt) 
12358       return III->getOperand(1);
12359     
12360     // Otherwise, the insertelement doesn't modify the value, recurse on its
12361     // vector input.
12362     return FindScalarElement(III->getOperand(0), EltNo, Context);
12363   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12364     unsigned LHSWidth =
12365       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12366     unsigned InEl = getShuffleMask(SVI)[EltNo];
12367     if (InEl < LHSWidth)
12368       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12369     else if (InEl < LHSWidth*2)
12370       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12371     else
12372       return Context->getUndef(PTy->getElementType());
12373   }
12374   
12375   // Otherwise, we don't know.
12376   return 0;
12377 }
12378
12379 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12380   // If vector val is undef, replace extract with scalar undef.
12381   if (isa<UndefValue>(EI.getOperand(0)))
12382     return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12383
12384   // If vector val is constant 0, replace extract with scalar 0.
12385   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12386     return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
12387   
12388   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12389     // If vector val is constant with all elements the same, replace EI with
12390     // that element. When the elements are not identical, we cannot replace yet
12391     // (we do that below, but only when the index is constant).
12392     Constant *op0 = C->getOperand(0);
12393     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12394       if (C->getOperand(i) != op0) {
12395         op0 = 0; 
12396         break;
12397       }
12398     if (op0)
12399       return ReplaceInstUsesWith(EI, op0);
12400   }
12401   
12402   // If extracting a specified index from the vector, see if we can recursively
12403   // find a previously computed scalar that was inserted into the vector.
12404   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12405     unsigned IndexVal = IdxC->getZExtValue();
12406     unsigned VectorWidth = 
12407       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12408       
12409     // If this is extracting an invalid index, turn this into undef, to avoid
12410     // crashing the code below.
12411     if (IndexVal >= VectorWidth)
12412       return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12413     
12414     // This instruction only demands the single element from the input vector.
12415     // If the input vector has a single use, simplify it based on this use
12416     // property.
12417     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12418       APInt UndefElts(VectorWidth, 0);
12419       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12420       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12421                                                 DemandedMask, UndefElts)) {
12422         EI.setOperand(0, V);
12423         return &EI;
12424       }
12425     }
12426     
12427     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12428       return ReplaceInstUsesWith(EI, Elt);
12429     
12430     // If the this extractelement is directly using a bitcast from a vector of
12431     // the same number of elements, see if we can find the source element from
12432     // it.  In this case, we will end up needing to bitcast the scalars.
12433     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12434       if (const VectorType *VT = 
12435               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12436         if (VT->getNumElements() == VectorWidth)
12437           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12438                                              IndexVal, Context))
12439             return new BitCastInst(Elt, EI.getType());
12440     }
12441   }
12442   
12443   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12444     if (I->hasOneUse()) {
12445       // Push extractelement into predecessor operation if legal and
12446       // profitable to do so
12447       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12448         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12449         if (CheapToScalarize(BO, isConstantElt)) {
12450           ExtractElementInst *newEI0 = 
12451             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12452                                    EI.getName()+".lhs");
12453           ExtractElementInst *newEI1 =
12454             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12455                                    EI.getName()+".rhs");
12456           InsertNewInstBefore(newEI0, EI);
12457           InsertNewInstBefore(newEI1, EI);
12458           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12459         }
12460       } else if (isa<LoadInst>(I)) {
12461         unsigned AS = 
12462           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12463         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12464                                   Context->getPointerType(EI.getType(), AS),EI);
12465         GetElementPtrInst *GEP =
12466           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12467         InsertNewInstBefore(GEP, EI);
12468         return new LoadInst(GEP);
12469       }
12470     }
12471     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12472       // Extracting the inserted element?
12473       if (IE->getOperand(2) == EI.getOperand(1))
12474         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12475       // If the inserted and extracted elements are constants, they must not
12476       // be the same value, extract from the pre-inserted value instead.
12477       if (isa<Constant>(IE->getOperand(2)) &&
12478           isa<Constant>(EI.getOperand(1))) {
12479         AddUsesToWorkList(EI);
12480         EI.setOperand(0, IE->getOperand(0));
12481         return &EI;
12482       }
12483     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12484       // If this is extracting an element from a shufflevector, figure out where
12485       // it came from and extract from the appropriate input element instead.
12486       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12487         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12488         Value *Src;
12489         unsigned LHSWidth =
12490           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12491
12492         if (SrcIdx < LHSWidth)
12493           Src = SVI->getOperand(0);
12494         else if (SrcIdx < LHSWidth*2) {
12495           SrcIdx -= LHSWidth;
12496           Src = SVI->getOperand(1);
12497         } else {
12498           return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12499         }
12500         return new ExtractElementInst(Src, SrcIdx);
12501       }
12502     }
12503   }
12504   return 0;
12505 }
12506
12507 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12508 /// elements from either LHS or RHS, return the shuffle mask and true. 
12509 /// Otherwise, return false.
12510 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12511                                          std::vector<Constant*> &Mask,
12512                                          LLVMContext *Context) {
12513   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12514          "Invalid CollectSingleShuffleElements");
12515   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12516
12517   if (isa<UndefValue>(V)) {
12518     Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12519     return true;
12520   } else if (V == LHS) {
12521     for (unsigned i = 0; i != NumElts; ++i)
12522       Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12523     return true;
12524   } else if (V == RHS) {
12525     for (unsigned i = 0; i != NumElts; ++i)
12526       Mask.push_back(Context->getConstantInt(Type::Int32Ty, i+NumElts));
12527     return true;
12528   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12529     // If this is an insert of an extract from some other vector, include it.
12530     Value *VecOp    = IEI->getOperand(0);
12531     Value *ScalarOp = IEI->getOperand(1);
12532     Value *IdxOp    = IEI->getOperand(2);
12533     
12534     if (!isa<ConstantInt>(IdxOp))
12535       return false;
12536     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12537     
12538     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12539       // Okay, we can handle this if the vector we are insertinting into is
12540       // transitively ok.
12541       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12542         // If so, update the mask to reflect the inserted undef.
12543         Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
12544         return true;
12545       }      
12546     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12547       if (isa<ConstantInt>(EI->getOperand(1)) &&
12548           EI->getOperand(0)->getType() == V->getType()) {
12549         unsigned ExtractedIdx =
12550           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12551         
12552         // This must be extracting from either LHS or RHS.
12553         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12554           // Okay, we can handle this if the vector we are insertinting into is
12555           // transitively ok.
12556           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12557             // If so, update the mask to reflect the inserted value.
12558             if (EI->getOperand(0) == LHS) {
12559               Mask[InsertedIdx % NumElts] = 
12560                  Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12561             } else {
12562               assert(EI->getOperand(0) == RHS);
12563               Mask[InsertedIdx % NumElts] = 
12564                 Context->getConstantInt(Type::Int32Ty, ExtractedIdx+NumElts);
12565               
12566             }
12567             return true;
12568           }
12569         }
12570       }
12571     }
12572   }
12573   // TODO: Handle shufflevector here!
12574   
12575   return false;
12576 }
12577
12578 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12579 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12580 /// that computes V and the LHS value of the shuffle.
12581 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12582                                      Value *&RHS, LLVMContext *Context) {
12583   assert(isa<VectorType>(V->getType()) && 
12584          (RHS == 0 || V->getType() == RHS->getType()) &&
12585          "Invalid shuffle!");
12586   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12587
12588   if (isa<UndefValue>(V)) {
12589     Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12590     return V;
12591   } else if (isa<ConstantAggregateZero>(V)) {
12592     Mask.assign(NumElts, Context->getConstantInt(Type::Int32Ty, 0));
12593     return V;
12594   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12595     // If this is an insert of an extract from some other vector, include it.
12596     Value *VecOp    = IEI->getOperand(0);
12597     Value *ScalarOp = IEI->getOperand(1);
12598     Value *IdxOp    = IEI->getOperand(2);
12599     
12600     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12601       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12602           EI->getOperand(0)->getType() == V->getType()) {
12603         unsigned ExtractedIdx =
12604           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12605         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12606         
12607         // Either the extracted from or inserted into vector must be RHSVec,
12608         // otherwise we'd end up with a shuffle of three inputs.
12609         if (EI->getOperand(0) == RHS || RHS == 0) {
12610           RHS = EI->getOperand(0);
12611           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12612           Mask[InsertedIdx % NumElts] = 
12613             Context->getConstantInt(Type::Int32Ty, NumElts+ExtractedIdx);
12614           return V;
12615         }
12616         
12617         if (VecOp == RHS) {
12618           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12619                                             RHS, Context);
12620           // Everything but the extracted element is replaced with the RHS.
12621           for (unsigned i = 0; i != NumElts; ++i) {
12622             if (i != InsertedIdx)
12623               Mask[i] = Context->getConstantInt(Type::Int32Ty, NumElts+i);
12624           }
12625           return V;
12626         }
12627         
12628         // If this insertelement is a chain that comes from exactly these two
12629         // vectors, return the vector and the effective shuffle.
12630         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12631                                          Context))
12632           return EI->getOperand(0);
12633         
12634       }
12635     }
12636   }
12637   // TODO: Handle shufflevector here!
12638   
12639   // Otherwise, can't do anything fancy.  Return an identity vector.
12640   for (unsigned i = 0; i != NumElts; ++i)
12641     Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12642   return V;
12643 }
12644
12645 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12646   Value *VecOp    = IE.getOperand(0);
12647   Value *ScalarOp = IE.getOperand(1);
12648   Value *IdxOp    = IE.getOperand(2);
12649   
12650   // Inserting an undef or into an undefined place, remove this.
12651   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12652     ReplaceInstUsesWith(IE, VecOp);
12653   
12654   // If the inserted element was extracted from some other vector, and if the 
12655   // indexes are constant, try to turn this into a shufflevector operation.
12656   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12657     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12658         EI->getOperand(0)->getType() == IE.getType()) {
12659       unsigned NumVectorElts = IE.getType()->getNumElements();
12660       unsigned ExtractedIdx =
12661         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12662       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12663       
12664       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12665         return ReplaceInstUsesWith(IE, VecOp);
12666       
12667       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12668         return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
12669       
12670       // If we are extracting a value from a vector, then inserting it right
12671       // back into the same place, just use the input vector.
12672       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12673         return ReplaceInstUsesWith(IE, VecOp);      
12674       
12675       // We could theoretically do this for ANY input.  However, doing so could
12676       // turn chains of insertelement instructions into a chain of shufflevector
12677       // instructions, and right now we do not merge shufflevectors.  As such,
12678       // only do this in a situation where it is clear that there is benefit.
12679       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12680         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12681         // the values of VecOp, except then one read from EIOp0.
12682         // Build a new shuffle mask.
12683         std::vector<Constant*> Mask;
12684         if (isa<UndefValue>(VecOp))
12685           Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
12686         else {
12687           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12688           Mask.assign(NumVectorElts, Context->getConstantInt(Type::Int32Ty,
12689                                                        NumVectorElts));
12690         } 
12691         Mask[InsertedIdx] = 
12692                            Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12693         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12694                                      Context->getConstantVector(Mask));
12695       }
12696       
12697       // If this insertelement isn't used by some other insertelement, turn it
12698       // (and any insertelements it points to), into one big shuffle.
12699       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12700         std::vector<Constant*> Mask;
12701         Value *RHS = 0;
12702         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12703         if (RHS == 0) RHS = Context->getUndef(LHS->getType());
12704         // We now have a shuffle of LHS, RHS, Mask.
12705         return new ShuffleVectorInst(LHS, RHS,
12706                                      Context->getConstantVector(Mask));
12707       }
12708     }
12709   }
12710
12711   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12712   APInt UndefElts(VWidth, 0);
12713   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12714   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12715     return &IE;
12716
12717   return 0;
12718 }
12719
12720
12721 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12722   Value *LHS = SVI.getOperand(0);
12723   Value *RHS = SVI.getOperand(1);
12724   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12725
12726   bool MadeChange = false;
12727
12728   // Undefined shuffle mask -> undefined value.
12729   if (isa<UndefValue>(SVI.getOperand(2)))
12730     return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
12731
12732   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12733
12734   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12735     return 0;
12736
12737   APInt UndefElts(VWidth, 0);
12738   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12739   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12740     LHS = SVI.getOperand(0);
12741     RHS = SVI.getOperand(1);
12742     MadeChange = true;
12743   }
12744   
12745   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12746   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12747   if (LHS == RHS || isa<UndefValue>(LHS)) {
12748     if (isa<UndefValue>(LHS) && LHS == RHS) {
12749       // shuffle(undef,undef,mask) -> undef.
12750       return ReplaceInstUsesWith(SVI, LHS);
12751     }
12752     
12753     // Remap any references to RHS to use LHS.
12754     std::vector<Constant*> Elts;
12755     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12756       if (Mask[i] >= 2*e)
12757         Elts.push_back(Context->getUndef(Type::Int32Ty));
12758       else {
12759         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12760             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12761           Mask[i] = 2*e;     // Turn into undef.
12762           Elts.push_back(Context->getUndef(Type::Int32Ty));
12763         } else {
12764           Mask[i] = Mask[i] % e;  // Force to LHS.
12765           Elts.push_back(Context->getConstantInt(Type::Int32Ty, Mask[i]));
12766         }
12767       }
12768     }
12769     SVI.setOperand(0, SVI.getOperand(1));
12770     SVI.setOperand(1, Context->getUndef(RHS->getType()));
12771     SVI.setOperand(2, Context->getConstantVector(Elts));
12772     LHS = SVI.getOperand(0);
12773     RHS = SVI.getOperand(1);
12774     MadeChange = true;
12775   }
12776   
12777   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12778   bool isLHSID = true, isRHSID = true;
12779     
12780   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12781     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12782     // Is this an identity shuffle of the LHS value?
12783     isLHSID &= (Mask[i] == i);
12784       
12785     // Is this an identity shuffle of the RHS value?
12786     isRHSID &= (Mask[i]-e == i);
12787   }
12788
12789   // Eliminate identity shuffles.
12790   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12791   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12792   
12793   // If the LHS is a shufflevector itself, see if we can combine it with this
12794   // one without producing an unusual shuffle.  Here we are really conservative:
12795   // we are absolutely afraid of producing a shuffle mask not in the input
12796   // program, because the code gen may not be smart enough to turn a merged
12797   // shuffle into two specific shuffles: it may produce worse code.  As such,
12798   // we only merge two shuffles if the result is one of the two input shuffle
12799   // masks.  In this case, merging the shuffles just removes one instruction,
12800   // which we know is safe.  This is good for things like turning:
12801   // (splat(splat)) -> splat.
12802   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12803     if (isa<UndefValue>(RHS)) {
12804       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12805
12806       std::vector<unsigned> NewMask;
12807       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12808         if (Mask[i] >= 2*e)
12809           NewMask.push_back(2*e);
12810         else
12811           NewMask.push_back(LHSMask[Mask[i]]);
12812       
12813       // If the result mask is equal to the src shuffle or this shuffle mask, do
12814       // the replacement.
12815       if (NewMask == LHSMask || NewMask == Mask) {
12816         unsigned LHSInNElts =
12817           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12818         std::vector<Constant*> Elts;
12819         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12820           if (NewMask[i] >= LHSInNElts*2) {
12821             Elts.push_back(Context->getUndef(Type::Int32Ty));
12822           } else {
12823             Elts.push_back(Context->getConstantInt(Type::Int32Ty, NewMask[i]));
12824           }
12825         }
12826         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12827                                      LHSSVI->getOperand(1),
12828                                      Context->getConstantVector(Elts));
12829       }
12830     }
12831   }
12832
12833   return MadeChange ? &SVI : 0;
12834 }
12835
12836
12837
12838
12839 /// TryToSinkInstruction - Try to move the specified instruction from its
12840 /// current block into the beginning of DestBlock, which can only happen if it's
12841 /// safe to move the instruction past all of the instructions between it and the
12842 /// end of its block.
12843 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12844   assert(I->hasOneUse() && "Invariants didn't hold!");
12845
12846   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12847   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12848     return false;
12849
12850   // Do not sink alloca instructions out of the entry block.
12851   if (isa<AllocaInst>(I) && I->getParent() ==
12852         &DestBlock->getParent()->getEntryBlock())
12853     return false;
12854
12855   // We can only sink load instructions if there is nothing between the load and
12856   // the end of block that could change the value.
12857   if (I->mayReadFromMemory()) {
12858     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12859          Scan != E; ++Scan)
12860       if (Scan->mayWriteToMemory())
12861         return false;
12862   }
12863
12864   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12865
12866   CopyPrecedingStopPoint(I, InsertPos);
12867   I->moveBefore(InsertPos);
12868   ++NumSunkInst;
12869   return true;
12870 }
12871
12872
12873 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12874 /// all reachable code to the worklist.
12875 ///
12876 /// This has a couple of tricks to make the code faster and more powerful.  In
12877 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12878 /// them to the worklist (this significantly speeds up instcombine on code where
12879 /// many instructions are dead or constant).  Additionally, if we find a branch
12880 /// whose condition is a known constant, we only visit the reachable successors.
12881 ///
12882 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12883                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12884                                        InstCombiner &IC,
12885                                        const TargetData *TD) {
12886   SmallVector<BasicBlock*, 256> Worklist;
12887   Worklist.push_back(BB);
12888
12889   while (!Worklist.empty()) {
12890     BB = Worklist.back();
12891     Worklist.pop_back();
12892     
12893     // We have now visited this block!  If we've already been here, ignore it.
12894     if (!Visited.insert(BB)) continue;
12895
12896     DbgInfoIntrinsic *DBI_Prev = NULL;
12897     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12898       Instruction *Inst = BBI++;
12899       
12900       // DCE instruction if trivially dead.
12901       if (isInstructionTriviallyDead(Inst)) {
12902         ++NumDeadInst;
12903         DOUT << "IC: DCE: " << *Inst;
12904         Inst->eraseFromParent();
12905         continue;
12906       }
12907       
12908       // ConstantProp instruction if trivially constant.
12909       if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12910         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12911         Inst->replaceAllUsesWith(C);
12912         ++NumConstProp;
12913         Inst->eraseFromParent();
12914         continue;
12915       }
12916      
12917       // If there are two consecutive llvm.dbg.stoppoint calls then
12918       // it is likely that the optimizer deleted code in between these
12919       // two intrinsics. 
12920       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12921       if (DBI_Next) {
12922         if (DBI_Prev
12923             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12924             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12925           IC.RemoveFromWorkList(DBI_Prev);
12926           DBI_Prev->eraseFromParent();
12927         }
12928         DBI_Prev = DBI_Next;
12929       } else {
12930         DBI_Prev = 0;
12931       }
12932
12933       IC.AddToWorkList(Inst);
12934     }
12935
12936     // Recursively visit successors.  If this is a branch or switch on a
12937     // constant, only visit the reachable successor.
12938     TerminatorInst *TI = BB->getTerminator();
12939     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12940       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12941         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12942         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12943         Worklist.push_back(ReachableBB);
12944         continue;
12945       }
12946     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12947       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12948         // See if this is an explicit destination.
12949         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12950           if (SI->getCaseValue(i) == Cond) {
12951             BasicBlock *ReachableBB = SI->getSuccessor(i);
12952             Worklist.push_back(ReachableBB);
12953             continue;
12954           }
12955         
12956         // Otherwise it is the default destination.
12957         Worklist.push_back(SI->getSuccessor(0));
12958         continue;
12959       }
12960     }
12961     
12962     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12963       Worklist.push_back(TI->getSuccessor(i));
12964   }
12965 }
12966
12967 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12968   bool Changed = false;
12969   TD = &getAnalysis<TargetData>();
12970   
12971   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12972              << F.getNameStr() << "\n");
12973
12974   {
12975     // Do a depth-first traversal of the function, populate the worklist with
12976     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12977     // track of which blocks we visit.
12978     SmallPtrSet<BasicBlock*, 64> Visited;
12979     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12980
12981     // Do a quick scan over the function.  If we find any blocks that are
12982     // unreachable, remove any instructions inside of them.  This prevents
12983     // the instcombine code from having to deal with some bad special cases.
12984     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12985       if (!Visited.count(BB)) {
12986         Instruction *Term = BB->getTerminator();
12987         while (Term != BB->begin()) {   // Remove instrs bottom-up
12988           BasicBlock::iterator I = Term; --I;
12989
12990           DOUT << "IC: DCE: " << *I;
12991           // A debug intrinsic shouldn't force another iteration if we weren't
12992           // going to do one without it.
12993           if (!isa<DbgInfoIntrinsic>(I)) {
12994             ++NumDeadInst;
12995             Changed = true;
12996           }
12997           if (!I->use_empty())
12998             I->replaceAllUsesWith(Context->getUndef(I->getType()));
12999           I->eraseFromParent();
13000         }
13001       }
13002   }
13003
13004   while (!Worklist.empty()) {
13005     Instruction *I = RemoveOneFromWorkList();
13006     if (I == 0) continue;  // skip null values.
13007
13008     // Check to see if we can DCE the instruction.
13009     if (isInstructionTriviallyDead(I)) {
13010       // Add operands to the worklist.
13011       if (I->getNumOperands() < 4)
13012         AddUsesToWorkList(*I);
13013       ++NumDeadInst;
13014
13015       DOUT << "IC: DCE: " << *I;
13016
13017       I->eraseFromParent();
13018       RemoveFromWorkList(I);
13019       Changed = true;
13020       continue;
13021     }
13022
13023     // Instruction isn't dead, see if we can constant propagate it.
13024     if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
13025       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
13026
13027       // Add operands to the worklist.
13028       AddUsesToWorkList(*I);
13029       ReplaceInstUsesWith(*I, C);
13030
13031       ++NumConstProp;
13032       I->eraseFromParent();
13033       RemoveFromWorkList(I);
13034       Changed = true;
13035       continue;
13036     }
13037
13038     if (TD &&
13039         (I->getType()->getTypeID() == Type::VoidTyID ||
13040          I->isTrapping())) {
13041       // See if we can constant fold its operands.
13042       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13043         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
13044           if (Constant *NewC = ConstantFoldConstantExpression(CE,   
13045                                   F.getContext(), TD))
13046             if (NewC != CE) {
13047               i->set(NewC);
13048               Changed = true;
13049             }
13050     }
13051
13052     // See if we can trivially sink this instruction to a successor basic block.
13053     if (I->hasOneUse()) {
13054       BasicBlock *BB = I->getParent();
13055       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13056       if (UserParent != BB) {
13057         bool UserIsSuccessor = false;
13058         // See if the user is one of our successors.
13059         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13060           if (*SI == UserParent) {
13061             UserIsSuccessor = true;
13062             break;
13063           }
13064
13065         // If the user is one of our immediate successors, and if that successor
13066         // only has us as a predecessors (we'd have to split the critical edge
13067         // otherwise), we can keep going.
13068         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13069             next(pred_begin(UserParent)) == pred_end(UserParent))
13070           // Okay, the CFG is simple enough, try to sink this instruction.
13071           Changed |= TryToSinkInstruction(I, UserParent);
13072       }
13073     }
13074
13075     // Now that we have an instruction, try combining it to simplify it...
13076 #ifndef NDEBUG
13077     std::string OrigI;
13078 #endif
13079     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
13080     if (Instruction *Result = visit(*I)) {
13081       ++NumCombined;
13082       // Should we replace the old instruction with a new one?
13083       if (Result != I) {
13084         DOUT << "IC: Old = " << *I
13085              << "    New = " << *Result;
13086
13087         // Everything uses the new instruction now.
13088         I->replaceAllUsesWith(Result);
13089
13090         // Push the new instruction and any users onto the worklist.
13091         AddToWorkList(Result);
13092         AddUsersToWorkList(*Result);
13093
13094         // Move the name to the new instruction first.
13095         Result->takeName(I);
13096
13097         // Insert the new instruction into the basic block...
13098         BasicBlock *InstParent = I->getParent();
13099         BasicBlock::iterator InsertPos = I;
13100
13101         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
13102           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13103             ++InsertPos;
13104
13105         InstParent->getInstList().insert(InsertPos, Result);
13106
13107         // Make sure that we reprocess all operands now that we reduced their
13108         // use counts.
13109         AddUsesToWorkList(*I);
13110
13111         // Instructions can end up on the worklist more than once.  Make sure
13112         // we do not process an instruction that has been deleted.
13113         RemoveFromWorkList(I);
13114
13115         // Erase the old instruction.
13116         InstParent->getInstList().erase(I);
13117       } else {
13118 #ifndef NDEBUG
13119         DOUT << "IC: Mod = " << OrigI
13120              << "    New = " << *I;
13121 #endif
13122
13123         // If the instruction was modified, it's possible that it is now dead.
13124         // if so, remove it.
13125         if (isInstructionTriviallyDead(I)) {
13126           // Make sure we process all operands now that we are reducing their
13127           // use counts.
13128           AddUsesToWorkList(*I);
13129
13130           // Instructions may end up in the worklist more than once.  Erase all
13131           // occurrences of this instruction.
13132           RemoveFromWorkList(I);
13133           I->eraseFromParent();
13134         } else {
13135           AddToWorkList(I);
13136           AddUsersToWorkList(*I);
13137         }
13138       }
13139       Changed = true;
13140     }
13141   }
13142
13143   assert(WorklistMap.empty() && "Worklist empty, but map not?");
13144     
13145   // Do an explicit clear, this shrinks the map if needed.
13146   WorklistMap.clear();
13147   return Changed;
13148 }
13149
13150
13151 bool InstCombiner::runOnFunction(Function &F) {
13152   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13153   
13154   bool EverMadeChange = false;
13155
13156   // Iterate while there is work to do.
13157   unsigned Iteration = 0;
13158   while (DoOneIteration(F, Iteration++))
13159     EverMadeChange = true;
13160   return EverMadeChange;
13161 }
13162
13163 FunctionPass *llvm::createInstructionCombiningPass() {
13164   return new InstCombiner();
13165 }