Fix old-style type names in comments.
[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/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/Analysis/ConstantFolding.h"
43 #include "llvm/Analysis/ValueTracking.h"
44 #include "llvm/Target/TargetData.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Support/CallSite.h"
48 #include "llvm/Support/ConstantRange.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/GetElementPtrTypeIterator.h"
51 #include "llvm/Support/InstVisitor.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/PatternMatch.h"
54 #include "llvm/Support/Compiler.h"
55 #include "llvm/ADT/DenseMap.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/SmallPtrSet.h"
58 #include "llvm/ADT/Statistic.h"
59 #include "llvm/ADT/STLExtras.h"
60 #include <algorithm>
61 #include <climits>
62 #include <sstream>
63 using namespace llvm;
64 using namespace llvm::PatternMatch;
65
66 STATISTIC(NumCombined , "Number of insts combined");
67 STATISTIC(NumConstProp, "Number of constant folds");
68 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70 STATISTIC(NumSunkInst , "Number of instructions sunk");
71
72 namespace {
73   class VISIBILITY_HIDDEN InstCombiner
74     : public FunctionPass,
75       public InstVisitor<InstCombiner, Instruction*> {
76     // Worklist of all of the instructions that need to be simplified.
77     SmallVector<Instruction*, 256> Worklist;
78     DenseMap<Instruction*, unsigned> WorklistMap;
79     TargetData *TD;
80     bool MustPreserveLCSSA;
81   public:
82     static char ID; // Pass identification, replacement for typeid
83     InstCombiner() : FunctionPass(&ID) {}
84
85     /// AddToWorkList - Add the specified instruction to the worklist if it
86     /// isn't already in it.
87     void AddToWorkList(Instruction *I) {
88       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
89         Worklist.push_back(I);
90     }
91     
92     // RemoveFromWorkList - remove I from the worklist if it exists.
93     void RemoveFromWorkList(Instruction *I) {
94       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95       if (It == WorklistMap.end()) return; // Not in worklist.
96       
97       // Don't bother moving everything down, just null out the slot.
98       Worklist[It->second] = 0;
99       
100       WorklistMap.erase(It);
101     }
102     
103     Instruction *RemoveOneFromWorkList() {
104       Instruction *I = Worklist.back();
105       Worklist.pop_back();
106       WorklistMap.erase(I);
107       return I;
108     }
109
110     
111     /// AddUsersToWorkList - When an instruction is simplified, add all users of
112     /// the instruction to the work lists because they might get more simplified
113     /// now.
114     ///
115     void AddUsersToWorkList(Value &I) {
116       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
117            UI != UE; ++UI)
118         AddToWorkList(cast<Instruction>(*UI));
119     }
120
121     /// AddUsesToWorkList - When an instruction is simplified, add operands to
122     /// the work lists because they might get more simplified now.
123     ///
124     void AddUsesToWorkList(Instruction &I) {
125       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
126         if (Instruction *Op = dyn_cast<Instruction>(*i))
127           AddToWorkList(Op);
128     }
129     
130     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131     /// dead.  Add all of its operands to the worklist, turning them into
132     /// undef's to reduce the number of uses of those instructions.
133     ///
134     /// Return the specified operand before it is turned into an undef.
135     ///
136     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137       Value *R = I.getOperand(op);
138       
139       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
140         if (Instruction *Op = dyn_cast<Instruction>(*i)) {
141           AddToWorkList(Op);
142           // Set the operand to undef to drop the use.
143           *i = UndefValue::get(Op->getType());
144         }
145       
146       return R;
147     }
148
149   public:
150     virtual bool runOnFunction(Function &F);
151     
152     bool DoOneIteration(Function &F, unsigned ItNum);
153
154     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
155       AU.addRequired<TargetData>();
156       AU.addPreservedID(LCSSAID);
157       AU.setPreservesCFG();
158     }
159
160     TargetData &getTargetData() const { return *TD; }
161
162     // Visitation implementation - Implement instruction combining for different
163     // instruction types.  The semantics are as follows:
164     // Return Value:
165     //    null        - No change was made
166     //     I          - Change was made, I is still valid, I may be dead though
167     //   otherwise    - Change was made, replace I with returned instruction
168     //
169     Instruction *visitAdd(BinaryOperator &I);
170     Instruction *visitFAdd(BinaryOperator &I);
171     Instruction *visitSub(BinaryOperator &I);
172     Instruction *visitFSub(BinaryOperator &I);
173     Instruction *visitMul(BinaryOperator &I);
174     Instruction *visitFMul(BinaryOperator &I);
175     Instruction *visitURem(BinaryOperator &I);
176     Instruction *visitSRem(BinaryOperator &I);
177     Instruction *visitFRem(BinaryOperator &I);
178     bool SimplifyDivRemOfSelect(BinaryOperator &I);
179     Instruction *commonRemTransforms(BinaryOperator &I);
180     Instruction *commonIRemTransforms(BinaryOperator &I);
181     Instruction *commonDivTransforms(BinaryOperator &I);
182     Instruction *commonIDivTransforms(BinaryOperator &I);
183     Instruction *visitUDiv(BinaryOperator &I);
184     Instruction *visitSDiv(BinaryOperator &I);
185     Instruction *visitFDiv(BinaryOperator &I);
186     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
187     Instruction *visitAnd(BinaryOperator &I);
188     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
189     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
190                                      Value *A, Value *B, Value *C);
191     Instruction *visitOr (BinaryOperator &I);
192     Instruction *visitXor(BinaryOperator &I);
193     Instruction *visitShl(BinaryOperator &I);
194     Instruction *visitAShr(BinaryOperator &I);
195     Instruction *visitLShr(BinaryOperator &I);
196     Instruction *commonShiftTransforms(BinaryOperator &I);
197     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
198                                       Constant *RHSC);
199     Instruction *visitFCmpInst(FCmpInst &I);
200     Instruction *visitICmpInst(ICmpInst &I);
201     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
202     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
203                                                 Instruction *LHS,
204                                                 ConstantInt *RHS);
205     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
206                                 ConstantInt *DivRHS);
207
208     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
209                              ICmpInst::Predicate Cond, Instruction &I);
210     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
211                                      BinaryOperator &I);
212     Instruction *commonCastTransforms(CastInst &CI);
213     Instruction *commonIntCastTransforms(CastInst &CI);
214     Instruction *commonPointerCastTransforms(CastInst &CI);
215     Instruction *visitTrunc(TruncInst &CI);
216     Instruction *visitZExt(ZExtInst &CI);
217     Instruction *visitSExt(SExtInst &CI);
218     Instruction *visitFPTrunc(FPTruncInst &CI);
219     Instruction *visitFPExt(CastInst &CI);
220     Instruction *visitFPToUI(FPToUIInst &FI);
221     Instruction *visitFPToSI(FPToSIInst &FI);
222     Instruction *visitUIToFP(CastInst &CI);
223     Instruction *visitSIToFP(CastInst &CI);
224     Instruction *visitPtrToInt(PtrToIntInst &CI);
225     Instruction *visitIntToPtr(IntToPtrInst &CI);
226     Instruction *visitBitCast(BitCastInst &CI);
227     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
228                                 Instruction *FI);
229     Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
230     Instruction *visitSelectInst(SelectInst &SI);
231     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
232     Instruction *visitCallInst(CallInst &CI);
233     Instruction *visitInvokeInst(InvokeInst &II);
234     Instruction *visitPHINode(PHINode &PN);
235     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
236     Instruction *visitAllocationInst(AllocationInst &AI);
237     Instruction *visitFreeInst(FreeInst &FI);
238     Instruction *visitLoadInst(LoadInst &LI);
239     Instruction *visitStoreInst(StoreInst &SI);
240     Instruction *visitBranchInst(BranchInst &BI);
241     Instruction *visitSwitchInst(SwitchInst &SI);
242     Instruction *visitInsertElementInst(InsertElementInst &IE);
243     Instruction *visitExtractElementInst(ExtractElementInst &EI);
244     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
245     Instruction *visitExtractValueInst(ExtractValueInst &EV);
246
247     // visitInstruction - Specify what to return for unhandled instructions...
248     Instruction *visitInstruction(Instruction &I) { return 0; }
249
250   private:
251     Instruction *visitCallSite(CallSite CS);
252     bool transformConstExprCastCall(CallSite CS);
253     Instruction *transformCallThroughTrampoline(CallSite CS);
254     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
255                                    bool DoXform = true);
256     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
257     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
258
259
260   public:
261     // InsertNewInstBefore - insert an instruction New before instruction Old
262     // in the program.  Add the new instruction to the worklist.
263     //
264     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
265       assert(New && New->getParent() == 0 &&
266              "New instruction already inserted into a basic block!");
267       BasicBlock *BB = Old.getParent();
268       BB->getInstList().insert(&Old, New);  // Insert inst
269       AddToWorkList(New);
270       return New;
271     }
272
273     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
274     /// This also adds the cast to the worklist.  Finally, this returns the
275     /// cast.
276     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
277                             Instruction &Pos) {
278       if (V->getType() == Ty) return V;
279
280       if (Constant *CV = dyn_cast<Constant>(V))
281         return ConstantExpr::getCast(opc, CV, Ty);
282       
283       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
284       AddToWorkList(C);
285       return C;
286     }
287         
288     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
289       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
290     }
291
292
293     // ReplaceInstUsesWith - This method is to be used when an instruction is
294     // found to be dead, replacable with another preexisting expression.  Here
295     // we add all uses of I to the worklist, replace all uses of I with the new
296     // value, then return I, so that the inst combiner will know that I was
297     // modified.
298     //
299     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
300       AddUsersToWorkList(I);         // Add all modified instrs to worklist
301       if (&I != V) {
302         I.replaceAllUsesWith(V);
303         return &I;
304       } else {
305         // If we are replacing the instruction with itself, this must be in a
306         // segment of unreachable code, so just clobber the instruction.
307         I.replaceAllUsesWith(UndefValue::get(I.getType()));
308         return &I;
309       }
310     }
311
312     // EraseInstFromFunction - When dealing with an instruction that has side
313     // effects or produces a void value, we can't rely on DCE to delete the
314     // instruction.  Instead, visit methods should return the value returned by
315     // this function.
316     Instruction *EraseInstFromFunction(Instruction &I) {
317       assert(I.use_empty() && "Cannot erase instruction that is used!");
318       AddUsesToWorkList(I);
319       RemoveFromWorkList(&I);
320       I.eraseFromParent();
321       return 0;  // Don't do anything with FI
322     }
323         
324     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
325                            APInt &KnownOne, unsigned Depth = 0) const {
326       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
327     }
328     
329     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
330                            unsigned Depth = 0) const {
331       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
332     }
333     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
334       return llvm::ComputeNumSignBits(Op, TD, Depth);
335     }
336
337   private:
338
339     /// SimplifyCommutative - This performs a few simplifications for 
340     /// commutative operators.
341     bool SimplifyCommutative(BinaryOperator &I);
342
343     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
344     /// most-complex to least-complex order.
345     bool SimplifyCompare(CmpInst &I);
346
347     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
348     /// based on the demanded bits.
349     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
350                                    APInt& KnownZero, APInt& KnownOne,
351                                    unsigned Depth);
352     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
353                               APInt& KnownZero, APInt& KnownOne,
354                               unsigned Depth=0);
355         
356     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
357     /// SimplifyDemandedBits knows about.  See if the instruction has any
358     /// properties that allow us to simplify its operands.
359     bool SimplifyDemandedInstructionBits(Instruction &Inst);
360         
361     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
362                                       APInt& UndefElts, unsigned Depth = 0);
363       
364     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
365     // PHI node as operand #0, see if we can fold the instruction into the PHI
366     // (which is only possible if all operands to the PHI are constants).
367     Instruction *FoldOpIntoPhi(Instruction &I);
368
369     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
370     // operator and they all are only used by the PHI, PHI together their
371     // inputs, and do the operation once, to the result of the PHI.
372     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
373     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
374     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
375
376     
377     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
378                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
379     
380     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
381                               bool isSub, Instruction &I);
382     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
383                                  bool isSigned, bool Inside, Instruction &IB);
384     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
385     Instruction *MatchBSwap(BinaryOperator &I);
386     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
387     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
388     Instruction *SimplifyMemSet(MemSetInst *MI);
389
390
391     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
392
393     bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
394                                     unsigned CastOpc, int &NumCastsRemoved);
395     unsigned GetOrEnforceKnownAlignment(Value *V,
396                                         unsigned PrefAlign = 0);
397
398   };
399 }
400
401 char InstCombiner::ID = 0;
402 static RegisterPass<InstCombiner>
403 X("instcombine", "Combine redundant instructions");
404
405 // getComplexity:  Assign a complexity or rank value to LLVM Values...
406 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
407 static unsigned getComplexity(Value *V) {
408   if (isa<Instruction>(V)) {
409     if (BinaryOperator::isNeg(V) || BinaryOperator::isFNeg(V) ||
410         BinaryOperator::isNot(V))
411       return 3;
412     return 4;
413   }
414   if (isa<Argument>(V)) return 3;
415   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
416 }
417
418 // isOnlyUse - Return true if this instruction will be deleted if we stop using
419 // it.
420 static bool isOnlyUse(Value *V) {
421   return V->hasOneUse() || isa<Constant>(V);
422 }
423
424 // getPromotedType - Return the specified type promoted as it would be to pass
425 // though a va_arg area...
426 static const Type *getPromotedType(const Type *Ty) {
427   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
428     if (ITy->getBitWidth() < 32)
429       return Type::Int32Ty;
430   }
431   return Ty;
432 }
433
434 /// getBitCastOperand - If the specified operand is a CastInst, a constant
435 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
436 /// operand value, otherwise return null.
437 static Value *getBitCastOperand(Value *V) {
438   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
439     // BitCastInst?
440     return I->getOperand(0);
441   else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
442     // GetElementPtrInst?
443     if (GEP->hasAllZeroIndices())
444       return GEP->getOperand(0);
445   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
446     if (CE->getOpcode() == Instruction::BitCast)
447       // BitCast ConstantExp?
448       return CE->getOperand(0);
449     else if (CE->getOpcode() == Instruction::GetElementPtr) {
450       // GetElementPtr ConstantExp?
451       for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
452            I != E; ++I) {
453         ConstantInt *CI = dyn_cast<ConstantInt>(I);
454         if (!CI || !CI->isZero())
455           // Any non-zero indices? Not cast-like.
456           return 0;
457       }
458       // All-zero indices? This is just like casting.
459       return CE->getOperand(0);
460     }
461   }
462   return 0;
463 }
464
465 /// This function is a wrapper around CastInst::isEliminableCastPair. It
466 /// simply extracts arguments and returns what that function returns.
467 static Instruction::CastOps 
468 isEliminableCastPair(
469   const CastInst *CI, ///< The first cast instruction
470   unsigned opcode,       ///< The opcode of the second cast instruction
471   const Type *DstTy,     ///< The target type for the second cast instruction
472   TargetData *TD         ///< The target data for pointer size
473 ) {
474   
475   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
476   const Type *MidTy = CI->getType();                  // B from above
477
478   // Get the opcodes of the two Cast instructions
479   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
480   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
481
482   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
483                                                 DstTy, TD->getIntPtrType());
484   
485   // We don't want to form an inttoptr or ptrtoint that converts to an integer
486   // type that differs from the pointer size.
487   if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
488       (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
489     Res = 0;
490   
491   return Instruction::CastOps(Res);
492 }
493
494 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
495 /// in any code being generated.  It does not require codegen if V is simple
496 /// enough or if the cast can be folded into other casts.
497 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
498                               const Type *Ty, TargetData *TD) {
499   if (V->getType() == Ty || isa<Constant>(V)) return false;
500   
501   // If this is another cast that can be eliminated, it isn't codegen either.
502   if (const CastInst *CI = dyn_cast<CastInst>(V))
503     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
504       return false;
505   return true;
506 }
507
508 // SimplifyCommutative - This performs a few simplifications for commutative
509 // operators:
510 //
511 //  1. Order operands such that they are listed from right (least complex) to
512 //     left (most complex).  This puts constants before unary operators before
513 //     binary operators.
514 //
515 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
516 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
517 //
518 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
519   bool Changed = false;
520   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
521     Changed = !I.swapOperands();
522
523   if (!I.isAssociative()) return Changed;
524   Instruction::BinaryOps Opcode = I.getOpcode();
525   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
526     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
527       if (isa<Constant>(I.getOperand(1))) {
528         Constant *Folded = ConstantExpr::get(I.getOpcode(),
529                                              cast<Constant>(I.getOperand(1)),
530                                              cast<Constant>(Op->getOperand(1)));
531         I.setOperand(0, Op->getOperand(0));
532         I.setOperand(1, Folded);
533         return true;
534       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
535         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
536             isOnlyUse(Op) && isOnlyUse(Op1)) {
537           Constant *C1 = cast<Constant>(Op->getOperand(1));
538           Constant *C2 = cast<Constant>(Op1->getOperand(1));
539
540           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
541           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
542           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
543                                                     Op1->getOperand(0),
544                                                     Op1->getName(), &I);
545           AddToWorkList(New);
546           I.setOperand(0, New);
547           I.setOperand(1, Folded);
548           return true;
549         }
550     }
551   return Changed;
552 }
553
554 /// SimplifyCompare - For a CmpInst this function just orders the operands
555 /// so that theyare listed from right (least complex) to left (most complex).
556 /// This puts constants before unary operators before binary operators.
557 bool InstCombiner::SimplifyCompare(CmpInst &I) {
558   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
559     return false;
560   I.swapOperands();
561   // Compare instructions are not associative so there's nothing else we can do.
562   return true;
563 }
564
565 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
566 // if the LHS is a constant zero (which is the 'negate' form).
567 //
568 static inline Value *dyn_castNegVal(Value *V) {
569   if (BinaryOperator::isNeg(V))
570     return BinaryOperator::getNegArgument(V);
571
572   // Constants can be considered to be negated values if they can be folded.
573   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
574     return ConstantExpr::getNeg(C);
575
576   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
577     if (C->getType()->getElementType()->isInteger())
578       return ConstantExpr::getNeg(C);
579
580   return 0;
581 }
582
583 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
584 // instruction if the LHS is a constant negative zero (which is the 'negate'
585 // form).
586 //
587 static inline Value *dyn_castFNegVal(Value *V) {
588   if (BinaryOperator::isFNeg(V))
589     return BinaryOperator::getFNegArgument(V);
590
591   // Constants can be considered to be negated values if they can be folded.
592   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
593     return ConstantExpr::getFNeg(C);
594
595   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
596     if (C->getType()->getElementType()->isFloatingPoint())
597       return ConstantExpr::getFNeg(C);
598
599   return 0;
600 }
601
602 static inline Value *dyn_castNotVal(Value *V) {
603   if (BinaryOperator::isNot(V))
604     return BinaryOperator::getNotArgument(V);
605
606   // Constants can be considered to be not'ed values...
607   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
608     return ConstantInt::get(~C->getValue());
609   return 0;
610 }
611
612 // dyn_castFoldableMul - If this value is a multiply that can be folded into
613 // other computations (because it has a constant operand), return the
614 // non-constant operand of the multiply, and set CST to point to the multiplier.
615 // Otherwise, return null.
616 //
617 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
618   if (V->hasOneUse() && V->getType()->isInteger())
619     if (Instruction *I = dyn_cast<Instruction>(V)) {
620       if (I->getOpcode() == Instruction::Mul)
621         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
622           return I->getOperand(0);
623       if (I->getOpcode() == Instruction::Shl)
624         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
625           // The multiplier is really 1 << CST.
626           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
627           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
628           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
629           return I->getOperand(0);
630         }
631     }
632   return 0;
633 }
634
635 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
636 /// expression, return it.
637 static User *dyn_castGetElementPtr(Value *V) {
638   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
639   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
640     if (CE->getOpcode() == Instruction::GetElementPtr)
641       return cast<User>(V);
642   return false;
643 }
644
645 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
646 /// opcode value. Otherwise return UserOp1.
647 static unsigned getOpcode(const Value *V) {
648   if (const Instruction *I = dyn_cast<Instruction>(V))
649     return I->getOpcode();
650   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
651     return CE->getOpcode();
652   // Use UserOp1 to mean there's no opcode.
653   return Instruction::UserOp1;
654 }
655
656 /// AddOne - Add one to a ConstantInt
657 static ConstantInt *AddOne(ConstantInt *C) {
658   APInt Val(C->getValue());
659   return ConstantInt::get(++Val);
660 }
661 /// SubOne - Subtract one from a ConstantInt
662 static ConstantInt *SubOne(ConstantInt *C) {
663   APInt Val(C->getValue());
664   return ConstantInt::get(--Val);
665 }
666 /// Add - Add two ConstantInts together
667 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
668   return ConstantInt::get(C1->getValue() + C2->getValue());
669 }
670 /// And - Bitwise AND two ConstantInts together
671 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
672   return ConstantInt::get(C1->getValue() & C2->getValue());
673 }
674 /// Subtract - Subtract one ConstantInt from another
675 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
676   return ConstantInt::get(C1->getValue() - C2->getValue());
677 }
678 /// Multiply - Multiply two ConstantInts together
679 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
680   return ConstantInt::get(C1->getValue() * C2->getValue());
681 }
682 /// MultiplyOverflows - True if the multiply can not be expressed in an int
683 /// this size.
684 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
685   uint32_t W = C1->getBitWidth();
686   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
687   if (sign) {
688     LHSExt.sext(W * 2);
689     RHSExt.sext(W * 2);
690   } else {
691     LHSExt.zext(W * 2);
692     RHSExt.zext(W * 2);
693   }
694
695   APInt MulExt = LHSExt * RHSExt;
696
697   if (sign) {
698     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
699     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
700     return MulExt.slt(Min) || MulExt.sgt(Max);
701   } else 
702     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
703 }
704
705
706 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
707 /// specified instruction is a constant integer.  If so, check to see if there
708 /// are any bits set in the constant that are not demanded.  If so, shrink the
709 /// constant and return true.
710 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
711                                    APInt Demanded) {
712   assert(I && "No instruction?");
713   assert(OpNo < I->getNumOperands() && "Operand index too large");
714
715   // If the operand is not a constant integer, nothing to do.
716   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
717   if (!OpC) return false;
718
719   // If there are no bits set that aren't demanded, nothing to do.
720   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
721   if ((~Demanded & OpC->getValue()) == 0)
722     return false;
723
724   // This instruction is producing bits that are not demanded. Shrink the RHS.
725   Demanded &= OpC->getValue();
726   I->setOperand(OpNo, ConstantInt::get(Demanded));
727   return true;
728 }
729
730 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
731 // set of known zero and one bits, compute the maximum and minimum values that
732 // could have the specified known zero and known one bits, returning them in
733 // min/max.
734 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
735                                                    const APInt& KnownOne,
736                                                    APInt& Min, APInt& Max) {
737   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
738          KnownZero.getBitWidth() == Min.getBitWidth() &&
739          KnownZero.getBitWidth() == Max.getBitWidth() &&
740          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
741   APInt UnknownBits = ~(KnownZero|KnownOne);
742
743   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
744   // bit if it is unknown.
745   Min = KnownOne;
746   Max = KnownOne|UnknownBits;
747   
748   if (UnknownBits.isNegative()) { // Sign bit is unknown
749     Min.set(Min.getBitWidth()-1);
750     Max.clear(Max.getBitWidth()-1);
751   }
752 }
753
754 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
755 // a set of known zero and one bits, compute the maximum and minimum values that
756 // could have the specified known zero and known one bits, returning them in
757 // min/max.
758 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
759                                                      const APInt &KnownOne,
760                                                      APInt &Min, APInt &Max) {
761   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
762          KnownZero.getBitWidth() == Min.getBitWidth() &&
763          KnownZero.getBitWidth() == Max.getBitWidth() &&
764          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
765   APInt UnknownBits = ~(KnownZero|KnownOne);
766   
767   // The minimum value is when the unknown bits are all zeros.
768   Min = KnownOne;
769   // The maximum value is when the unknown bits are all ones.
770   Max = KnownOne|UnknownBits;
771 }
772
773 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
774 /// SimplifyDemandedBits knows about.  See if the instruction has any
775 /// properties that allow us to simplify its operands.
776 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
777   unsigned BitWidth = cast<IntegerType>(Inst.getType())->getBitWidth();
778   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
779   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
780   
781   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
782                                      KnownZero, KnownOne, 0);
783   if (V == 0) return false;
784   if (V == &Inst) return true;
785   ReplaceInstUsesWith(Inst, V);
786   return true;
787 }
788
789 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
790 /// specified instruction operand if possible, updating it in place.  It returns
791 /// true if it made any change and false otherwise.
792 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
793                                         APInt &KnownZero, APInt &KnownOne,
794                                         unsigned Depth) {
795   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
796                                           KnownZero, KnownOne, Depth);
797   if (NewVal == 0) return false;
798   U.set(NewVal);
799   return true;
800 }
801
802
803 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
804 /// value based on the demanded bits.  When this function is called, it is known
805 /// that only the bits set in DemandedMask of the result of V are ever used
806 /// downstream. Consequently, depending on the mask and V, it may be possible
807 /// to replace V with a constant or one of its operands. In such cases, this
808 /// function does the replacement and returns true. In all other cases, it
809 /// returns false after analyzing the expression and setting KnownOne and known
810 /// to be one in the expression.  KnownZero contains all the bits that are known
811 /// to be zero in the expression. These are provided to potentially allow the
812 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
813 /// the expression. KnownOne and KnownZero always follow the invariant that 
814 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
815 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
816 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
817 /// and KnownOne must all be the same.
818 ///
819 /// This returns null if it did not change anything and it permits no
820 /// simplification.  This returns V itself if it did some simplification of V's
821 /// operands based on the information about what bits are demanded. This returns
822 /// some other non-null value if it found out that V is equal to another value
823 /// in the context where the specified bits are demanded, but not for all users.
824 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
825                                              APInt &KnownZero, APInt &KnownOne,
826                                              unsigned Depth) {
827   assert(V != 0 && "Null pointer of Value???");
828   assert(Depth <= 6 && "Limit Search Depth");
829   uint32_t BitWidth = DemandedMask.getBitWidth();
830   const Type *VTy = V->getType();
831   assert((TD || !isa<PointerType>(VTy)) &&
832          "SimplifyDemandedBits needs to know bit widths!");
833   assert((!TD || TD->getTypeSizeInBits(VTy) == BitWidth) &&
834          (!isa<IntegerType>(VTy) ||
835           VTy->getPrimitiveSizeInBits() == BitWidth) &&
836          KnownZero.getBitWidth() == BitWidth &&
837          KnownOne.getBitWidth() == BitWidth &&
838          "Value *V, DemandedMask, KnownZero and KnownOne \
839           must have same BitWidth");
840   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
841     // We know all of the bits for a constant!
842     KnownOne = CI->getValue() & DemandedMask;
843     KnownZero = ~KnownOne & DemandedMask;
844     return 0;
845   }
846   if (isa<ConstantPointerNull>(V)) {
847     // We know all of the bits for a constant!
848     KnownOne.clear();
849     KnownZero = DemandedMask;
850     return 0;
851   }
852
853   KnownZero.clear();
854   KnownOne.clear();
855   if (DemandedMask == 0) {   // Not demanding any bits from V.
856     if (isa<UndefValue>(V))
857       return 0;
858     return UndefValue::get(VTy);
859   }
860   
861   if (Depth == 6)        // Limit search depth.
862     return 0;
863   
864   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
865   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
866
867   Instruction *I = dyn_cast<Instruction>(V);
868   if (!I) {
869     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
870     return 0;        // Only analyze instructions.
871   }
872
873   // If there are multiple uses of this value and we aren't at the root, then
874   // we can't do any simplifications of the operands, because DemandedMask
875   // only reflects the bits demanded by *one* of the users.
876   if (Depth != 0 && !I->hasOneUse()) {
877     // Despite the fact that we can't simplify this instruction in all User's
878     // context, we can at least compute the knownzero/knownone bits, and we can
879     // do simplifications that apply to *just* the one user if we know that
880     // this instruction has a simpler value in that context.
881     if (I->getOpcode() == Instruction::And) {
882       // If either the LHS or the RHS are Zero, the result is zero.
883       ComputeMaskedBits(I->getOperand(1), DemandedMask,
884                         RHSKnownZero, RHSKnownOne, Depth+1);
885       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
886                         LHSKnownZero, LHSKnownOne, Depth+1);
887       
888       // If all of the demanded bits are known 1 on one side, return the other.
889       // These bits cannot contribute to the result of the 'and' in this
890       // context.
891       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
892           (DemandedMask & ~LHSKnownZero))
893         return I->getOperand(0);
894       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
895           (DemandedMask & ~RHSKnownZero))
896         return I->getOperand(1);
897       
898       // If all of the demanded bits in the inputs are known zeros, return zero.
899       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
900         return Constant::getNullValue(VTy);
901       
902     } else if (I->getOpcode() == Instruction::Or) {
903       // We can simplify (X|Y) -> X or Y in the user's context if we know that
904       // only bits from X or Y are demanded.
905       
906       // If either the LHS or the RHS are One, the result is One.
907       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
908                         RHSKnownZero, RHSKnownOne, Depth+1);
909       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
910                         LHSKnownZero, LHSKnownOne, Depth+1);
911       
912       // If all of the demanded bits are known zero on one side, return the
913       // other.  These bits cannot contribute to the result of the 'or' in this
914       // context.
915       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
916           (DemandedMask & ~LHSKnownOne))
917         return I->getOperand(0);
918       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
919           (DemandedMask & ~RHSKnownOne))
920         return I->getOperand(1);
921       
922       // If all of the potentially set bits on one side are known to be set on
923       // the other side, just use the 'other' side.
924       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
925           (DemandedMask & (~RHSKnownZero)))
926         return I->getOperand(0);
927       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
928           (DemandedMask & (~LHSKnownZero)))
929         return I->getOperand(1);
930     }
931     
932     // Compute the KnownZero/KnownOne bits to simplify things downstream.
933     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
934     return 0;
935   }
936   
937   // If this is the root being simplified, allow it to have multiple uses,
938   // just set the DemandedMask to all bits so that we can try to simplify the
939   // operands.  This allows visitTruncInst (for example) to simplify the
940   // operand of a trunc without duplicating all the logic below.
941   if (Depth == 0 && !V->hasOneUse())
942     DemandedMask = APInt::getAllOnesValue(BitWidth);
943   
944   switch (I->getOpcode()) {
945   default:
946     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
947     break;
948   case Instruction::And:
949     // If either the LHS or the RHS are Zero, the result is zero.
950     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
951                              RHSKnownZero, RHSKnownOne, Depth+1) ||
952         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
953                              LHSKnownZero, LHSKnownOne, Depth+1))
954       return I;
955     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
956     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
957
958     // If all of the demanded bits are known 1 on one side, return the other.
959     // These bits cannot contribute to the result of the 'and'.
960     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
961         (DemandedMask & ~LHSKnownZero))
962       return I->getOperand(0);
963     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
964         (DemandedMask & ~RHSKnownZero))
965       return I->getOperand(1);
966     
967     // If all of the demanded bits in the inputs are known zeros, return zero.
968     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
969       return Constant::getNullValue(VTy);
970       
971     // If the RHS is a constant, see if we can simplify it.
972     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
973       return I;
974       
975     // Output known-1 bits are only known if set in both the LHS & RHS.
976     RHSKnownOne &= LHSKnownOne;
977     // Output known-0 are known to be clear if zero in either the LHS | RHS.
978     RHSKnownZero |= LHSKnownZero;
979     break;
980   case Instruction::Or:
981     // If either the LHS or the RHS are One, the result is One.
982     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
983                              RHSKnownZero, RHSKnownOne, Depth+1) ||
984         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
985                              LHSKnownZero, LHSKnownOne, Depth+1))
986       return I;
987     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
988     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
989     
990     // If all of the demanded bits are known zero on one side, return the other.
991     // These bits cannot contribute to the result of the 'or'.
992     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
993         (DemandedMask & ~LHSKnownOne))
994       return I->getOperand(0);
995     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
996         (DemandedMask & ~RHSKnownOne))
997       return I->getOperand(1);
998
999     // If all of the potentially set bits on one side are known to be set on
1000     // the other side, just use the 'other' side.
1001     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
1002         (DemandedMask & (~RHSKnownZero)))
1003       return I->getOperand(0);
1004     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
1005         (DemandedMask & (~LHSKnownZero)))
1006       return I->getOperand(1);
1007         
1008     // If the RHS is a constant, see if we can simplify it.
1009     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1010       return I;
1011           
1012     // Output known-0 bits are only known if clear in both the LHS & RHS.
1013     RHSKnownZero &= LHSKnownZero;
1014     // Output known-1 are known to be set if set in either the LHS | RHS.
1015     RHSKnownOne |= LHSKnownOne;
1016     break;
1017   case Instruction::Xor: {
1018     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1019                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1020         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1021                              LHSKnownZero, LHSKnownOne, Depth+1))
1022       return I;
1023     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1024     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1025     
1026     // If all of the demanded bits are known zero on one side, return the other.
1027     // These bits cannot contribute to the result of the 'xor'.
1028     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1029       return I->getOperand(0);
1030     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1031       return I->getOperand(1);
1032     
1033     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1034     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1035                          (RHSKnownOne & LHSKnownOne);
1036     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1037     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1038                         (RHSKnownOne & LHSKnownZero);
1039     
1040     // If all of the demanded bits are known to be zero on one side or the
1041     // other, turn this into an *inclusive* or.
1042     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1043     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1044       Instruction *Or =
1045         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1046                                  I->getName());
1047       return InsertNewInstBefore(Or, *I);
1048     }
1049     
1050     // If all of the demanded bits on one side are known, and all of the set
1051     // bits on that side are also known to be set on the other side, turn this
1052     // into an AND, as we know the bits will be cleared.
1053     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1054     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1055       // all known
1056       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1057         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1058         Instruction *And = 
1059           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1060         return InsertNewInstBefore(And, *I);
1061       }
1062     }
1063     
1064     // If the RHS is a constant, see if we can simplify it.
1065     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1066     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1067       return I;
1068     
1069     RHSKnownZero = KnownZeroOut;
1070     RHSKnownOne  = KnownOneOut;
1071     break;
1072   }
1073   case Instruction::Select:
1074     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1075                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1076         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1077                              LHSKnownZero, LHSKnownOne, Depth+1))
1078       return I;
1079     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1080     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1081     
1082     // If the operands are constants, see if we can simplify them.
1083     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1084         ShrinkDemandedConstant(I, 2, DemandedMask))
1085       return I;
1086     
1087     // Only known if known in both the LHS and RHS.
1088     RHSKnownOne &= LHSKnownOne;
1089     RHSKnownZero &= LHSKnownZero;
1090     break;
1091   case Instruction::Trunc: {
1092     unsigned truncBf = I->getOperand(0)->getType()->getPrimitiveSizeInBits();
1093     DemandedMask.zext(truncBf);
1094     RHSKnownZero.zext(truncBf);
1095     RHSKnownOne.zext(truncBf);
1096     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1097                              RHSKnownZero, RHSKnownOne, Depth+1))
1098       return I;
1099     DemandedMask.trunc(BitWidth);
1100     RHSKnownZero.trunc(BitWidth);
1101     RHSKnownOne.trunc(BitWidth);
1102     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1103     break;
1104   }
1105   case Instruction::BitCast:
1106     if (!I->getOperand(0)->getType()->isInteger())
1107       return false;  // vector->int or fp->int?
1108     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1109                              RHSKnownZero, RHSKnownOne, Depth+1))
1110       return I;
1111     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1112     break;
1113   case Instruction::ZExt: {
1114     // Compute the bits in the result that are not present in the input.
1115     unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
1116     
1117     DemandedMask.trunc(SrcBitWidth);
1118     RHSKnownZero.trunc(SrcBitWidth);
1119     RHSKnownOne.trunc(SrcBitWidth);
1120     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1121                              RHSKnownZero, RHSKnownOne, Depth+1))
1122       return I;
1123     DemandedMask.zext(BitWidth);
1124     RHSKnownZero.zext(BitWidth);
1125     RHSKnownOne.zext(BitWidth);
1126     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1127     // The top bits are known to be zero.
1128     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1129     break;
1130   }
1131   case Instruction::SExt: {
1132     // Compute the bits in the result that are not present in the input.
1133     unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
1134     
1135     APInt InputDemandedBits = DemandedMask & 
1136                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1137
1138     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1139     // If any of the sign extended bits are demanded, we know that the sign
1140     // bit is demanded.
1141     if ((NewBits & DemandedMask) != 0)
1142       InputDemandedBits.set(SrcBitWidth-1);
1143       
1144     InputDemandedBits.trunc(SrcBitWidth);
1145     RHSKnownZero.trunc(SrcBitWidth);
1146     RHSKnownOne.trunc(SrcBitWidth);
1147     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1148                              RHSKnownZero, RHSKnownOne, Depth+1))
1149       return I;
1150     InputDemandedBits.zext(BitWidth);
1151     RHSKnownZero.zext(BitWidth);
1152     RHSKnownOne.zext(BitWidth);
1153     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1154       
1155     // If the sign bit of the input is known set or clear, then we know the
1156     // top bits of the result.
1157
1158     // If the input sign bit is known zero, or if the NewBits are not demanded
1159     // convert this into a zero extension.
1160     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1161       // Convert to ZExt cast
1162       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1163       return InsertNewInstBefore(NewCast, *I);
1164     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1165       RHSKnownOne |= NewBits;
1166     }
1167     break;
1168   }
1169   case Instruction::Add: {
1170     // Figure out what the input bits are.  If the top bits of the and result
1171     // are not demanded, then the add doesn't demand them from its input
1172     // either.
1173     unsigned NLZ = DemandedMask.countLeadingZeros();
1174       
1175     // If there is a constant on the RHS, there are a variety of xformations
1176     // we can do.
1177     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1178       // If null, this should be simplified elsewhere.  Some of the xforms here
1179       // won't work if the RHS is zero.
1180       if (RHS->isZero())
1181         break;
1182       
1183       // If the top bit of the output is demanded, demand everything from the
1184       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1185       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1186
1187       // Find information about known zero/one bits in the input.
1188       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1189                                LHSKnownZero, LHSKnownOne, Depth+1))
1190         return I;
1191
1192       // If the RHS of the add has bits set that can't affect the input, reduce
1193       // the constant.
1194       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1195         return I;
1196       
1197       // Avoid excess work.
1198       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1199         break;
1200       
1201       // Turn it into OR if input bits are zero.
1202       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1203         Instruction *Or =
1204           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1205                                    I->getName());
1206         return InsertNewInstBefore(Or, *I);
1207       }
1208       
1209       // We can say something about the output known-zero and known-one bits,
1210       // depending on potential carries from the input constant and the
1211       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1212       // bits set and the RHS constant is 0x01001, then we know we have a known
1213       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1214       
1215       // To compute this, we first compute the potential carry bits.  These are
1216       // the bits which may be modified.  I'm not aware of a better way to do
1217       // this scan.
1218       const APInt &RHSVal = RHS->getValue();
1219       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1220       
1221       // Now that we know which bits have carries, compute the known-1/0 sets.
1222       
1223       // Bits are known one if they are known zero in one operand and one in the
1224       // other, and there is no input carry.
1225       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1226                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1227       
1228       // Bits are known zero if they are known zero in both operands and there
1229       // is no input carry.
1230       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1231     } else {
1232       // If the high-bits of this ADD are not demanded, then it does not demand
1233       // the high bits of its LHS or RHS.
1234       if (DemandedMask[BitWidth-1] == 0) {
1235         // Right fill the mask of bits for this ADD to demand the most
1236         // significant bit and all those below it.
1237         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1238         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1239                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1240             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1241                                  LHSKnownZero, LHSKnownOne, Depth+1))
1242           return I;
1243       }
1244     }
1245     break;
1246   }
1247   case Instruction::Sub:
1248     // If the high-bits of this SUB are not demanded, then it does not demand
1249     // the high bits of its LHS or RHS.
1250     if (DemandedMask[BitWidth-1] == 0) {
1251       // Right fill the mask of bits for this SUB to demand the most
1252       // significant bit and all those below it.
1253       uint32_t NLZ = DemandedMask.countLeadingZeros();
1254       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1255       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1256                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1257           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1258                                LHSKnownZero, LHSKnownOne, Depth+1))
1259         return I;
1260     }
1261     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1262     // the known zeros and ones.
1263     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1264     break;
1265   case Instruction::Shl:
1266     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1267       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1268       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1269       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1270                                RHSKnownZero, RHSKnownOne, Depth+1))
1271         return I;
1272       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1273       RHSKnownZero <<= ShiftAmt;
1274       RHSKnownOne  <<= ShiftAmt;
1275       // low bits known zero.
1276       if (ShiftAmt)
1277         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1278     }
1279     break;
1280   case Instruction::LShr:
1281     // For a logical shift right
1282     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1283       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1284       
1285       // Unsigned shift right.
1286       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1287       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1288                                RHSKnownZero, RHSKnownOne, Depth+1))
1289         return I;
1290       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1291       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1292       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1293       if (ShiftAmt) {
1294         // Compute the new bits that are at the top now.
1295         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1296         RHSKnownZero |= HighBits;  // high bits known zero.
1297       }
1298     }
1299     break;
1300   case Instruction::AShr:
1301     // If this is an arithmetic shift right and only the low-bit is set, we can
1302     // always convert this into a logical shr, even if the shift amount is
1303     // variable.  The low bit of the shift cannot be an input sign bit unless
1304     // the shift amount is >= the size of the datatype, which is undefined.
1305     if (DemandedMask == 1) {
1306       // Perform the logical shift right.
1307       Instruction *NewVal = BinaryOperator::CreateLShr(
1308                         I->getOperand(0), I->getOperand(1), I->getName());
1309       return InsertNewInstBefore(NewVal, *I);
1310     }    
1311
1312     // If the sign bit is the only bit demanded by this ashr, then there is no
1313     // need to do it, the shift doesn't change the high bit.
1314     if (DemandedMask.isSignBit())
1315       return I->getOperand(0);
1316     
1317     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1318       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1319       
1320       // Signed shift right.
1321       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1322       // If any of the "high bits" are demanded, we should set the sign bit as
1323       // demanded.
1324       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1325         DemandedMaskIn.set(BitWidth-1);
1326       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1327                                RHSKnownZero, RHSKnownOne, Depth+1))
1328         return I;
1329       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1330       // Compute the new bits that are at the top now.
1331       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1332       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1333       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1334         
1335       // Handle the sign bits.
1336       APInt SignBit(APInt::getSignBit(BitWidth));
1337       // Adjust to where it is now in the mask.
1338       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1339         
1340       // If the input sign bit is known to be zero, or if none of the top bits
1341       // are demanded, turn this into an unsigned shift right.
1342       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1343           (HighBits & ~DemandedMask) == HighBits) {
1344         // Perform the logical shift right.
1345         Instruction *NewVal = BinaryOperator::CreateLShr(
1346                           I->getOperand(0), SA, I->getName());
1347         return InsertNewInstBefore(NewVal, *I);
1348       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1349         RHSKnownOne |= HighBits;
1350       }
1351     }
1352     break;
1353   case Instruction::SRem:
1354     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1355       APInt RA = Rem->getValue().abs();
1356       if (RA.isPowerOf2()) {
1357         if (DemandedMask.ule(RA))    // srem won't affect demanded bits
1358           return I->getOperand(0);
1359
1360         APInt LowBits = RA - 1;
1361         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1362         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1363                                  LHSKnownZero, LHSKnownOne, Depth+1))
1364           return I;
1365
1366         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1367           LHSKnownZero |= ~LowBits;
1368
1369         KnownZero |= LHSKnownZero & DemandedMask;
1370
1371         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1372       }
1373     }
1374     break;
1375   case Instruction::URem: {
1376     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1377     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1378     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1379                              KnownZero2, KnownOne2, Depth+1) ||
1380         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1381                              KnownZero2, KnownOne2, Depth+1))
1382       return I;
1383
1384     unsigned Leaders = KnownZero2.countLeadingOnes();
1385     Leaders = std::max(Leaders,
1386                        KnownZero2.countLeadingOnes());
1387     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1388     break;
1389   }
1390   case Instruction::Call:
1391     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1392       switch (II->getIntrinsicID()) {
1393       default: break;
1394       case Intrinsic::bswap: {
1395         // If the only bits demanded come from one byte of the bswap result,
1396         // just shift the input byte into position to eliminate the bswap.
1397         unsigned NLZ = DemandedMask.countLeadingZeros();
1398         unsigned NTZ = DemandedMask.countTrailingZeros();
1399           
1400         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1401         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1402         // have 14 leading zeros, round to 8.
1403         NLZ &= ~7;
1404         NTZ &= ~7;
1405         // If we need exactly one byte, we can do this transformation.
1406         if (BitWidth-NLZ-NTZ == 8) {
1407           unsigned ResultBit = NTZ;
1408           unsigned InputBit = BitWidth-NTZ-8;
1409           
1410           // Replace this with either a left or right shift to get the byte into
1411           // the right place.
1412           Instruction *NewVal;
1413           if (InputBit > ResultBit)
1414             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1415                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1416           else
1417             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1418                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1419           NewVal->takeName(I);
1420           return InsertNewInstBefore(NewVal, *I);
1421         }
1422           
1423         // TODO: Could compute known zero/one bits based on the input.
1424         break;
1425       }
1426       }
1427     }
1428     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1429     break;
1430   }
1431   
1432   // If the client is only demanding bits that we know, return the known
1433   // constant.
1434   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1435     Constant *C = ConstantInt::get(RHSKnownOne);
1436     if (isa<PointerType>(V->getType()))
1437       C = ConstantExpr::getIntToPtr(C, V->getType());
1438     return C;
1439   }
1440   return false;
1441 }
1442
1443
1444 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1445 /// any number of elements. DemandedElts contains the set of elements that are
1446 /// actually used by the caller.  This method analyzes which elements of the
1447 /// operand are undef and returns that information in UndefElts.
1448 ///
1449 /// If the information about demanded elements can be used to simplify the
1450 /// operation, the operation is simplified, then the resultant value is
1451 /// returned.  This returns null if no change was made.
1452 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1453                                                 APInt& UndefElts,
1454                                                 unsigned Depth) {
1455   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1456   APInt EltMask(APInt::getAllOnesValue(VWidth));
1457   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1458
1459   if (isa<UndefValue>(V)) {
1460     // If the entire vector is undefined, just return this info.
1461     UndefElts = EltMask;
1462     return 0;
1463   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1464     UndefElts = EltMask;
1465     return UndefValue::get(V->getType());
1466   }
1467
1468   UndefElts = 0;
1469   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1470     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1471     Constant *Undef = UndefValue::get(EltTy);
1472
1473     std::vector<Constant*> Elts;
1474     for (unsigned i = 0; i != VWidth; ++i)
1475       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1476         Elts.push_back(Undef);
1477         UndefElts.set(i);
1478       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1479         Elts.push_back(Undef);
1480         UndefElts.set(i);
1481       } else {                               // Otherwise, defined.
1482         Elts.push_back(CP->getOperand(i));
1483       }
1484
1485     // If we changed the constant, return it.
1486     Constant *NewCP = ConstantVector::get(Elts);
1487     return NewCP != CP ? NewCP : 0;
1488   } else if (isa<ConstantAggregateZero>(V)) {
1489     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1490     // set to undef.
1491     
1492     // Check if this is identity. If so, return 0 since we are not simplifying
1493     // anything.
1494     if (DemandedElts == ((1ULL << VWidth) -1))
1495       return 0;
1496     
1497     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1498     Constant *Zero = Constant::getNullValue(EltTy);
1499     Constant *Undef = UndefValue::get(EltTy);
1500     std::vector<Constant*> Elts;
1501     for (unsigned i = 0; i != VWidth; ++i) {
1502       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1503       Elts.push_back(Elt);
1504     }
1505     UndefElts = DemandedElts ^ EltMask;
1506     return ConstantVector::get(Elts);
1507   }
1508   
1509   // Limit search depth.
1510   if (Depth == 10)
1511     return 0;
1512
1513   // If multiple users are using the root value, procede with
1514   // simplification conservatively assuming that all elements
1515   // are needed.
1516   if (!V->hasOneUse()) {
1517     // Quit if we find multiple users of a non-root value though.
1518     // They'll be handled when it's their turn to be visited by
1519     // the main instcombine process.
1520     if (Depth != 0)
1521       // TODO: Just compute the UndefElts information recursively.
1522       return 0;
1523
1524     // Conservatively assume that all elements are needed.
1525     DemandedElts = EltMask;
1526   }
1527   
1528   Instruction *I = dyn_cast<Instruction>(V);
1529   if (!I) return 0;        // Only analyze instructions.
1530   
1531   bool MadeChange = false;
1532   APInt UndefElts2(VWidth, 0);
1533   Value *TmpV;
1534   switch (I->getOpcode()) {
1535   default: break;
1536     
1537   case Instruction::InsertElement: {
1538     // If this is a variable index, we don't know which element it overwrites.
1539     // demand exactly the same input as we produce.
1540     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1541     if (Idx == 0) {
1542       // Note that we can't propagate undef elt info, because we don't know
1543       // which elt is getting updated.
1544       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1545                                         UndefElts2, Depth+1);
1546       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1547       break;
1548     }
1549     
1550     // If this is inserting an element that isn't demanded, remove this
1551     // insertelement.
1552     unsigned IdxNo = Idx->getZExtValue();
1553     if (IdxNo >= VWidth || !DemandedElts[IdxNo])
1554       return AddSoonDeadInstToWorklist(*I, 0);
1555     
1556     // Otherwise, the element inserted overwrites whatever was there, so the
1557     // input demanded set is simpler than the output set.
1558     APInt DemandedElts2 = DemandedElts;
1559     DemandedElts2.clear(IdxNo);
1560     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1561                                       UndefElts, Depth+1);
1562     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1563
1564     // The inserted element is defined.
1565     UndefElts.clear(IdxNo);
1566     break;
1567   }
1568   case Instruction::ShuffleVector: {
1569     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1570     uint64_t LHSVWidth =
1571       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1572     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1573     for (unsigned i = 0; i < VWidth; i++) {
1574       if (DemandedElts[i]) {
1575         unsigned MaskVal = Shuffle->getMaskValue(i);
1576         if (MaskVal != -1u) {
1577           assert(MaskVal < LHSVWidth * 2 &&
1578                  "shufflevector mask index out of range!");
1579           if (MaskVal < LHSVWidth)
1580             LeftDemanded.set(MaskVal);
1581           else
1582             RightDemanded.set(MaskVal - LHSVWidth);
1583         }
1584       }
1585     }
1586
1587     APInt UndefElts4(LHSVWidth, 0);
1588     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1589                                       UndefElts4, Depth+1);
1590     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1591
1592     APInt UndefElts3(LHSVWidth, 0);
1593     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1594                                       UndefElts3, Depth+1);
1595     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1596
1597     bool NewUndefElts = false;
1598     for (unsigned i = 0; i < VWidth; i++) {
1599       unsigned MaskVal = Shuffle->getMaskValue(i);
1600       if (MaskVal == -1u) {
1601         UndefElts.set(i);
1602       } else if (MaskVal < LHSVWidth) {
1603         if (UndefElts4[MaskVal]) {
1604           NewUndefElts = true;
1605           UndefElts.set(i);
1606         }
1607       } else {
1608         if (UndefElts3[MaskVal - LHSVWidth]) {
1609           NewUndefElts = true;
1610           UndefElts.set(i);
1611         }
1612       }
1613     }
1614
1615     if (NewUndefElts) {
1616       // Add additional discovered undefs.
1617       std::vector<Constant*> Elts;
1618       for (unsigned i = 0; i < VWidth; ++i) {
1619         if (UndefElts[i])
1620           Elts.push_back(UndefValue::get(Type::Int32Ty));
1621         else
1622           Elts.push_back(ConstantInt::get(Type::Int32Ty,
1623                                           Shuffle->getMaskValue(i)));
1624       }
1625       I->setOperand(2, ConstantVector::get(Elts));
1626       MadeChange = true;
1627     }
1628     break;
1629   }
1630   case Instruction::BitCast: {
1631     // Vector->vector casts only.
1632     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1633     if (!VTy) break;
1634     unsigned InVWidth = VTy->getNumElements();
1635     APInt InputDemandedElts(InVWidth, 0);
1636     unsigned Ratio;
1637
1638     if (VWidth == InVWidth) {
1639       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1640       // elements as are demanded of us.
1641       Ratio = 1;
1642       InputDemandedElts = DemandedElts;
1643     } else if (VWidth > InVWidth) {
1644       // Untested so far.
1645       break;
1646       
1647       // If there are more elements in the result than there are in the source,
1648       // then an input element is live if any of the corresponding output
1649       // elements are live.
1650       Ratio = VWidth/InVWidth;
1651       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1652         if (DemandedElts[OutIdx])
1653           InputDemandedElts.set(OutIdx/Ratio);
1654       }
1655     } else {
1656       // Untested so far.
1657       break;
1658       
1659       // If there are more elements in the source than there are in the result,
1660       // then an input element is live if the corresponding output element is
1661       // live.
1662       Ratio = InVWidth/VWidth;
1663       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1664         if (DemandedElts[InIdx/Ratio])
1665           InputDemandedElts.set(InIdx);
1666     }
1667     
1668     // div/rem demand all inputs, because they don't want divide by zero.
1669     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1670                                       UndefElts2, Depth+1);
1671     if (TmpV) {
1672       I->setOperand(0, TmpV);
1673       MadeChange = true;
1674     }
1675     
1676     UndefElts = UndefElts2;
1677     if (VWidth > InVWidth) {
1678       assert(0 && "Unimp");
1679       // If there are more elements in the result than there are in the source,
1680       // then an output element is undef if the corresponding input element is
1681       // undef.
1682       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1683         if (UndefElts2[OutIdx/Ratio])
1684           UndefElts.set(OutIdx);
1685     } else if (VWidth < InVWidth) {
1686       assert(0 && "Unimp");
1687       // If there are more elements in the source than there are in the result,
1688       // then a result element is undef if all of the corresponding input
1689       // elements are undef.
1690       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1691       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1692         if (!UndefElts2[InIdx])            // Not undef?
1693           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1694     }
1695     break;
1696   }
1697   case Instruction::And:
1698   case Instruction::Or:
1699   case Instruction::Xor:
1700   case Instruction::Add:
1701   case Instruction::Sub:
1702   case Instruction::Mul:
1703     // div/rem demand all inputs, because they don't want divide by zero.
1704     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1705                                       UndefElts, Depth+1);
1706     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1707     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1708                                       UndefElts2, Depth+1);
1709     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1710       
1711     // Output elements are undefined if both are undefined.  Consider things
1712     // like undef&0.  The result is known zero, not undef.
1713     UndefElts &= UndefElts2;
1714     break;
1715     
1716   case Instruction::Call: {
1717     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1718     if (!II) break;
1719     switch (II->getIntrinsicID()) {
1720     default: break;
1721       
1722     // Binary vector operations that work column-wise.  A dest element is a
1723     // function of the corresponding input elements from the two inputs.
1724     case Intrinsic::x86_sse_sub_ss:
1725     case Intrinsic::x86_sse_mul_ss:
1726     case Intrinsic::x86_sse_min_ss:
1727     case Intrinsic::x86_sse_max_ss:
1728     case Intrinsic::x86_sse2_sub_sd:
1729     case Intrinsic::x86_sse2_mul_sd:
1730     case Intrinsic::x86_sse2_min_sd:
1731     case Intrinsic::x86_sse2_max_sd:
1732       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1733                                         UndefElts, Depth+1);
1734       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1735       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1736                                         UndefElts2, Depth+1);
1737       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1738
1739       // If only the low elt is demanded and this is a scalarizable intrinsic,
1740       // scalarize it now.
1741       if (DemandedElts == 1) {
1742         switch (II->getIntrinsicID()) {
1743         default: break;
1744         case Intrinsic::x86_sse_sub_ss:
1745         case Intrinsic::x86_sse_mul_ss:
1746         case Intrinsic::x86_sse2_sub_sd:
1747         case Intrinsic::x86_sse2_mul_sd:
1748           // TODO: Lower MIN/MAX/ABS/etc
1749           Value *LHS = II->getOperand(1);
1750           Value *RHS = II->getOperand(2);
1751           // Extract the element as scalars.
1752           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1753           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1754           
1755           switch (II->getIntrinsicID()) {
1756           default: assert(0 && "Case stmts out of sync!");
1757           case Intrinsic::x86_sse_sub_ss:
1758           case Intrinsic::x86_sse2_sub_sd:
1759             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1760                                                         II->getName()), *II);
1761             break;
1762           case Intrinsic::x86_sse_mul_ss:
1763           case Intrinsic::x86_sse2_mul_sd:
1764             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1765                                                          II->getName()), *II);
1766             break;
1767           }
1768           
1769           Instruction *New =
1770             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1771                                       II->getName());
1772           InsertNewInstBefore(New, *II);
1773           AddSoonDeadInstToWorklist(*II, 0);
1774           return New;
1775         }            
1776       }
1777         
1778       // Output elements are undefined if both are undefined.  Consider things
1779       // like undef&0.  The result is known zero, not undef.
1780       UndefElts &= UndefElts2;
1781       break;
1782     }
1783     break;
1784   }
1785   }
1786   return MadeChange ? I : 0;
1787 }
1788
1789
1790 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1791 /// function is designed to check a chain of associative operators for a
1792 /// potential to apply a certain optimization.  Since the optimization may be
1793 /// applicable if the expression was reassociated, this checks the chain, then
1794 /// reassociates the expression as necessary to expose the optimization
1795 /// opportunity.  This makes use of a special Functor, which must define
1796 /// 'shouldApply' and 'apply' methods.
1797 ///
1798 template<typename Functor>
1799 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1800   unsigned Opcode = Root.getOpcode();
1801   Value *LHS = Root.getOperand(0);
1802
1803   // Quick check, see if the immediate LHS matches...
1804   if (F.shouldApply(LHS))
1805     return F.apply(Root);
1806
1807   // Otherwise, if the LHS is not of the same opcode as the root, return.
1808   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1809   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1810     // Should we apply this transform to the RHS?
1811     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1812
1813     // If not to the RHS, check to see if we should apply to the LHS...
1814     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1815       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1816       ShouldApply = true;
1817     }
1818
1819     // If the functor wants to apply the optimization to the RHS of LHSI,
1820     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1821     if (ShouldApply) {
1822       // Now all of the instructions are in the current basic block, go ahead
1823       // and perform the reassociation.
1824       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1825
1826       // First move the selected RHS to the LHS of the root...
1827       Root.setOperand(0, LHSI->getOperand(1));
1828
1829       // Make what used to be the LHS of the root be the user of the root...
1830       Value *ExtraOperand = TmpLHSI->getOperand(1);
1831       if (&Root == TmpLHSI) {
1832         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1833         return 0;
1834       }
1835       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1836       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1837       BasicBlock::iterator ARI = &Root; ++ARI;
1838       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1839       ARI = Root;
1840
1841       // Now propagate the ExtraOperand down the chain of instructions until we
1842       // get to LHSI.
1843       while (TmpLHSI != LHSI) {
1844         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1845         // Move the instruction to immediately before the chain we are
1846         // constructing to avoid breaking dominance properties.
1847         NextLHSI->moveBefore(ARI);
1848         ARI = NextLHSI;
1849
1850         Value *NextOp = NextLHSI->getOperand(1);
1851         NextLHSI->setOperand(1, ExtraOperand);
1852         TmpLHSI = NextLHSI;
1853         ExtraOperand = NextOp;
1854       }
1855
1856       // Now that the instructions are reassociated, have the functor perform
1857       // the transformation...
1858       return F.apply(Root);
1859     }
1860
1861     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1862   }
1863   return 0;
1864 }
1865
1866 namespace {
1867
1868 // AddRHS - Implements: X + X --> X << 1
1869 struct AddRHS {
1870   Value *RHS;
1871   AddRHS(Value *rhs) : RHS(rhs) {}
1872   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1873   Instruction *apply(BinaryOperator &Add) const {
1874     return BinaryOperator::CreateShl(Add.getOperand(0),
1875                                      ConstantInt::get(Add.getType(), 1));
1876   }
1877 };
1878
1879 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1880 //                 iff C1&C2 == 0
1881 struct AddMaskingAnd {
1882   Constant *C2;
1883   AddMaskingAnd(Constant *c) : C2(c) {}
1884   bool shouldApply(Value *LHS) const {
1885     ConstantInt *C1;
1886     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1887            ConstantExpr::getAnd(C1, C2)->isNullValue();
1888   }
1889   Instruction *apply(BinaryOperator &Add) const {
1890     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1891   }
1892 };
1893
1894 }
1895
1896 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1897                                              InstCombiner *IC) {
1898   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1899     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1900   }
1901
1902   // Figure out if the constant is the left or the right argument.
1903   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1904   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1905
1906   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1907     if (ConstIsRHS)
1908       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1909     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1910   }
1911
1912   Value *Op0 = SO, *Op1 = ConstOperand;
1913   if (!ConstIsRHS)
1914     std::swap(Op0, Op1);
1915   Instruction *New;
1916   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1917     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1918   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1919     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1920                           SO->getName()+".cmp");
1921   else {
1922     assert(0 && "Unknown binary instruction type!");
1923     abort();
1924   }
1925   return IC->InsertNewInstBefore(New, I);
1926 }
1927
1928 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1929 // constant as the other operand, try to fold the binary operator into the
1930 // select arguments.  This also works for Cast instructions, which obviously do
1931 // not have a second operand.
1932 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1933                                      InstCombiner *IC) {
1934   // Don't modify shared select instructions
1935   if (!SI->hasOneUse()) return 0;
1936   Value *TV = SI->getOperand(1);
1937   Value *FV = SI->getOperand(2);
1938
1939   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1940     // Bool selects with constant operands can be folded to logical ops.
1941     if (SI->getType() == Type::Int1Ty) return 0;
1942
1943     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1944     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1945
1946     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1947                               SelectFalseVal);
1948   }
1949   return 0;
1950 }
1951
1952
1953 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1954 /// node as operand #0, see if we can fold the instruction into the PHI (which
1955 /// is only possible if all operands to the PHI are constants).
1956 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1957   PHINode *PN = cast<PHINode>(I.getOperand(0));
1958   unsigned NumPHIValues = PN->getNumIncomingValues();
1959   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1960
1961   // Check to see if all of the operands of the PHI are constants.  If there is
1962   // one non-constant value, remember the BB it is.  If there is more than one
1963   // or if *it* is a PHI, bail out.
1964   BasicBlock *NonConstBB = 0;
1965   for (unsigned i = 0; i != NumPHIValues; ++i)
1966     if (!isa<Constant>(PN->getIncomingValue(i))) {
1967       if (NonConstBB) return 0;  // More than one non-const value.
1968       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1969       NonConstBB = PN->getIncomingBlock(i);
1970       
1971       // If the incoming non-constant value is in I's block, we have an infinite
1972       // loop.
1973       if (NonConstBB == I.getParent())
1974         return 0;
1975     }
1976   
1977   // If there is exactly one non-constant value, we can insert a copy of the
1978   // operation in that block.  However, if this is a critical edge, we would be
1979   // inserting the computation one some other paths (e.g. inside a loop).  Only
1980   // do this if the pred block is unconditionally branching into the phi block.
1981   if (NonConstBB) {
1982     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1983     if (!BI || !BI->isUnconditional()) return 0;
1984   }
1985
1986   // Okay, we can do the transformation: create the new PHI node.
1987   PHINode *NewPN = PHINode::Create(I.getType(), "");
1988   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1989   InsertNewInstBefore(NewPN, *PN);
1990   NewPN->takeName(PN);
1991
1992   // Next, add all of the operands to the PHI.
1993   if (I.getNumOperands() == 2) {
1994     Constant *C = cast<Constant>(I.getOperand(1));
1995     for (unsigned i = 0; i != NumPHIValues; ++i) {
1996       Value *InV = 0;
1997       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1998         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1999           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2000         else
2001           InV = ConstantExpr::get(I.getOpcode(), InC, C);
2002       } else {
2003         assert(PN->getIncomingBlock(i) == NonConstBB);
2004         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
2005           InV = BinaryOperator::Create(BO->getOpcode(),
2006                                        PN->getIncomingValue(i), C, "phitmp",
2007                                        NonConstBB->getTerminator());
2008         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2009           InV = CmpInst::Create(CI->getOpcode(), 
2010                                 CI->getPredicate(),
2011                                 PN->getIncomingValue(i), C, "phitmp",
2012                                 NonConstBB->getTerminator());
2013         else
2014           assert(0 && "Unknown binop!");
2015         
2016         AddToWorkList(cast<Instruction>(InV));
2017       }
2018       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2019     }
2020   } else { 
2021     CastInst *CI = cast<CastInst>(&I);
2022     const Type *RetTy = CI->getType();
2023     for (unsigned i = 0; i != NumPHIValues; ++i) {
2024       Value *InV;
2025       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2026         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2027       } else {
2028         assert(PN->getIncomingBlock(i) == NonConstBB);
2029         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2030                                I.getType(), "phitmp", 
2031                                NonConstBB->getTerminator());
2032         AddToWorkList(cast<Instruction>(InV));
2033       }
2034       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2035     }
2036   }
2037   return ReplaceInstUsesWith(I, NewPN);
2038 }
2039
2040
2041 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2042 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2043 /// This basically requires proving that the add in the original type would not
2044 /// overflow to change the sign bit or have a carry out.
2045 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2046   // There are different heuristics we can use for this.  Here are some simple
2047   // ones.
2048   
2049   // Add has the property that adding any two 2's complement numbers can only 
2050   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2051   // have at least two sign bits, we know that the addition of the two values will
2052   // sign extend fine.
2053   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2054     return true;
2055   
2056   
2057   // If one of the operands only has one non-zero bit, and if the other operand
2058   // has a known-zero bit in a more significant place than it (not including the
2059   // sign bit) the ripple may go up to and fill the zero, but won't change the
2060   // sign.  For example, (X & ~4) + 1.
2061   
2062   // TODO: Implement.
2063   
2064   return false;
2065 }
2066
2067
2068 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2069   bool Changed = SimplifyCommutative(I);
2070   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2071
2072   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2073     // X + undef -> undef
2074     if (isa<UndefValue>(RHS))
2075       return ReplaceInstUsesWith(I, RHS);
2076
2077     // X + 0 --> X
2078     if (RHSC->isNullValue())
2079       return ReplaceInstUsesWith(I, LHS);
2080
2081     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2082       // X + (signbit) --> X ^ signbit
2083       const APInt& Val = CI->getValue();
2084       uint32_t BitWidth = Val.getBitWidth();
2085       if (Val == APInt::getSignBit(BitWidth))
2086         return BinaryOperator::CreateXor(LHS, RHS);
2087       
2088       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2089       // (X & 254)+1 -> (X&254)|1
2090       if (!isa<VectorType>(I.getType()) && SimplifyDemandedInstructionBits(I))
2091         return &I;
2092
2093       // zext(i1) - 1  ->  select i1, 0, -1
2094       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2095         if (CI->isAllOnesValue() &&
2096             ZI->getOperand(0)->getType() == Type::Int1Ty)
2097           return SelectInst::Create(ZI->getOperand(0),
2098                                     Constant::getNullValue(I.getType()),
2099                                     ConstantInt::getAllOnesValue(I.getType()));
2100     }
2101
2102     if (isa<PHINode>(LHS))
2103       if (Instruction *NV = FoldOpIntoPhi(I))
2104         return NV;
2105     
2106     ConstantInt *XorRHS = 0;
2107     Value *XorLHS = 0;
2108     if (isa<ConstantInt>(RHSC) &&
2109         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2110       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2111       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2112       
2113       uint32_t Size = TySizeBits / 2;
2114       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2115       APInt CFF80Val(-C0080Val);
2116       do {
2117         if (TySizeBits > Size) {
2118           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2119           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2120           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2121               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2122             // This is a sign extend if the top bits are known zero.
2123             if (!MaskedValueIsZero(XorLHS, 
2124                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2125               Size = 0;  // Not a sign ext, but can't be any others either.
2126             break;
2127           }
2128         }
2129         Size >>= 1;
2130         C0080Val = APIntOps::lshr(C0080Val, Size);
2131         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2132       } while (Size >= 1);
2133       
2134       // FIXME: This shouldn't be necessary. When the backends can handle types
2135       // with funny bit widths then this switch statement should be removed. It
2136       // is just here to get the size of the "middle" type back up to something
2137       // that the back ends can handle.
2138       const Type *MiddleType = 0;
2139       switch (Size) {
2140         default: break;
2141         case 32: MiddleType = Type::Int32Ty; break;
2142         case 16: MiddleType = Type::Int16Ty; break;
2143         case  8: MiddleType = Type::Int8Ty; break;
2144       }
2145       if (MiddleType) {
2146         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2147         InsertNewInstBefore(NewTrunc, I);
2148         return new SExtInst(NewTrunc, I.getType(), I.getName());
2149       }
2150     }
2151   }
2152
2153   if (I.getType() == Type::Int1Ty)
2154     return BinaryOperator::CreateXor(LHS, RHS);
2155
2156   // X + X --> X << 1
2157   if (I.getType()->isInteger()) {
2158     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2159
2160     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2161       if (RHSI->getOpcode() == Instruction::Sub)
2162         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2163           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2164     }
2165     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2166       if (LHSI->getOpcode() == Instruction::Sub)
2167         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2168           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2169     }
2170   }
2171
2172   // -A + B  -->  B - A
2173   // -A + -B  -->  -(A + B)
2174   if (Value *LHSV = dyn_castNegVal(LHS)) {
2175     if (LHS->getType()->isIntOrIntVector()) {
2176       if (Value *RHSV = dyn_castNegVal(RHS)) {
2177         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2178         InsertNewInstBefore(NewAdd, I);
2179         return BinaryOperator::CreateNeg(NewAdd);
2180       }
2181     }
2182     
2183     return BinaryOperator::CreateSub(RHS, LHSV);
2184   }
2185
2186   // A + -B  -->  A - B
2187   if (!isa<Constant>(RHS))
2188     if (Value *V = dyn_castNegVal(RHS))
2189       return BinaryOperator::CreateSub(LHS, V);
2190
2191
2192   ConstantInt *C2;
2193   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2194     if (X == RHS)   // X*C + X --> X * (C+1)
2195       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2196
2197     // X*C1 + X*C2 --> X * (C1+C2)
2198     ConstantInt *C1;
2199     if (X == dyn_castFoldableMul(RHS, C1))
2200       return BinaryOperator::CreateMul(X, Add(C1, C2));
2201   }
2202
2203   // X + X*C --> X * (C+1)
2204   if (dyn_castFoldableMul(RHS, C2) == LHS)
2205     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2206
2207   // X + ~X --> -1   since   ~X = -X-1
2208   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2209     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2210   
2211
2212   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2213   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2214     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2215       return R;
2216   
2217   // A+B --> A|B iff A and B have no bits set in common.
2218   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2219     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2220     APInt LHSKnownOne(IT->getBitWidth(), 0);
2221     APInt LHSKnownZero(IT->getBitWidth(), 0);
2222     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2223     if (LHSKnownZero != 0) {
2224       APInt RHSKnownOne(IT->getBitWidth(), 0);
2225       APInt RHSKnownZero(IT->getBitWidth(), 0);
2226       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2227       
2228       // No bits in common -> bitwise or.
2229       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2230         return BinaryOperator::CreateOr(LHS, RHS);
2231     }
2232   }
2233
2234   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2235   if (I.getType()->isIntOrIntVector()) {
2236     Value *W, *X, *Y, *Z;
2237     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2238         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2239       if (W != Y) {
2240         if (W == Z) {
2241           std::swap(Y, Z);
2242         } else if (Y == X) {
2243           std::swap(W, X);
2244         } else if (X == Z) {
2245           std::swap(Y, Z);
2246           std::swap(W, X);
2247         }
2248       }
2249
2250       if (W == Y) {
2251         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2252                                                             LHS->getName()), I);
2253         return BinaryOperator::CreateMul(W, NewAdd);
2254       }
2255     }
2256   }
2257
2258   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2259     Value *X = 0;
2260     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2261       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2262
2263     // (X & FF00) + xx00  -> (X+xx00) & FF00
2264     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2265       Constant *Anded = And(CRHS, C2);
2266       if (Anded == CRHS) {
2267         // See if all bits from the first bit set in the Add RHS up are included
2268         // in the mask.  First, get the rightmost bit.
2269         const APInt& AddRHSV = CRHS->getValue();
2270
2271         // Form a mask of all bits from the lowest bit added through the top.
2272         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2273
2274         // See if the and mask includes all of these bits.
2275         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2276
2277         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2278           // Okay, the xform is safe.  Insert the new add pronto.
2279           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2280                                                             LHS->getName()), I);
2281           return BinaryOperator::CreateAnd(NewAdd, C2);
2282         }
2283       }
2284     }
2285
2286     // Try to fold constant add into select arguments.
2287     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2288       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2289         return R;
2290   }
2291
2292   // add (cast *A to intptrtype) B -> 
2293   //   cast (GEP (cast *A to i8*) B)  -->  intptrtype
2294   {
2295     CastInst *CI = dyn_cast<CastInst>(LHS);
2296     Value *Other = RHS;
2297     if (!CI) {
2298       CI = dyn_cast<CastInst>(RHS);
2299       Other = LHS;
2300     }
2301     if (CI && CI->getType()->isSized() && 
2302         (CI->getType()->getPrimitiveSizeInBits() == 
2303          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2304         && isa<PointerType>(CI->getOperand(0)->getType())) {
2305       unsigned AS =
2306         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2307       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2308                                       PointerType::get(Type::Int8Ty, AS), I);
2309       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2310       return new PtrToIntInst(I2, CI->getType());
2311     }
2312   }
2313   
2314   // add (select X 0 (sub n A)) A  -->  select X A n
2315   {
2316     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2317     Value *A = RHS;
2318     if (!SI) {
2319       SI = dyn_cast<SelectInst>(RHS);
2320       A = LHS;
2321     }
2322     if (SI && SI->hasOneUse()) {
2323       Value *TV = SI->getTrueValue();
2324       Value *FV = SI->getFalseValue();
2325       Value *N;
2326
2327       // Can we fold the add into the argument of the select?
2328       // We check both true and false select arguments for a matching subtract.
2329       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2330         // Fold the add into the true select value.
2331         return SelectInst::Create(SI->getCondition(), N, A);
2332       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2333         // Fold the add into the false select value.
2334         return SelectInst::Create(SI->getCondition(), A, N);
2335     }
2336   }
2337
2338   // Check for (add (sext x), y), see if we can merge this into an
2339   // integer add followed by a sext.
2340   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2341     // (add (sext x), cst) --> (sext (add x, cst'))
2342     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2343       Constant *CI = 
2344         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2345       if (LHSConv->hasOneUse() &&
2346           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2347           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2348         // Insert the new, smaller add.
2349         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2350                                                         CI, "addconv");
2351         InsertNewInstBefore(NewAdd, I);
2352         return new SExtInst(NewAdd, I.getType());
2353       }
2354     }
2355     
2356     // (add (sext x), (sext y)) --> (sext (add int x, y))
2357     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2358       // Only do this if x/y have the same type, if at last one of them has a
2359       // single use (so we don't increase the number of sexts), and if the
2360       // integer add will not overflow.
2361       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2362           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2363           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2364                                    RHSConv->getOperand(0))) {
2365         // Insert the new integer add.
2366         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2367                                                         RHSConv->getOperand(0),
2368                                                         "addconv");
2369         InsertNewInstBefore(NewAdd, I);
2370         return new SExtInst(NewAdd, I.getType());
2371       }
2372     }
2373   }
2374
2375   return Changed ? &I : 0;
2376 }
2377
2378 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2379   bool Changed = SimplifyCommutative(I);
2380   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2381
2382   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2383     // X + 0 --> X
2384     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2385       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2386                               (I.getType())->getValueAPF()))
2387         return ReplaceInstUsesWith(I, LHS);
2388     }
2389
2390     if (isa<PHINode>(LHS))
2391       if (Instruction *NV = FoldOpIntoPhi(I))
2392         return NV;
2393   }
2394
2395   // -A + B  -->  B - A
2396   // -A + -B  -->  -(A + B)
2397   if (Value *LHSV = dyn_castFNegVal(LHS))
2398     return BinaryOperator::CreateFSub(RHS, LHSV);
2399
2400   // A + -B  -->  A - B
2401   if (!isa<Constant>(RHS))
2402     if (Value *V = dyn_castFNegVal(RHS))
2403       return BinaryOperator::CreateFSub(LHS, V);
2404
2405   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2406   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2407     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2408       return ReplaceInstUsesWith(I, LHS);
2409
2410   // Check for (add double (sitofp x), y), see if we can merge this into an
2411   // integer add followed by a promotion.
2412   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2413     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2414     // ... if the constant fits in the integer value.  This is useful for things
2415     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2416     // requires a constant pool load, and generally allows the add to be better
2417     // instcombined.
2418     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2419       Constant *CI = 
2420       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2421       if (LHSConv->hasOneUse() &&
2422           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2423           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2424         // Insert the new integer add.
2425         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2426                                                         CI, "addconv");
2427         InsertNewInstBefore(NewAdd, I);
2428         return new SIToFPInst(NewAdd, I.getType());
2429       }
2430     }
2431     
2432     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2433     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2434       // Only do this if x/y have the same type, if at last one of them has a
2435       // single use (so we don't increase the number of int->fp conversions),
2436       // and if the integer add will not overflow.
2437       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2438           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2439           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2440                                    RHSConv->getOperand(0))) {
2441         // Insert the new integer add.
2442         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2443                                                         RHSConv->getOperand(0),
2444                                                         "addconv");
2445         InsertNewInstBefore(NewAdd, I);
2446         return new SIToFPInst(NewAdd, I.getType());
2447       }
2448     }
2449   }
2450   
2451   return Changed ? &I : 0;
2452 }
2453
2454 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2455   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2456
2457   if (Op0 == Op1)                        // sub X, X  -> 0
2458     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2459
2460   // If this is a 'B = x-(-A)', change to B = x+A...
2461   if (Value *V = dyn_castNegVal(Op1))
2462     return BinaryOperator::CreateAdd(Op0, V);
2463
2464   if (isa<UndefValue>(Op0))
2465     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2466   if (isa<UndefValue>(Op1))
2467     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2468
2469   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2470     // Replace (-1 - A) with (~A)...
2471     if (C->isAllOnesValue())
2472       return BinaryOperator::CreateNot(Op1);
2473
2474     // C - ~X == X + (1+C)
2475     Value *X = 0;
2476     if (match(Op1, m_Not(m_Value(X))))
2477       return BinaryOperator::CreateAdd(X, AddOne(C));
2478
2479     // -(X >>u 31) -> (X >>s 31)
2480     // -(X >>s 31) -> (X >>u 31)
2481     if (C->isZero()) {
2482       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2483         if (SI->getOpcode() == Instruction::LShr) {
2484           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2485             // Check to see if we are shifting out everything but the sign bit.
2486             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2487                 SI->getType()->getPrimitiveSizeInBits()-1) {
2488               // Ok, the transformation is safe.  Insert AShr.
2489               return BinaryOperator::Create(Instruction::AShr, 
2490                                           SI->getOperand(0), CU, SI->getName());
2491             }
2492           }
2493         }
2494         else if (SI->getOpcode() == Instruction::AShr) {
2495           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2496             // Check to see if we are shifting out everything but the sign bit.
2497             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2498                 SI->getType()->getPrimitiveSizeInBits()-1) {
2499               // Ok, the transformation is safe.  Insert LShr. 
2500               return BinaryOperator::CreateLShr(
2501                                           SI->getOperand(0), CU, SI->getName());
2502             }
2503           }
2504         }
2505       }
2506     }
2507
2508     // Try to fold constant sub into select arguments.
2509     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2510       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2511         return R;
2512   }
2513
2514   if (I.getType() == Type::Int1Ty)
2515     return BinaryOperator::CreateXor(Op0, Op1);
2516
2517   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2518     if (Op1I->getOpcode() == Instruction::Add) {
2519       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2520         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2521       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2522         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2523       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2524         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2525           // C1-(X+C2) --> (C1-C2)-X
2526           return BinaryOperator::CreateSub(Subtract(CI1, CI2), 
2527                                            Op1I->getOperand(0));
2528       }
2529     }
2530
2531     if (Op1I->hasOneUse()) {
2532       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2533       // is not used by anyone else...
2534       //
2535       if (Op1I->getOpcode() == Instruction::Sub) {
2536         // Swap the two operands of the subexpr...
2537         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2538         Op1I->setOperand(0, IIOp1);
2539         Op1I->setOperand(1, IIOp0);
2540
2541         // Create the new top level add instruction...
2542         return BinaryOperator::CreateAdd(Op0, Op1);
2543       }
2544
2545       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2546       //
2547       if (Op1I->getOpcode() == Instruction::And &&
2548           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2549         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2550
2551         Value *NewNot =
2552           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2553         return BinaryOperator::CreateAnd(Op0, NewNot);
2554       }
2555
2556       // 0 - (X sdiv C)  -> (X sdiv -C)
2557       if (Op1I->getOpcode() == Instruction::SDiv)
2558         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2559           if (CSI->isZero())
2560             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2561               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2562                                                ConstantExpr::getNeg(DivRHS));
2563
2564       // X - X*C --> X * (1-C)
2565       ConstantInt *C2 = 0;
2566       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2567         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2568         return BinaryOperator::CreateMul(Op0, CP1);
2569       }
2570     }
2571   }
2572
2573   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2574     if (Op0I->getOpcode() == Instruction::Add) {
2575       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2576         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2577       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2578         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2579     } else if (Op0I->getOpcode() == Instruction::Sub) {
2580       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2581         return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2582     }
2583   }
2584
2585   ConstantInt *C1;
2586   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2587     if (X == Op1)  // X*C - X --> X * (C-1)
2588       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2589
2590     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2591     if (X == dyn_castFoldableMul(Op1, C2))
2592       return BinaryOperator::CreateMul(X, Subtract(C1, C2));
2593   }
2594   return 0;
2595 }
2596
2597 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2598   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2599
2600   // If this is a 'B = x-(-A)', change to B = x+A...
2601   if (Value *V = dyn_castFNegVal(Op1))
2602     return BinaryOperator::CreateFAdd(Op0, V);
2603
2604   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2605     if (Op1I->getOpcode() == Instruction::FAdd) {
2606       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2607         return BinaryOperator::CreateFNeg(Op1I->getOperand(1), I.getName());
2608       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2609         return BinaryOperator::CreateFNeg(Op1I->getOperand(0), I.getName());
2610     }
2611   }
2612
2613   return 0;
2614 }
2615
2616 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2617 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2618 /// TrueIfSigned if the result of the comparison is true when the input value is
2619 /// signed.
2620 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2621                            bool &TrueIfSigned) {
2622   switch (pred) {
2623   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2624     TrueIfSigned = true;
2625     return RHS->isZero();
2626   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2627     TrueIfSigned = true;
2628     return RHS->isAllOnesValue();
2629   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2630     TrueIfSigned = false;
2631     return RHS->isAllOnesValue();
2632   case ICmpInst::ICMP_UGT:
2633     // True if LHS u> RHS and RHS == high-bit-mask - 1
2634     TrueIfSigned = true;
2635     return RHS->getValue() ==
2636       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2637   case ICmpInst::ICMP_UGE: 
2638     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2639     TrueIfSigned = true;
2640     return RHS->getValue().isSignBit();
2641   default:
2642     return false;
2643   }
2644 }
2645
2646 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2647   bool Changed = SimplifyCommutative(I);
2648   Value *Op0 = I.getOperand(0);
2649
2650   // TODO: If Op1 is undef and Op0 is finite, return zero.
2651   if (!I.getType()->isFPOrFPVector() &&
2652       isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2653     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2654
2655   // Simplify mul instructions with a constant RHS...
2656   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2657     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2658
2659       // ((X << C1)*C2) == (X * (C2 << C1))
2660       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2661         if (SI->getOpcode() == Instruction::Shl)
2662           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2663             return BinaryOperator::CreateMul(SI->getOperand(0),
2664                                              ConstantExpr::getShl(CI, ShOp));
2665
2666       if (CI->isZero())
2667         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2668       if (CI->equalsInt(1))                  // X * 1  == X
2669         return ReplaceInstUsesWith(I, Op0);
2670       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2671         return BinaryOperator::CreateNeg(Op0, I.getName());
2672
2673       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2674       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2675         return BinaryOperator::CreateShl(Op0,
2676                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2677       }
2678     } else if (isa<VectorType>(Op1->getType())) {
2679       // TODO: If Op1 is all zeros and Op0 is all finite, return all zeros.
2680
2681       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2682         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2683           return BinaryOperator::CreateNeg(Op0, I.getName());
2684
2685         // As above, vector X*splat(1.0) -> X in all defined cases.
2686         if (Constant *Splat = Op1V->getSplatValue()) {
2687           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2688             if (CI->equalsInt(1))
2689               return ReplaceInstUsesWith(I, Op0);
2690         }
2691       }
2692     }
2693     
2694     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2695       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2696           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2697         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2698         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2699                                                      Op1, "tmp");
2700         InsertNewInstBefore(Add, I);
2701         Value *C1C2 = ConstantExpr::getMul(Op1, 
2702                                            cast<Constant>(Op0I->getOperand(1)));
2703         return BinaryOperator::CreateAdd(Add, C1C2);
2704         
2705       }
2706
2707     // Try to fold constant mul into select arguments.
2708     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2709       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2710         return R;
2711
2712     if (isa<PHINode>(Op0))
2713       if (Instruction *NV = FoldOpIntoPhi(I))
2714         return NV;
2715   }
2716
2717   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2718     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2719       return BinaryOperator::CreateMul(Op0v, Op1v);
2720
2721   // (X / Y) *  Y = X - (X % Y)
2722   // (X / Y) * -Y = (X % Y) - X
2723   {
2724     Value *Op1 = I.getOperand(1);
2725     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2726     if (!BO ||
2727         (BO->getOpcode() != Instruction::UDiv && 
2728          BO->getOpcode() != Instruction::SDiv)) {
2729       Op1 = Op0;
2730       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2731     }
2732     Value *Neg = dyn_castNegVal(Op1);
2733     if (BO && BO->hasOneUse() &&
2734         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2735         (BO->getOpcode() == Instruction::UDiv ||
2736          BO->getOpcode() == Instruction::SDiv)) {
2737       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2738
2739       Instruction *Rem;
2740       if (BO->getOpcode() == Instruction::UDiv)
2741         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2742       else
2743         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2744
2745       InsertNewInstBefore(Rem, I);
2746       Rem->takeName(BO);
2747
2748       if (Op1BO == Op1)
2749         return BinaryOperator::CreateSub(Op0BO, Rem);
2750       else
2751         return BinaryOperator::CreateSub(Rem, Op0BO);
2752     }
2753   }
2754
2755   if (I.getType() == Type::Int1Ty)
2756     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2757
2758   // If one of the operands of the multiply is a cast from a boolean value, then
2759   // we know the bool is either zero or one, so this is a 'masking' multiply.
2760   // See if we can simplify things based on how the boolean was originally
2761   // formed.
2762   CastInst *BoolCast = 0;
2763   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2764     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2765       BoolCast = CI;
2766   if (!BoolCast)
2767     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2768       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2769         BoolCast = CI;
2770   if (BoolCast) {
2771     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2772       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2773       const Type *SCOpTy = SCIOp0->getType();
2774       bool TIS = false;
2775       
2776       // If the icmp is true iff the sign bit of X is set, then convert this
2777       // multiply into a shift/and combination.
2778       if (isa<ConstantInt>(SCIOp1) &&
2779           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2780           TIS) {
2781         // Shift the X value right to turn it into "all signbits".
2782         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2783                                           SCOpTy->getPrimitiveSizeInBits()-1);
2784         Value *V =
2785           InsertNewInstBefore(
2786             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2787                                             BoolCast->getOperand(0)->getName()+
2788                                             ".mask"), I);
2789
2790         // If the multiply type is not the same as the source type, sign extend
2791         // or truncate to the multiply type.
2792         if (I.getType() != V->getType()) {
2793           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2794           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2795           Instruction::CastOps opcode = 
2796             (SrcBits == DstBits ? Instruction::BitCast : 
2797              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2798           V = InsertCastBefore(opcode, V, I.getType(), I);
2799         }
2800
2801         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2802         return BinaryOperator::CreateAnd(V, OtherOp);
2803       }
2804     }
2805   }
2806
2807   return Changed ? &I : 0;
2808 }
2809
2810 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2811   bool Changed = SimplifyCommutative(I);
2812   Value *Op0 = I.getOperand(0);
2813
2814   // Simplify mul instructions with a constant RHS...
2815   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2816     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2817       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2818       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2819       if (Op1F->isExactlyValue(1.0))
2820         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2821     } else if (isa<VectorType>(Op1->getType())) {
2822       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2823         // As above, vector X*splat(1.0) -> X in all defined cases.
2824         if (Constant *Splat = Op1V->getSplatValue()) {
2825           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2826             if (F->isExactlyValue(1.0))
2827               return ReplaceInstUsesWith(I, Op0);
2828         }
2829       }
2830     }
2831
2832     // Try to fold constant mul into select arguments.
2833     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2834       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2835         return R;
2836
2837     if (isa<PHINode>(Op0))
2838       if (Instruction *NV = FoldOpIntoPhi(I))
2839         return NV;
2840   }
2841
2842   if (Value *Op0v = dyn_castFNegVal(Op0))     // -X * -Y = X*Y
2843     if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
2844       return BinaryOperator::CreateFMul(Op0v, Op1v);
2845
2846   return Changed ? &I : 0;
2847 }
2848
2849 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2850 /// instruction.
2851 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2852   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2853   
2854   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2855   int NonNullOperand = -1;
2856   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2857     if (ST->isNullValue())
2858       NonNullOperand = 2;
2859   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2860   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2861     if (ST->isNullValue())
2862       NonNullOperand = 1;
2863   
2864   if (NonNullOperand == -1)
2865     return false;
2866   
2867   Value *SelectCond = SI->getOperand(0);
2868   
2869   // Change the div/rem to use 'Y' instead of the select.
2870   I.setOperand(1, SI->getOperand(NonNullOperand));
2871   
2872   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2873   // problem.  However, the select, or the condition of the select may have
2874   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2875   // propagate the known value for the select into other uses of it, and
2876   // propagate a known value of the condition into its other users.
2877   
2878   // If the select and condition only have a single use, don't bother with this,
2879   // early exit.
2880   if (SI->use_empty() && SelectCond->hasOneUse())
2881     return true;
2882   
2883   // Scan the current block backward, looking for other uses of SI.
2884   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2885   
2886   while (BBI != BBFront) {
2887     --BBI;
2888     // If we found a call to a function, we can't assume it will return, so
2889     // information from below it cannot be propagated above it.
2890     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2891       break;
2892     
2893     // Replace uses of the select or its condition with the known values.
2894     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2895          I != E; ++I) {
2896       if (*I == SI) {
2897         *I = SI->getOperand(NonNullOperand);
2898         AddToWorkList(BBI);
2899       } else if (*I == SelectCond) {
2900         *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2901                                    ConstantInt::getFalse();
2902         AddToWorkList(BBI);
2903       }
2904     }
2905     
2906     // If we past the instruction, quit looking for it.
2907     if (&*BBI == SI)
2908       SI = 0;
2909     if (&*BBI == SelectCond)
2910       SelectCond = 0;
2911     
2912     // If we ran out of things to eliminate, break out of the loop.
2913     if (SelectCond == 0 && SI == 0)
2914       break;
2915     
2916   }
2917   return true;
2918 }
2919
2920
2921 /// This function implements the transforms on div instructions that work
2922 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2923 /// used by the visitors to those instructions.
2924 /// @brief Transforms common to all three div instructions
2925 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2926   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2927
2928   // undef / X -> 0        for integer.
2929   // undef / X -> undef    for FP (the undef could be a snan).
2930   if (isa<UndefValue>(Op0)) {
2931     if (Op0->getType()->isFPOrFPVector())
2932       return ReplaceInstUsesWith(I, Op0);
2933     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2934   }
2935
2936   // X / undef -> undef
2937   if (isa<UndefValue>(Op1))
2938     return ReplaceInstUsesWith(I, Op1);
2939
2940   return 0;
2941 }
2942
2943 /// This function implements the transforms common to both integer division
2944 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2945 /// division instructions.
2946 /// @brief Common integer divide transforms
2947 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2948   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2949
2950   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2951   if (Op0 == Op1) {
2952     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2953       ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2954       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2955       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2956     }
2957
2958     ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2959     return ReplaceInstUsesWith(I, CI);
2960   }
2961   
2962   if (Instruction *Common = commonDivTransforms(I))
2963     return Common;
2964   
2965   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2966   // This does not apply for fdiv.
2967   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2968     return &I;
2969
2970   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2971     // div X, 1 == X
2972     if (RHS->equalsInt(1))
2973       return ReplaceInstUsesWith(I, Op0);
2974
2975     // (X / C1) / C2  -> X / (C1*C2)
2976     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2977       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2978         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2979           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2980             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2981           else 
2982             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2983                                           Multiply(RHS, LHSRHS));
2984         }
2985
2986     if (!RHS->isZero()) { // avoid X udiv 0
2987       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2988         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2989           return R;
2990       if (isa<PHINode>(Op0))
2991         if (Instruction *NV = FoldOpIntoPhi(I))
2992           return NV;
2993     }
2994   }
2995
2996   // 0 / X == 0, we don't need to preserve faults!
2997   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2998     if (LHS->equalsInt(0))
2999       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3000
3001   // It can't be division by zero, hence it must be division by one.
3002   if (I.getType() == Type::Int1Ty)
3003     return ReplaceInstUsesWith(I, Op0);
3004
3005   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3006     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3007       // div X, 1 == X
3008       if (X->isOne())
3009         return ReplaceInstUsesWith(I, Op0);
3010   }
3011
3012   return 0;
3013 }
3014
3015 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3016   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3017
3018   // Handle the integer div common cases
3019   if (Instruction *Common = commonIDivTransforms(I))
3020     return Common;
3021
3022   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3023     // X udiv C^2 -> X >> C
3024     // Check to see if this is an unsigned division with an exact power of 2,
3025     // if so, convert to a right shift.
3026     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3027       return BinaryOperator::CreateLShr(Op0, 
3028                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3029
3030     // X udiv C, where C >= signbit
3031     if (C->getValue().isNegative()) {
3032       Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
3033                                       I);
3034       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3035                                 ConstantInt::get(I.getType(), 1));
3036     }
3037   }
3038
3039   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3040   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3041     if (RHSI->getOpcode() == Instruction::Shl &&
3042         isa<ConstantInt>(RHSI->getOperand(0))) {
3043       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3044       if (C1.isPowerOf2()) {
3045         Value *N = RHSI->getOperand(1);
3046         const Type *NTy = N->getType();
3047         if (uint32_t C2 = C1.logBase2()) {
3048           Constant *C2V = ConstantInt::get(NTy, C2);
3049           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3050         }
3051         return BinaryOperator::CreateLShr(Op0, N);
3052       }
3053     }
3054   }
3055   
3056   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3057   // where C1&C2 are powers of two.
3058   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3059     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3060       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3061         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3062         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3063           // Compute the shift amounts
3064           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3065           // Construct the "on true" case of the select
3066           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3067           Instruction *TSI = BinaryOperator::CreateLShr(
3068                                                  Op0, TC, SI->getName()+".t");
3069           TSI = InsertNewInstBefore(TSI, I);
3070   
3071           // Construct the "on false" case of the select
3072           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3073           Instruction *FSI = BinaryOperator::CreateLShr(
3074                                                  Op0, FC, SI->getName()+".f");
3075           FSI = InsertNewInstBefore(FSI, I);
3076
3077           // construct the select instruction and return it.
3078           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3079         }
3080       }
3081   return 0;
3082 }
3083
3084 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3085   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3086
3087   // Handle the integer div common cases
3088   if (Instruction *Common = commonIDivTransforms(I))
3089     return Common;
3090
3091   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3092     // sdiv X, -1 == -X
3093     if (RHS->isAllOnesValue())
3094       return BinaryOperator::CreateNeg(Op0);
3095   }
3096
3097   // If the sign bits of both operands are zero (i.e. we can prove they are
3098   // unsigned inputs), turn this into a udiv.
3099   if (I.getType()->isInteger()) {
3100     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3101     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3102       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3103       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3104     }
3105   }      
3106   
3107   return 0;
3108 }
3109
3110 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3111   return commonDivTransforms(I);
3112 }
3113
3114 /// This function implements the transforms on rem instructions that work
3115 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3116 /// is used by the visitors to those instructions.
3117 /// @brief Transforms common to all three rem instructions
3118 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3119   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3120
3121   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3122     if (I.getType()->isFPOrFPVector())
3123       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3124     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3125   }
3126   if (isa<UndefValue>(Op1))
3127     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3128
3129   // Handle cases involving: rem X, (select Cond, Y, Z)
3130   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3131     return &I;
3132
3133   return 0;
3134 }
3135
3136 /// This function implements the transforms common to both integer remainder
3137 /// instructions (urem and srem). It is called by the visitors to those integer
3138 /// remainder instructions.
3139 /// @brief Common integer remainder transforms
3140 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3141   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3142
3143   if (Instruction *common = commonRemTransforms(I))
3144     return common;
3145
3146   // 0 % X == 0 for integer, we don't need to preserve faults!
3147   if (Constant *LHS = dyn_cast<Constant>(Op0))
3148     if (LHS->isNullValue())
3149       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3150
3151   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3152     // X % 0 == undef, we don't need to preserve faults!
3153     if (RHS->equalsInt(0))
3154       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3155     
3156     if (RHS->equalsInt(1))  // X % 1 == 0
3157       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3158
3159     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3160       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3161         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3162           return R;
3163       } else if (isa<PHINode>(Op0I)) {
3164         if (Instruction *NV = FoldOpIntoPhi(I))
3165           return NV;
3166       }
3167
3168       // See if we can fold away this rem instruction.
3169       if (SimplifyDemandedInstructionBits(I))
3170         return &I;
3171     }
3172   }
3173
3174   return 0;
3175 }
3176
3177 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3178   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3179
3180   if (Instruction *common = commonIRemTransforms(I))
3181     return common;
3182   
3183   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3184     // X urem C^2 -> X and C
3185     // Check to see if this is an unsigned remainder with an exact power of 2,
3186     // if so, convert to a bitwise and.
3187     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3188       if (C->getValue().isPowerOf2())
3189         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3190   }
3191
3192   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3193     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3194     if (RHSI->getOpcode() == Instruction::Shl &&
3195         isa<ConstantInt>(RHSI->getOperand(0))) {
3196       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3197         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3198         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3199                                                                    "tmp"), I);
3200         return BinaryOperator::CreateAnd(Op0, Add);
3201       }
3202     }
3203   }
3204
3205   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3206   // where C1&C2 are powers of two.
3207   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3208     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3209       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3210         // STO == 0 and SFO == 0 handled above.
3211         if ((STO->getValue().isPowerOf2()) && 
3212             (SFO->getValue().isPowerOf2())) {
3213           Value *TrueAnd = InsertNewInstBefore(
3214             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3215           Value *FalseAnd = InsertNewInstBefore(
3216             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3217           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3218         }
3219       }
3220   }
3221   
3222   return 0;
3223 }
3224
3225 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3226   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3227
3228   // Handle the integer rem common cases
3229   if (Instruction *common = commonIRemTransforms(I))
3230     return common;
3231   
3232   if (Value *RHSNeg = dyn_castNegVal(Op1))
3233     if (!isa<Constant>(RHSNeg) ||
3234         (isa<ConstantInt>(RHSNeg) &&
3235          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3236       // X % -Y -> X % Y
3237       AddUsesToWorkList(I);
3238       I.setOperand(1, RHSNeg);
3239       return &I;
3240     }
3241
3242   // If the sign bits of both operands are zero (i.e. we can prove they are
3243   // unsigned inputs), turn this into a urem.
3244   if (I.getType()->isInteger()) {
3245     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3246     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3247       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3248       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3249     }
3250   }
3251
3252   // If it's a constant vector, flip any negative values positive.
3253   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3254     unsigned VWidth = RHSV->getNumOperands();
3255
3256     bool hasNegative = false;
3257     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3258       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3259         if (RHS->getValue().isNegative())
3260           hasNegative = true;
3261
3262     if (hasNegative) {
3263       std::vector<Constant *> Elts(VWidth);
3264       for (unsigned i = 0; i != VWidth; ++i) {
3265         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3266           if (RHS->getValue().isNegative())
3267             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3268           else
3269             Elts[i] = RHS;
3270         }
3271       }
3272
3273       Constant *NewRHSV = ConstantVector::get(Elts);
3274       if (NewRHSV != RHSV) {
3275         AddUsesToWorkList(I);
3276         I.setOperand(1, NewRHSV);
3277         return &I;
3278       }
3279     }
3280   }
3281
3282   return 0;
3283 }
3284
3285 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3286   return commonRemTransforms(I);
3287 }
3288
3289 // isOneBitSet - Return true if there is exactly one bit set in the specified
3290 // constant.
3291 static bool isOneBitSet(const ConstantInt *CI) {
3292   return CI->getValue().isPowerOf2();
3293 }
3294
3295 // isHighOnes - Return true if the constant is of the form 1+0+.
3296 // This is the same as lowones(~X).
3297 static bool isHighOnes(const ConstantInt *CI) {
3298   return (~CI->getValue() + 1).isPowerOf2();
3299 }
3300
3301 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3302 /// are carefully arranged to allow folding of expressions such as:
3303 ///
3304 ///      (A < B) | (A > B) --> (A != B)
3305 ///
3306 /// Note that this is only valid if the first and second predicates have the
3307 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3308 ///
3309 /// Three bits are used to represent the condition, as follows:
3310 ///   0  A > B
3311 ///   1  A == B
3312 ///   2  A < B
3313 ///
3314 /// <=>  Value  Definition
3315 /// 000     0   Always false
3316 /// 001     1   A >  B
3317 /// 010     2   A == B
3318 /// 011     3   A >= B
3319 /// 100     4   A <  B
3320 /// 101     5   A != B
3321 /// 110     6   A <= B
3322 /// 111     7   Always true
3323 ///  
3324 static unsigned getICmpCode(const ICmpInst *ICI) {
3325   switch (ICI->getPredicate()) {
3326     // False -> 0
3327   case ICmpInst::ICMP_UGT: return 1;  // 001
3328   case ICmpInst::ICMP_SGT: return 1;  // 001
3329   case ICmpInst::ICMP_EQ:  return 2;  // 010
3330   case ICmpInst::ICMP_UGE: return 3;  // 011
3331   case ICmpInst::ICMP_SGE: return 3;  // 011
3332   case ICmpInst::ICMP_ULT: return 4;  // 100
3333   case ICmpInst::ICMP_SLT: return 4;  // 100
3334   case ICmpInst::ICMP_NE:  return 5;  // 101
3335   case ICmpInst::ICMP_ULE: return 6;  // 110
3336   case ICmpInst::ICMP_SLE: return 6;  // 110
3337     // True -> 7
3338   default:
3339     assert(0 && "Invalid ICmp predicate!");
3340     return 0;
3341   }
3342 }
3343
3344 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3345 /// predicate into a three bit mask. It also returns whether it is an ordered
3346 /// predicate by reference.
3347 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3348   isOrdered = false;
3349   switch (CC) {
3350   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3351   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3352   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3353   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3354   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3355   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3356   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3357   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3358   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3359   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3360   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3361   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3362   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3363   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3364     // True -> 7
3365   default:
3366     // Not expecting FCMP_FALSE and FCMP_TRUE;
3367     assert(0 && "Unexpected FCmp predicate!");
3368     return 0;
3369   }
3370 }
3371
3372 /// getICmpValue - This is the complement of getICmpCode, which turns an
3373 /// opcode and two operands into either a constant true or false, or a brand 
3374 /// new ICmp instruction. The sign is passed in to determine which kind
3375 /// of predicate to use in the new icmp instruction.
3376 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3377   switch (code) {
3378   default: assert(0 && "Illegal ICmp code!");
3379   case  0: return ConstantInt::getFalse();
3380   case  1: 
3381     if (sign)
3382       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3383     else
3384       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3385   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3386   case  3: 
3387     if (sign)
3388       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3389     else
3390       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3391   case  4: 
3392     if (sign)
3393       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3394     else
3395       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3396   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3397   case  6: 
3398     if (sign)
3399       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3400     else
3401       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3402   case  7: return ConstantInt::getTrue();
3403   }
3404 }
3405
3406 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3407 /// opcode and two operands into either a FCmp instruction. isordered is passed
3408 /// in to determine which kind of predicate to use in the new fcmp instruction.
3409 static Value *getFCmpValue(bool isordered, unsigned code,
3410                            Value *LHS, Value *RHS) {
3411   switch (code) {
3412   default: assert(0 && "Illegal FCmp code!");
3413   case  0:
3414     if (isordered)
3415       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3416     else
3417       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3418   case  1: 
3419     if (isordered)
3420       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3421     else
3422       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3423   case  2: 
3424     if (isordered)
3425       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3426     else
3427       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3428   case  3: 
3429     if (isordered)
3430       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3431     else
3432       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3433   case  4: 
3434     if (isordered)
3435       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3436     else
3437       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3438   case  5: 
3439     if (isordered)
3440       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3441     else
3442       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3443   case  6: 
3444     if (isordered)
3445       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3446     else
3447       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3448   case  7: return ConstantInt::getTrue();
3449   }
3450 }
3451
3452 /// PredicatesFoldable - Return true if both predicates match sign or if at
3453 /// least one of them is an equality comparison (which is signless).
3454 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3455   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3456          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3457          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3458 }
3459
3460 namespace { 
3461 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3462 struct FoldICmpLogical {
3463   InstCombiner &IC;
3464   Value *LHS, *RHS;
3465   ICmpInst::Predicate pred;
3466   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3467     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3468       pred(ICI->getPredicate()) {}
3469   bool shouldApply(Value *V) const {
3470     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3471       if (PredicatesFoldable(pred, ICI->getPredicate()))
3472         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3473                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3474     return false;
3475   }
3476   Instruction *apply(Instruction &Log) const {
3477     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3478     if (ICI->getOperand(0) != LHS) {
3479       assert(ICI->getOperand(1) == LHS);
3480       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3481     }
3482
3483     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3484     unsigned LHSCode = getICmpCode(ICI);
3485     unsigned RHSCode = getICmpCode(RHSICI);
3486     unsigned Code;
3487     switch (Log.getOpcode()) {
3488     case Instruction::And: Code = LHSCode & RHSCode; break;
3489     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3490     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3491     default: assert(0 && "Illegal logical opcode!"); return 0;
3492     }
3493
3494     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3495                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3496       
3497     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3498     if (Instruction *I = dyn_cast<Instruction>(RV))
3499       return I;
3500     // Otherwise, it's a constant boolean value...
3501     return IC.ReplaceInstUsesWith(Log, RV);
3502   }
3503 };
3504 } // end anonymous namespace
3505
3506 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3507 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3508 // guaranteed to be a binary operator.
3509 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3510                                     ConstantInt *OpRHS,
3511                                     ConstantInt *AndRHS,
3512                                     BinaryOperator &TheAnd) {
3513   Value *X = Op->getOperand(0);
3514   Constant *Together = 0;
3515   if (!Op->isShift())
3516     Together = And(AndRHS, OpRHS);
3517
3518   switch (Op->getOpcode()) {
3519   case Instruction::Xor:
3520     if (Op->hasOneUse()) {
3521       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3522       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3523       InsertNewInstBefore(And, TheAnd);
3524       And->takeName(Op);
3525       return BinaryOperator::CreateXor(And, Together);
3526     }
3527     break;
3528   case Instruction::Or:
3529     if (Together == AndRHS) // (X | C) & C --> C
3530       return ReplaceInstUsesWith(TheAnd, AndRHS);
3531
3532     if (Op->hasOneUse() && Together != OpRHS) {
3533       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3534       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3535       InsertNewInstBefore(Or, TheAnd);
3536       Or->takeName(Op);
3537       return BinaryOperator::CreateAnd(Or, AndRHS);
3538     }
3539     break;
3540   case Instruction::Add:
3541     if (Op->hasOneUse()) {
3542       // Adding a one to a single bit bit-field should be turned into an XOR
3543       // of the bit.  First thing to check is to see if this AND is with a
3544       // single bit constant.
3545       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3546
3547       // If there is only one bit set...
3548       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3549         // Ok, at this point, we know that we are masking the result of the
3550         // ADD down to exactly one bit.  If the constant we are adding has
3551         // no bits set below this bit, then we can eliminate the ADD.
3552         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3553
3554         // Check to see if any bits below the one bit set in AndRHSV are set.
3555         if ((AddRHS & (AndRHSV-1)) == 0) {
3556           // If not, the only thing that can effect the output of the AND is
3557           // the bit specified by AndRHSV.  If that bit is set, the effect of
3558           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3559           // no effect.
3560           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3561             TheAnd.setOperand(0, X);
3562             return &TheAnd;
3563           } else {
3564             // Pull the XOR out of the AND.
3565             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3566             InsertNewInstBefore(NewAnd, TheAnd);
3567             NewAnd->takeName(Op);
3568             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3569           }
3570         }
3571       }
3572     }
3573     break;
3574
3575   case Instruction::Shl: {
3576     // We know that the AND will not produce any of the bits shifted in, so if
3577     // the anded constant includes them, clear them now!
3578     //
3579     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3580     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3581     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3582     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3583
3584     if (CI->getValue() == ShlMask) { 
3585     // Masking out bits that the shift already masks
3586       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3587     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3588       TheAnd.setOperand(1, CI);
3589       return &TheAnd;
3590     }
3591     break;
3592   }
3593   case Instruction::LShr:
3594   {
3595     // We know that the AND will not produce any of the bits shifted in, so if
3596     // the anded constant includes them, clear them now!  This only applies to
3597     // unsigned shifts, because a signed shr may bring in set bits!
3598     //
3599     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3600     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3601     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3602     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3603
3604     if (CI->getValue() == ShrMask) {   
3605     // Masking out bits that the shift already masks.
3606       return ReplaceInstUsesWith(TheAnd, Op);
3607     } else if (CI != AndRHS) {
3608       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3609       return &TheAnd;
3610     }
3611     break;
3612   }
3613   case Instruction::AShr:
3614     // Signed shr.
3615     // See if this is shifting in some sign extension, then masking it out
3616     // with an and.
3617     if (Op->hasOneUse()) {
3618       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3619       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3620       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3621       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3622       if (C == AndRHS) {          // Masking out bits shifted in.
3623         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3624         // Make the argument unsigned.
3625         Value *ShVal = Op->getOperand(0);
3626         ShVal = InsertNewInstBefore(
3627             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3628                                    Op->getName()), TheAnd);
3629         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3630       }
3631     }
3632     break;
3633   }
3634   return 0;
3635 }
3636
3637
3638 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3639 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3640 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3641 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3642 /// insert new instructions.
3643 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3644                                            bool isSigned, bool Inside, 
3645                                            Instruction &IB) {
3646   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3647             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3648          "Lo is not <= Hi in range emission code!");
3649     
3650   if (Inside) {
3651     if (Lo == Hi)  // Trivially false.
3652       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3653
3654     // V >= Min && V < Hi --> V < Hi
3655     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3656       ICmpInst::Predicate pred = (isSigned ? 
3657         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3658       return new ICmpInst(pred, V, Hi);
3659     }
3660
3661     // Emit V-Lo <u Hi-Lo
3662     Constant *NegLo = ConstantExpr::getNeg(Lo);
3663     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3664     InsertNewInstBefore(Add, IB);
3665     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3666     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3667   }
3668
3669   if (Lo == Hi)  // Trivially true.
3670     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3671
3672   // V < Min || V >= Hi -> V > Hi-1
3673   Hi = SubOne(cast<ConstantInt>(Hi));
3674   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3675     ICmpInst::Predicate pred = (isSigned ? 
3676         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3677     return new ICmpInst(pred, V, Hi);
3678   }
3679
3680   // Emit V-Lo >u Hi-1-Lo
3681   // Note that Hi has already had one subtracted from it, above.
3682   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3683   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3684   InsertNewInstBefore(Add, IB);
3685   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3686   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3687 }
3688
3689 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3690 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3691 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3692 // not, since all 1s are not contiguous.
3693 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3694   const APInt& V = Val->getValue();
3695   uint32_t BitWidth = Val->getType()->getBitWidth();
3696   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3697
3698   // look for the first zero bit after the run of ones
3699   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3700   // look for the first non-zero bit
3701   ME = V.getActiveBits(); 
3702   return true;
3703 }
3704
3705 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3706 /// where isSub determines whether the operator is a sub.  If we can fold one of
3707 /// the following xforms:
3708 /// 
3709 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3710 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3711 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3712 ///
3713 /// return (A +/- B).
3714 ///
3715 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3716                                         ConstantInt *Mask, bool isSub,
3717                                         Instruction &I) {
3718   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3719   if (!LHSI || LHSI->getNumOperands() != 2 ||
3720       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3721
3722   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3723
3724   switch (LHSI->getOpcode()) {
3725   default: return 0;
3726   case Instruction::And:
3727     if (And(N, Mask) == Mask) {
3728       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3729       if ((Mask->getValue().countLeadingZeros() + 
3730            Mask->getValue().countPopulation()) == 
3731           Mask->getValue().getBitWidth())
3732         break;
3733
3734       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3735       // part, we don't need any explicit masks to take them out of A.  If that
3736       // is all N is, ignore it.
3737       uint32_t MB = 0, ME = 0;
3738       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3739         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3740         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3741         if (MaskedValueIsZero(RHS, Mask))
3742           break;
3743       }
3744     }
3745     return 0;
3746   case Instruction::Or:
3747   case Instruction::Xor:
3748     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3749     if ((Mask->getValue().countLeadingZeros() + 
3750          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3751         && And(N, Mask)->isZero())
3752       break;
3753     return 0;
3754   }
3755   
3756   Instruction *New;
3757   if (isSub)
3758     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3759   else
3760     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3761   return InsertNewInstBefore(New, I);
3762 }
3763
3764 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3765 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3766                                           ICmpInst *LHS, ICmpInst *RHS) {
3767   Value *Val, *Val2;
3768   ConstantInt *LHSCst, *RHSCst;
3769   ICmpInst::Predicate LHSCC, RHSCC;
3770   
3771   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3772   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
3773       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
3774     return 0;
3775   
3776   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3777   // where C is a power of 2
3778   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3779       LHSCst->getValue().isPowerOf2()) {
3780     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3781     InsertNewInstBefore(NewOr, I);
3782     return new ICmpInst(LHSCC, NewOr, LHSCst);
3783   }
3784   
3785   // From here on, we only handle:
3786   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3787   if (Val != Val2) return 0;
3788   
3789   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3790   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3791       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3792       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3793       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3794     return 0;
3795   
3796   // We can't fold (ugt x, C) & (sgt x, C2).
3797   if (!PredicatesFoldable(LHSCC, RHSCC))
3798     return 0;
3799     
3800   // Ensure that the larger constant is on the RHS.
3801   bool ShouldSwap;
3802   if (ICmpInst::isSignedPredicate(LHSCC) ||
3803       (ICmpInst::isEquality(LHSCC) && 
3804        ICmpInst::isSignedPredicate(RHSCC)))
3805     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3806   else
3807     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3808     
3809   if (ShouldSwap) {
3810     std::swap(LHS, RHS);
3811     std::swap(LHSCst, RHSCst);
3812     std::swap(LHSCC, RHSCC);
3813   }
3814
3815   // At this point, we know we have have two icmp instructions
3816   // comparing a value against two constants and and'ing the result
3817   // together.  Because of the above check, we know that we only have
3818   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3819   // (from the FoldICmpLogical check above), that the two constants 
3820   // are not equal and that the larger constant is on the RHS
3821   assert(LHSCst != RHSCst && "Compares not folded above?");
3822
3823   switch (LHSCC) {
3824   default: assert(0 && "Unknown integer condition code!");
3825   case ICmpInst::ICMP_EQ:
3826     switch (RHSCC) {
3827     default: assert(0 && "Unknown integer condition code!");
3828     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3829     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3830     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3831       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3832     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3833     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3834     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3835       return ReplaceInstUsesWith(I, LHS);
3836     }
3837   case ICmpInst::ICMP_NE:
3838     switch (RHSCC) {
3839     default: assert(0 && "Unknown integer condition code!");
3840     case ICmpInst::ICMP_ULT:
3841       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3842         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3843       break;                        // (X != 13 & X u< 15) -> no change
3844     case ICmpInst::ICMP_SLT:
3845       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3846         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3847       break;                        // (X != 13 & X s< 15) -> no change
3848     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3849     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3850     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3851       return ReplaceInstUsesWith(I, RHS);
3852     case ICmpInst::ICMP_NE:
3853       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3854         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3855         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3856                                                      Val->getName()+".off");
3857         InsertNewInstBefore(Add, I);
3858         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3859                             ConstantInt::get(Add->getType(), 1));
3860       }
3861       break;                        // (X != 13 & X != 15) -> no change
3862     }
3863     break;
3864   case ICmpInst::ICMP_ULT:
3865     switch (RHSCC) {
3866     default: assert(0 && "Unknown integer condition code!");
3867     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3868     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3869       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3870     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3871       break;
3872     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3873     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3874       return ReplaceInstUsesWith(I, LHS);
3875     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3876       break;
3877     }
3878     break;
3879   case ICmpInst::ICMP_SLT:
3880     switch (RHSCC) {
3881     default: assert(0 && "Unknown integer condition code!");
3882     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3883     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3884       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3885     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3886       break;
3887     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3888     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3889       return ReplaceInstUsesWith(I, LHS);
3890     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3891       break;
3892     }
3893     break;
3894   case ICmpInst::ICMP_UGT:
3895     switch (RHSCC) {
3896     default: assert(0 && "Unknown integer condition code!");
3897     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3898     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3899       return ReplaceInstUsesWith(I, RHS);
3900     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3901       break;
3902     case ICmpInst::ICMP_NE:
3903       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3904         return new ICmpInst(LHSCC, Val, RHSCst);
3905       break;                        // (X u> 13 & X != 15) -> no change
3906     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3907       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3908     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3909       break;
3910     }
3911     break;
3912   case ICmpInst::ICMP_SGT:
3913     switch (RHSCC) {
3914     default: assert(0 && "Unknown integer condition code!");
3915     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3916     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3917       return ReplaceInstUsesWith(I, RHS);
3918     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3919       break;
3920     case ICmpInst::ICMP_NE:
3921       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3922         return new ICmpInst(LHSCC, Val, RHSCst);
3923       break;                        // (X s> 13 & X != 15) -> no change
3924     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3925       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3926     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3927       break;
3928     }
3929     break;
3930   }
3931  
3932   return 0;
3933 }
3934
3935
3936 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3937   bool Changed = SimplifyCommutative(I);
3938   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3939
3940   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3941     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3942
3943   // and X, X = X
3944   if (Op0 == Op1)
3945     return ReplaceInstUsesWith(I, Op1);
3946
3947   // See if we can simplify any instructions used by the instruction whose sole 
3948   // purpose is to compute bits we don't care about.
3949   if (!isa<VectorType>(I.getType())) {
3950     if (SimplifyDemandedInstructionBits(I))
3951       return &I;
3952   } else {
3953     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3954       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3955         return ReplaceInstUsesWith(I, I.getOperand(0));
3956     } else if (isa<ConstantAggregateZero>(Op1)) {
3957       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3958     }
3959   }
3960   
3961   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3962     const APInt& AndRHSMask = AndRHS->getValue();
3963     APInt NotAndRHS(~AndRHSMask);
3964
3965     // Optimize a variety of ((val OP C1) & C2) combinations...
3966     if (isa<BinaryOperator>(Op0)) {
3967       Instruction *Op0I = cast<Instruction>(Op0);
3968       Value *Op0LHS = Op0I->getOperand(0);
3969       Value *Op0RHS = Op0I->getOperand(1);
3970       switch (Op0I->getOpcode()) {
3971       case Instruction::Xor:
3972       case Instruction::Or:
3973         // If the mask is only needed on one incoming arm, push it up.
3974         if (Op0I->hasOneUse()) {
3975           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3976             // Not masking anything out for the LHS, move to RHS.
3977             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3978                                                    Op0RHS->getName()+".masked");
3979             InsertNewInstBefore(NewRHS, I);
3980             return BinaryOperator::Create(
3981                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3982           }
3983           if (!isa<Constant>(Op0RHS) &&
3984               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3985             // Not masking anything out for the RHS, move to LHS.
3986             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3987                                                    Op0LHS->getName()+".masked");
3988             InsertNewInstBefore(NewLHS, I);
3989             return BinaryOperator::Create(
3990                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3991           }
3992         }
3993
3994         break;
3995       case Instruction::Add:
3996         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3997         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3998         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3999         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4000           return BinaryOperator::CreateAnd(V, AndRHS);
4001         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4002           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4003         break;
4004
4005       case Instruction::Sub:
4006         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4007         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4008         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4009         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4010           return BinaryOperator::CreateAnd(V, AndRHS);
4011
4012         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4013         // has 1's for all bits that the subtraction with A might affect.
4014         if (Op0I->hasOneUse()) {
4015           uint32_t BitWidth = AndRHSMask.getBitWidth();
4016           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4017           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4018
4019           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4020           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4021               MaskedValueIsZero(Op0LHS, Mask)) {
4022             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
4023             InsertNewInstBefore(NewNeg, I);
4024             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4025           }
4026         }
4027         break;
4028
4029       case Instruction::Shl:
4030       case Instruction::LShr:
4031         // (1 << x) & 1 --> zext(x == 0)
4032         // (1 >> x) & 1 --> zext(x == 0)
4033         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4034           Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
4035                                            Constant::getNullValue(I.getType()));
4036           InsertNewInstBefore(NewICmp, I);
4037           return new ZExtInst(NewICmp, I.getType());
4038         }
4039         break;
4040       }
4041
4042       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4043         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4044           return Res;
4045     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4046       // If this is an integer truncation or change from signed-to-unsigned, and
4047       // if the source is an and/or with immediate, transform it.  This
4048       // frequently occurs for bitfield accesses.
4049       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4050         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4051             CastOp->getNumOperands() == 2)
4052           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4053             if (CastOp->getOpcode() == Instruction::And) {
4054               // Change: and (cast (and X, C1) to T), C2
4055               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4056               // This will fold the two constants together, which may allow 
4057               // other simplifications.
4058               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4059                 CastOp->getOperand(0), I.getType(), 
4060                 CastOp->getName()+".shrunk");
4061               NewCast = InsertNewInstBefore(NewCast, I);
4062               // trunc_or_bitcast(C1)&C2
4063               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4064               C3 = ConstantExpr::getAnd(C3, AndRHS);
4065               return BinaryOperator::CreateAnd(NewCast, C3);
4066             } else if (CastOp->getOpcode() == Instruction::Or) {
4067               // Change: and (cast (or X, C1) to T), C2
4068               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4069               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4070               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
4071                 return ReplaceInstUsesWith(I, AndRHS);
4072             }
4073           }
4074       }
4075     }
4076
4077     // Try to fold constant and into select arguments.
4078     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4079       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4080         return R;
4081     if (isa<PHINode>(Op0))
4082       if (Instruction *NV = FoldOpIntoPhi(I))
4083         return NV;
4084   }
4085
4086   Value *Op0NotVal = dyn_castNotVal(Op0);
4087   Value *Op1NotVal = dyn_castNotVal(Op1);
4088
4089   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4090     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4091
4092   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4093   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4094     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4095                                                I.getName()+".demorgan");
4096     InsertNewInstBefore(Or, I);
4097     return BinaryOperator::CreateNot(Or);
4098   }
4099   
4100   {
4101     Value *A = 0, *B = 0, *C = 0, *D = 0;
4102     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4103       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4104         return ReplaceInstUsesWith(I, Op1);
4105     
4106       // (A|B) & ~(A&B) -> A^B
4107       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4108         if ((A == C && B == D) || (A == D && B == C))
4109           return BinaryOperator::CreateXor(A, B);
4110       }
4111     }
4112     
4113     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4114       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4115         return ReplaceInstUsesWith(I, Op0);
4116
4117       // ~(A&B) & (A|B) -> A^B
4118       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4119         if ((A == C && B == D) || (A == D && B == C))
4120           return BinaryOperator::CreateXor(A, B);
4121       }
4122     }
4123     
4124     if (Op0->hasOneUse() &&
4125         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4126       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4127         I.swapOperands();     // Simplify below
4128         std::swap(Op0, Op1);
4129       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4130         cast<BinaryOperator>(Op0)->swapOperands();
4131         I.swapOperands();     // Simplify below
4132         std::swap(Op0, Op1);
4133       }
4134     }
4135
4136     if (Op1->hasOneUse() &&
4137         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4138       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4139         cast<BinaryOperator>(Op1)->swapOperands();
4140         std::swap(A, B);
4141       }
4142       if (A == Op0) {                                // A&(A^B) -> A & ~B
4143         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
4144         InsertNewInstBefore(NotB, I);
4145         return BinaryOperator::CreateAnd(A, NotB);
4146       }
4147     }
4148
4149     // (A&((~A)|B)) -> A&B
4150     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4151         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4152       return BinaryOperator::CreateAnd(A, Op1);
4153     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4154         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4155       return BinaryOperator::CreateAnd(A, Op0);
4156   }
4157   
4158   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4159     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4160     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4161       return R;
4162
4163     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4164       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4165         return Res;
4166   }
4167
4168   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4169   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4170     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4171       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4172         const Type *SrcTy = Op0C->getOperand(0)->getType();
4173         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4174             // Only do this if the casts both really cause code to be generated.
4175             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4176                               I.getType(), TD) &&
4177             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4178                               I.getType(), TD)) {
4179           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4180                                                          Op1C->getOperand(0),
4181                                                          I.getName());
4182           InsertNewInstBefore(NewOp, I);
4183           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4184         }
4185       }
4186     
4187   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4188   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4189     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4190       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4191           SI0->getOperand(1) == SI1->getOperand(1) &&
4192           (SI0->hasOneUse() || SI1->hasOneUse())) {
4193         Instruction *NewOp =
4194           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4195                                                         SI1->getOperand(0),
4196                                                         SI0->getName()), I);
4197         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4198                                       SI1->getOperand(1));
4199       }
4200   }
4201
4202   // If and'ing two fcmp, try combine them into one.
4203   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4204     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4205       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4206           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4207         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4208         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4209           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4210             // If either of the constants are nans, then the whole thing returns
4211             // false.
4212             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4213               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4214             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4215                                 RHS->getOperand(0));
4216           }
4217       } else {
4218         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4219         FCmpInst::Predicate Op0CC, Op1CC;
4220         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4221             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4222           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4223             // Swap RHS operands to match LHS.
4224             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4225             std::swap(Op1LHS, Op1RHS);
4226           }
4227           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4228             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4229             if (Op0CC == Op1CC)
4230               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4231             else if (Op0CC == FCmpInst::FCMP_FALSE ||
4232                      Op1CC == FCmpInst::FCMP_FALSE)
4233               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4234             else if (Op0CC == FCmpInst::FCMP_TRUE)
4235               return ReplaceInstUsesWith(I, Op1);
4236             else if (Op1CC == FCmpInst::FCMP_TRUE)
4237               return ReplaceInstUsesWith(I, Op0);
4238             bool Op0Ordered;
4239             bool Op1Ordered;
4240             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4241             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4242             if (Op1Pred == 0) {
4243               std::swap(Op0, Op1);
4244               std::swap(Op0Pred, Op1Pred);
4245               std::swap(Op0Ordered, Op1Ordered);
4246             }
4247             if (Op0Pred == 0) {
4248               // uno && ueq -> uno && (uno || eq) -> ueq
4249               // ord && olt -> ord && (ord && lt) -> olt
4250               if (Op0Ordered == Op1Ordered)
4251                 return ReplaceInstUsesWith(I, Op1);
4252               // uno && oeq -> uno && (ord && eq) -> false
4253               // uno && ord -> false
4254               if (!Op0Ordered)
4255                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4256               // ord && ueq -> ord && (uno || eq) -> oeq
4257               return cast<Instruction>(getFCmpValue(true, Op1Pred,
4258                                                     Op0LHS, Op0RHS));
4259             }
4260           }
4261         }
4262       }
4263     }
4264   }
4265
4266   return Changed ? &I : 0;
4267 }
4268
4269 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4270 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4271 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4272 /// the expression came from the corresponding "byte swapped" byte in some other
4273 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4274 /// we know that the expression deposits the low byte of %X into the high byte
4275 /// of the bswap result and that all other bytes are zero.  This expression is
4276 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4277 /// match.
4278 ///
4279 /// This function returns true if the match was unsuccessful and false if so.
4280 /// On entry to the function the "OverallLeftShift" is a signed integer value
4281 /// indicating the number of bytes that the subexpression is later shifted.  For
4282 /// example, if the expression is later right shifted by 16 bits, the
4283 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4284 /// byte of ByteValues is actually being set.
4285 ///
4286 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4287 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4288 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4289 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4290 /// always in the local (OverallLeftShift) coordinate space.
4291 ///
4292 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4293                               SmallVector<Value*, 8> &ByteValues) {
4294   if (Instruction *I = dyn_cast<Instruction>(V)) {
4295     // If this is an or instruction, it may be an inner node of the bswap.
4296     if (I->getOpcode() == Instruction::Or) {
4297       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4298                                ByteValues) ||
4299              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4300                                ByteValues);
4301     }
4302   
4303     // If this is a logical shift by a constant multiple of 8, recurse with
4304     // OverallLeftShift and ByteMask adjusted.
4305     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4306       unsigned ShAmt = 
4307         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4308       // Ensure the shift amount is defined and of a byte value.
4309       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4310         return true;
4311
4312       unsigned ByteShift = ShAmt >> 3;
4313       if (I->getOpcode() == Instruction::Shl) {
4314         // X << 2 -> collect(X, +2)
4315         OverallLeftShift += ByteShift;
4316         ByteMask >>= ByteShift;
4317       } else {
4318         // X >>u 2 -> collect(X, -2)
4319         OverallLeftShift -= ByteShift;
4320         ByteMask <<= ByteShift;
4321         ByteMask &= (~0U >> (32-ByteValues.size()));
4322       }
4323
4324       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4325       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4326
4327       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4328                                ByteValues);
4329     }
4330
4331     // If this is a logical 'and' with a mask that clears bytes, clear the
4332     // corresponding bytes in ByteMask.
4333     if (I->getOpcode() == Instruction::And &&
4334         isa<ConstantInt>(I->getOperand(1))) {
4335       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4336       unsigned NumBytes = ByteValues.size();
4337       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4338       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4339       
4340       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4341         // If this byte is masked out by a later operation, we don't care what
4342         // the and mask is.
4343         if ((ByteMask & (1 << i)) == 0)
4344           continue;
4345         
4346         // If the AndMask is all zeros for this byte, clear the bit.
4347         APInt MaskB = AndMask & Byte;
4348         if (MaskB == 0) {
4349           ByteMask &= ~(1U << i);
4350           continue;
4351         }
4352         
4353         // If the AndMask is not all ones for this byte, it's not a bytezap.
4354         if (MaskB != Byte)
4355           return true;
4356
4357         // Otherwise, this byte is kept.
4358       }
4359
4360       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4361                                ByteValues);
4362     }
4363   }
4364   
4365   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4366   // the input value to the bswap.  Some observations: 1) if more than one byte
4367   // is demanded from this input, then it could not be successfully assembled
4368   // into a byteswap.  At least one of the two bytes would not be aligned with
4369   // their ultimate destination.
4370   if (!isPowerOf2_32(ByteMask)) return true;
4371   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4372   
4373   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4374   // is demanded, it needs to go into byte 0 of the result.  This means that the
4375   // byte needs to be shifted until it lands in the right byte bucket.  The
4376   // shift amount depends on the position: if the byte is coming from the high
4377   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4378   // low part, it must be shifted left.
4379   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4380   if (InputByteNo < ByteValues.size()/2) {
4381     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4382       return true;
4383   } else {
4384     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4385       return true;
4386   }
4387   
4388   // If the destination byte value is already defined, the values are or'd
4389   // together, which isn't a bswap (unless it's an or of the same bits).
4390   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4391     return true;
4392   ByteValues[DestByteNo] = V;
4393   return false;
4394 }
4395
4396 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4397 /// If so, insert the new bswap intrinsic and return it.
4398 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4399   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4400   if (!ITy || ITy->getBitWidth() % 16 || 
4401       // ByteMask only allows up to 32-byte values.
4402       ITy->getBitWidth() > 32*8) 
4403     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4404   
4405   /// ByteValues - For each byte of the result, we keep track of which value
4406   /// defines each byte.
4407   SmallVector<Value*, 8> ByteValues;
4408   ByteValues.resize(ITy->getBitWidth()/8);
4409     
4410   // Try to find all the pieces corresponding to the bswap.
4411   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4412   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4413     return 0;
4414   
4415   // Check to see if all of the bytes come from the same value.
4416   Value *V = ByteValues[0];
4417   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4418   
4419   // Check to make sure that all of the bytes come from the same value.
4420   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4421     if (ByteValues[i] != V)
4422       return 0;
4423   const Type *Tys[] = { ITy };
4424   Module *M = I.getParent()->getParent()->getParent();
4425   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4426   return CallInst::Create(F, V);
4427 }
4428
4429 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4430 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4431 /// we can simplify this expression to "cond ? C : D or B".
4432 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4433                                          Value *C, Value *D) {
4434   // If A is not a select of -1/0, this cannot match.
4435   Value *Cond = 0;
4436   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4437     return 0;
4438
4439   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4440   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4441     return SelectInst::Create(Cond, C, B);
4442   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4443     return SelectInst::Create(Cond, C, B);
4444   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4445   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4446     return SelectInst::Create(Cond, C, D);
4447   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4448     return SelectInst::Create(Cond, C, D);
4449   return 0;
4450 }
4451
4452 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4453 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4454                                          ICmpInst *LHS, ICmpInst *RHS) {
4455   Value *Val, *Val2;
4456   ConstantInt *LHSCst, *RHSCst;
4457   ICmpInst::Predicate LHSCC, RHSCC;
4458   
4459   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4460   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4461       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4462     return 0;
4463   
4464   // From here on, we only handle:
4465   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4466   if (Val != Val2) return 0;
4467   
4468   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4469   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4470       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4471       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4472       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4473     return 0;
4474   
4475   // We can't fold (ugt x, C) | (sgt x, C2).
4476   if (!PredicatesFoldable(LHSCC, RHSCC))
4477     return 0;
4478   
4479   // Ensure that the larger constant is on the RHS.
4480   bool ShouldSwap;
4481   if (ICmpInst::isSignedPredicate(LHSCC) ||
4482       (ICmpInst::isEquality(LHSCC) && 
4483        ICmpInst::isSignedPredicate(RHSCC)))
4484     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4485   else
4486     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4487   
4488   if (ShouldSwap) {
4489     std::swap(LHS, RHS);
4490     std::swap(LHSCst, RHSCst);
4491     std::swap(LHSCC, RHSCC);
4492   }
4493   
4494   // At this point, we know we have have two icmp instructions
4495   // comparing a value against two constants and or'ing the result
4496   // together.  Because of the above check, we know that we only have
4497   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4498   // FoldICmpLogical check above), that the two constants are not
4499   // equal.
4500   assert(LHSCst != RHSCst && "Compares not folded above?");
4501
4502   switch (LHSCC) {
4503   default: assert(0 && "Unknown integer condition code!");
4504   case ICmpInst::ICMP_EQ:
4505     switch (RHSCC) {
4506     default: assert(0 && "Unknown integer condition code!");
4507     case ICmpInst::ICMP_EQ:
4508       if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4509         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4510         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4511                                                      Val->getName()+".off");
4512         InsertNewInstBefore(Add, I);
4513         AddCST = Subtract(AddOne(RHSCst), LHSCst);
4514         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4515       }
4516       break;                         // (X == 13 | X == 15) -> no change
4517     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4518     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4519       break;
4520     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4521     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4522     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4523       return ReplaceInstUsesWith(I, RHS);
4524     }
4525     break;
4526   case ICmpInst::ICMP_NE:
4527     switch (RHSCC) {
4528     default: assert(0 && "Unknown integer condition code!");
4529     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4530     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4531     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4532       return ReplaceInstUsesWith(I, LHS);
4533     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4534     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4535     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4536       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4537     }
4538     break;
4539   case ICmpInst::ICMP_ULT:
4540     switch (RHSCC) {
4541     default: assert(0 && "Unknown integer condition code!");
4542     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4543       break;
4544     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4545       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4546       // this can cause overflow.
4547       if (RHSCst->isMaxValue(false))
4548         return ReplaceInstUsesWith(I, LHS);
4549       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4550     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4551       break;
4552     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4553     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4554       return ReplaceInstUsesWith(I, RHS);
4555     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4556       break;
4557     }
4558     break;
4559   case ICmpInst::ICMP_SLT:
4560     switch (RHSCC) {
4561     default: assert(0 && "Unknown integer condition code!");
4562     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4563       break;
4564     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4565       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4566       // this can cause overflow.
4567       if (RHSCst->isMaxValue(true))
4568         return ReplaceInstUsesWith(I, LHS);
4569       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4570     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4571       break;
4572     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4573     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4574       return ReplaceInstUsesWith(I, RHS);
4575     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4576       break;
4577     }
4578     break;
4579   case ICmpInst::ICMP_UGT:
4580     switch (RHSCC) {
4581     default: assert(0 && "Unknown integer condition code!");
4582     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4583     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4584       return ReplaceInstUsesWith(I, LHS);
4585     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4586       break;
4587     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4588     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4589       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4590     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4591       break;
4592     }
4593     break;
4594   case ICmpInst::ICMP_SGT:
4595     switch (RHSCC) {
4596     default: assert(0 && "Unknown integer condition code!");
4597     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4598     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4599       return ReplaceInstUsesWith(I, LHS);
4600     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4601       break;
4602     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4603     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4604       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4605     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4606       break;
4607     }
4608     break;
4609   }
4610   return 0;
4611 }
4612
4613 /// FoldOrWithConstants - This helper function folds:
4614 ///
4615 ///     ((A | B) & C1) | (B & C2)
4616 ///
4617 /// into:
4618 /// 
4619 ///     (A & C1) | B
4620 ///
4621 /// when the XOR of the two constants is "all ones" (-1).
4622 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4623                                                Value *A, Value *B, Value *C) {
4624   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4625   if (!CI1) return 0;
4626
4627   Value *V1 = 0;
4628   ConstantInt *CI2 = 0;
4629   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4630
4631   APInt Xor = CI1->getValue() ^ CI2->getValue();
4632   if (!Xor.isAllOnesValue()) return 0;
4633
4634   if (V1 == A || V1 == B) {
4635     Instruction *NewOp =
4636       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4637     return BinaryOperator::CreateOr(NewOp, V1);
4638   }
4639
4640   return 0;
4641 }
4642
4643 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4644   bool Changed = SimplifyCommutative(I);
4645   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4646
4647   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4648     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4649
4650   // or X, X = X
4651   if (Op0 == Op1)
4652     return ReplaceInstUsesWith(I, Op0);
4653
4654   // See if we can simplify any instructions used by the instruction whose sole 
4655   // purpose is to compute bits we don't care about.
4656   if (!isa<VectorType>(I.getType())) {
4657     if (SimplifyDemandedInstructionBits(I))
4658       return &I;
4659   } else if (isa<ConstantAggregateZero>(Op1)) {
4660     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4661   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4662     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4663       return ReplaceInstUsesWith(I, I.getOperand(1));
4664   }
4665     
4666
4667   
4668   // or X, -1 == -1
4669   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4670     ConstantInt *C1 = 0; Value *X = 0;
4671     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4672     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4673       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4674       InsertNewInstBefore(Or, I);
4675       Or->takeName(Op0);
4676       return BinaryOperator::CreateAnd(Or, 
4677                ConstantInt::get(RHS->getValue() | C1->getValue()));
4678     }
4679
4680     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4681     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4682       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4683       InsertNewInstBefore(Or, I);
4684       Or->takeName(Op0);
4685       return BinaryOperator::CreateXor(Or,
4686                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4687     }
4688
4689     // Try to fold constant and into select arguments.
4690     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4691       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4692         return R;
4693     if (isa<PHINode>(Op0))
4694       if (Instruction *NV = FoldOpIntoPhi(I))
4695         return NV;
4696   }
4697
4698   Value *A = 0, *B = 0;
4699   ConstantInt *C1 = 0, *C2 = 0;
4700
4701   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4702     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4703       return ReplaceInstUsesWith(I, Op1);
4704   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4705     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4706       return ReplaceInstUsesWith(I, Op0);
4707
4708   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4709   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4710   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4711       match(Op1, m_Or(m_Value(), m_Value())) ||
4712       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4713        match(Op1, m_Shift(m_Value(), m_Value())))) {
4714     if (Instruction *BSwap = MatchBSwap(I))
4715       return BSwap;
4716   }
4717   
4718   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4719   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4720       MaskedValueIsZero(Op1, C1->getValue())) {
4721     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4722     InsertNewInstBefore(NOr, I);
4723     NOr->takeName(Op0);
4724     return BinaryOperator::CreateXor(NOr, C1);
4725   }
4726
4727   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4728   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4729       MaskedValueIsZero(Op0, C1->getValue())) {
4730     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4731     InsertNewInstBefore(NOr, I);
4732     NOr->takeName(Op0);
4733     return BinaryOperator::CreateXor(NOr, C1);
4734   }
4735
4736   // (A & C)|(B & D)
4737   Value *C = 0, *D = 0;
4738   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4739       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4740     Value *V1 = 0, *V2 = 0, *V3 = 0;
4741     C1 = dyn_cast<ConstantInt>(C);
4742     C2 = dyn_cast<ConstantInt>(D);
4743     if (C1 && C2) {  // (A & C1)|(B & C2)
4744       // If we have: ((V + N) & C1) | (V & C2)
4745       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4746       // replace with V+N.
4747       if (C1->getValue() == ~C2->getValue()) {
4748         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4749             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4750           // Add commutes, try both ways.
4751           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4752             return ReplaceInstUsesWith(I, A);
4753           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4754             return ReplaceInstUsesWith(I, A);
4755         }
4756         // Or commutes, try both ways.
4757         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4758             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4759           // Add commutes, try both ways.
4760           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4761             return ReplaceInstUsesWith(I, B);
4762           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4763             return ReplaceInstUsesWith(I, B);
4764         }
4765       }
4766       V1 = 0; V2 = 0; V3 = 0;
4767     }
4768     
4769     // Check to see if we have any common things being and'ed.  If so, find the
4770     // terms for V1 & (V2|V3).
4771     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4772       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4773         V1 = A, V2 = C, V3 = D;
4774       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4775         V1 = A, V2 = B, V3 = C;
4776       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4777         V1 = C, V2 = A, V3 = D;
4778       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4779         V1 = C, V2 = A, V3 = B;
4780       
4781       if (V1) {
4782         Value *Or =
4783           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4784         return BinaryOperator::CreateAnd(V1, Or);
4785       }
4786     }
4787
4788     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4789     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4790       return Match;
4791     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4792       return Match;
4793     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4794       return Match;
4795     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4796       return Match;
4797
4798     // ((A&~B)|(~A&B)) -> A^B
4799     if ((match(C, m_Not(m_Specific(D))) &&
4800          match(B, m_Not(m_Specific(A)))))
4801       return BinaryOperator::CreateXor(A, D);
4802     // ((~B&A)|(~A&B)) -> A^B
4803     if ((match(A, m_Not(m_Specific(D))) &&
4804          match(B, m_Not(m_Specific(C)))))
4805       return BinaryOperator::CreateXor(C, D);
4806     // ((A&~B)|(B&~A)) -> A^B
4807     if ((match(C, m_Not(m_Specific(B))) &&
4808          match(D, m_Not(m_Specific(A)))))
4809       return BinaryOperator::CreateXor(A, B);
4810     // ((~B&A)|(B&~A)) -> A^B
4811     if ((match(A, m_Not(m_Specific(B))) &&
4812          match(D, m_Not(m_Specific(C)))))
4813       return BinaryOperator::CreateXor(C, B);
4814   }
4815   
4816   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4817   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4818     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4819       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4820           SI0->getOperand(1) == SI1->getOperand(1) &&
4821           (SI0->hasOneUse() || SI1->hasOneUse())) {
4822         Instruction *NewOp =
4823         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4824                                                      SI1->getOperand(0),
4825                                                      SI0->getName()), I);
4826         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4827                                       SI1->getOperand(1));
4828       }
4829   }
4830
4831   // ((A|B)&1)|(B&-2) -> (A&1) | B
4832   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4833       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4834     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4835     if (Ret) return Ret;
4836   }
4837   // (B&-2)|((A|B)&1) -> (A&1) | B
4838   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4839       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4840     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4841     if (Ret) return Ret;
4842   }
4843
4844   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4845     if (A == Op1)   // ~A | A == -1
4846       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4847   } else {
4848     A = 0;
4849   }
4850   // Note, A is still live here!
4851   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4852     if (Op0 == B)
4853       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4854
4855     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4856     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4857       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4858                                               I.getName()+".demorgan"), I);
4859       return BinaryOperator::CreateNot(And);
4860     }
4861   }
4862
4863   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4864   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4865     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4866       return R;
4867
4868     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4869       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4870         return Res;
4871   }
4872     
4873   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4874   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4875     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4876       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4877         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4878             !isa<ICmpInst>(Op1C->getOperand(0))) {
4879           const Type *SrcTy = Op0C->getOperand(0)->getType();
4880           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4881               // Only do this if the casts both really cause code to be
4882               // generated.
4883               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4884                                 I.getType(), TD) &&
4885               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4886                                 I.getType(), TD)) {
4887             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4888                                                           Op1C->getOperand(0),
4889                                                           I.getName());
4890             InsertNewInstBefore(NewOp, I);
4891             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4892           }
4893         }
4894       }
4895   }
4896   
4897     
4898   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4899   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4900     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4901       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4902           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4903           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4904         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4905           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4906             // If either of the constants are nans, then the whole thing returns
4907             // true.
4908             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4909               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4910             
4911             // Otherwise, no need to compare the two constants, compare the
4912             // rest.
4913             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4914                                 RHS->getOperand(0));
4915           }
4916       } else {
4917         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4918         FCmpInst::Predicate Op0CC, Op1CC;
4919         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4920             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4921           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4922             // Swap RHS operands to match LHS.
4923             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4924             std::swap(Op1LHS, Op1RHS);
4925           }
4926           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4927             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4928             if (Op0CC == Op1CC)
4929               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4930             else if (Op0CC == FCmpInst::FCMP_TRUE ||
4931                      Op1CC == FCmpInst::FCMP_TRUE)
4932               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4933             else if (Op0CC == FCmpInst::FCMP_FALSE)
4934               return ReplaceInstUsesWith(I, Op1);
4935             else if (Op1CC == FCmpInst::FCMP_FALSE)
4936               return ReplaceInstUsesWith(I, Op0);
4937             bool Op0Ordered;
4938             bool Op1Ordered;
4939             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4940             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4941             if (Op0Ordered == Op1Ordered) {
4942               // If both are ordered or unordered, return a new fcmp with
4943               // or'ed predicates.
4944               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4945                                        Op0LHS, Op0RHS);
4946               if (Instruction *I = dyn_cast<Instruction>(RV))
4947                 return I;
4948               // Otherwise, it's a constant boolean value...
4949               return ReplaceInstUsesWith(I, RV);
4950             }
4951           }
4952         }
4953       }
4954     }
4955   }
4956
4957   return Changed ? &I : 0;
4958 }
4959
4960 namespace {
4961
4962 // XorSelf - Implements: X ^ X --> 0
4963 struct XorSelf {
4964   Value *RHS;
4965   XorSelf(Value *rhs) : RHS(rhs) {}
4966   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4967   Instruction *apply(BinaryOperator &Xor) const {
4968     return &Xor;
4969   }
4970 };
4971
4972 }
4973
4974 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4975   bool Changed = SimplifyCommutative(I);
4976   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4977
4978   if (isa<UndefValue>(Op1)) {
4979     if (isa<UndefValue>(Op0))
4980       // Handle undef ^ undef -> 0 special case. This is a common
4981       // idiom (misuse).
4982       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4983     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4984   }
4985
4986   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4987   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4988     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4989     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4990   }
4991   
4992   // See if we can simplify any instructions used by the instruction whose sole 
4993   // purpose is to compute bits we don't care about.
4994   if (!isa<VectorType>(I.getType())) {
4995     if (SimplifyDemandedInstructionBits(I))
4996       return &I;
4997   } else if (isa<ConstantAggregateZero>(Op1)) {
4998     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4999   }
5000
5001   // Is this a ~ operation?
5002   if (Value *NotOp = dyn_castNotVal(&I)) {
5003     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5004     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5005     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5006       if (Op0I->getOpcode() == Instruction::And || 
5007           Op0I->getOpcode() == Instruction::Or) {
5008         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5009         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5010           Instruction *NotY =
5011             BinaryOperator::CreateNot(Op0I->getOperand(1),
5012                                       Op0I->getOperand(1)->getName()+".not");
5013           InsertNewInstBefore(NotY, I);
5014           if (Op0I->getOpcode() == Instruction::And)
5015             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5016           else
5017             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5018         }
5019       }
5020     }
5021   }
5022   
5023   
5024   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5025     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
5026       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5027       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5028         return new ICmpInst(ICI->getInversePredicate(),
5029                             ICI->getOperand(0), ICI->getOperand(1));
5030
5031       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5032         return new FCmpInst(FCI->getInversePredicate(),
5033                             FCI->getOperand(0), FCI->getOperand(1));
5034     }
5035
5036     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5037     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5038       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5039         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5040           Instruction::CastOps Opcode = Op0C->getOpcode();
5041           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5042             if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
5043                                              Op0C->getDestTy())) {
5044               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5045                                      CI->getOpcode(), CI->getInversePredicate(),
5046                                      CI->getOperand(0), CI->getOperand(1)), I);
5047               NewCI->takeName(CI);
5048               return CastInst::Create(Opcode, NewCI, Op0C->getType());
5049             }
5050           }
5051         }
5052       }
5053     }
5054
5055     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5056       // ~(c-X) == X-c-1 == X+(-c-1)
5057       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5058         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5059           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5060           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5061                                               ConstantInt::get(I.getType(), 1));
5062           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5063         }
5064           
5065       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5066         if (Op0I->getOpcode() == Instruction::Add) {
5067           // ~(X-c) --> (-c-1)-X
5068           if (RHS->isAllOnesValue()) {
5069             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5070             return BinaryOperator::CreateSub(
5071                            ConstantExpr::getSub(NegOp0CI,
5072                                              ConstantInt::get(I.getType(), 1)),
5073                                           Op0I->getOperand(0));
5074           } else if (RHS->getValue().isSignBit()) {
5075             // (X + C) ^ signbit -> (X + C + signbit)
5076             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
5077             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5078
5079           }
5080         } else if (Op0I->getOpcode() == Instruction::Or) {
5081           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5082           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5083             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5084             // Anything in both C1 and C2 is known to be zero, remove it from
5085             // NewRHS.
5086             Constant *CommonBits = And(Op0CI, RHS);
5087             NewRHS = ConstantExpr::getAnd(NewRHS, 
5088                                           ConstantExpr::getNot(CommonBits));
5089             AddToWorkList(Op0I);
5090             I.setOperand(0, Op0I->getOperand(0));
5091             I.setOperand(1, NewRHS);
5092             return &I;
5093           }
5094         }
5095       }
5096     }
5097
5098     // Try to fold constant and into select arguments.
5099     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5100       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5101         return R;
5102     if (isa<PHINode>(Op0))
5103       if (Instruction *NV = FoldOpIntoPhi(I))
5104         return NV;
5105   }
5106
5107   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
5108     if (X == Op1)
5109       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5110
5111   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5112     if (X == Op0)
5113       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5114
5115   
5116   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5117   if (Op1I) {
5118     Value *A, *B;
5119     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5120       if (A == Op0) {              // B^(B|A) == (A|B)^B
5121         Op1I->swapOperands();
5122         I.swapOperands();
5123         std::swap(Op0, Op1);
5124       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5125         I.swapOperands();     // Simplified below.
5126         std::swap(Op0, Op1);
5127       }
5128     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5129       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5130     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5131       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5132     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
5133       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5134         Op1I->swapOperands();
5135         std::swap(A, B);
5136       }
5137       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5138         I.swapOperands();     // Simplified below.
5139         std::swap(Op0, Op1);
5140       }
5141     }
5142   }
5143   
5144   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5145   if (Op0I) {
5146     Value *A, *B;
5147     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5148       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5149         std::swap(A, B);
5150       if (B == Op1) {                                // (A|B)^B == A & ~B
5151         Instruction *NotB =
5152           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5153         return BinaryOperator::CreateAnd(A, NotB);
5154       }
5155     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5156       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5157     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5158       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5159     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5160       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5161         std::swap(A, B);
5162       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5163           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5164         Instruction *N =
5165           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5166         return BinaryOperator::CreateAnd(N, Op1);
5167       }
5168     }
5169   }
5170   
5171   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5172   if (Op0I && Op1I && Op0I->isShift() && 
5173       Op0I->getOpcode() == Op1I->getOpcode() && 
5174       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5175       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5176     Instruction *NewOp =
5177       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5178                                                     Op1I->getOperand(0),
5179                                                     Op0I->getName()), I);
5180     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5181                                   Op1I->getOperand(1));
5182   }
5183     
5184   if (Op0I && Op1I) {
5185     Value *A, *B, *C, *D;
5186     // (A & B)^(A | B) -> A ^ B
5187     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5188         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5189       if ((A == C && B == D) || (A == D && B == C)) 
5190         return BinaryOperator::CreateXor(A, B);
5191     }
5192     // (A | B)^(A & B) -> A ^ B
5193     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5194         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5195       if ((A == C && B == D) || (A == D && B == C)) 
5196         return BinaryOperator::CreateXor(A, B);
5197     }
5198     
5199     // (A & B)^(C & D)
5200     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5201         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5202         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5203       // (X & Y)^(X & Y) -> (Y^Z) & X
5204       Value *X = 0, *Y = 0, *Z = 0;
5205       if (A == C)
5206         X = A, Y = B, Z = D;
5207       else if (A == D)
5208         X = A, Y = B, Z = C;
5209       else if (B == C)
5210         X = B, Y = A, Z = D;
5211       else if (B == D)
5212         X = B, Y = A, Z = C;
5213       
5214       if (X) {
5215         Instruction *NewOp =
5216         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5217         return BinaryOperator::CreateAnd(NewOp, X);
5218       }
5219     }
5220   }
5221     
5222   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5223   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5224     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5225       return R;
5226
5227   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5228   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5229     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5230       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5231         const Type *SrcTy = Op0C->getOperand(0)->getType();
5232         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5233             // Only do this if the casts both really cause code to be generated.
5234             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5235                               I.getType(), TD) &&
5236             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5237                               I.getType(), TD)) {
5238           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5239                                                          Op1C->getOperand(0),
5240                                                          I.getName());
5241           InsertNewInstBefore(NewOp, I);
5242           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5243         }
5244       }
5245   }
5246
5247   return Changed ? &I : 0;
5248 }
5249
5250 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5251 /// overflowed for this type.
5252 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5253                             ConstantInt *In2, bool IsSigned = false) {
5254   Result = cast<ConstantInt>(Add(In1, In2));
5255
5256   if (IsSigned)
5257     if (In2->getValue().isNegative())
5258       return Result->getValue().sgt(In1->getValue());
5259     else
5260       return Result->getValue().slt(In1->getValue());
5261   else
5262     return Result->getValue().ult(In1->getValue());
5263 }
5264
5265 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5266 /// overflowed for this type.
5267 static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5268                             ConstantInt *In2, bool IsSigned = false) {
5269   Result = cast<ConstantInt>(Subtract(In1, In2));
5270
5271   if (IsSigned)
5272     if (In2->getValue().isNegative())
5273       return Result->getValue().slt(In1->getValue());
5274     else
5275       return Result->getValue().sgt(In1->getValue());
5276   else
5277     return Result->getValue().ugt(In1->getValue());
5278 }
5279
5280 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5281 /// code necessary to compute the offset from the base pointer (without adding
5282 /// in the base pointer).  Return the result as a signed integer of intptr size.
5283 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5284   TargetData &TD = IC.getTargetData();
5285   gep_type_iterator GTI = gep_type_begin(GEP);
5286   const Type *IntPtrTy = TD.getIntPtrType();
5287   Value *Result = Constant::getNullValue(IntPtrTy);
5288
5289   // Build a mask for high order bits.
5290   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5291   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5292
5293   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5294        ++i, ++GTI) {
5295     Value *Op = *i;
5296     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5297     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5298       if (OpC->isZero()) continue;
5299       
5300       // Handle a struct index, which adds its field offset to the pointer.
5301       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5302         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5303         
5304         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5305           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
5306         else
5307           Result = IC.InsertNewInstBefore(
5308                    BinaryOperator::CreateAdd(Result,
5309                                              ConstantInt::get(IntPtrTy, Size),
5310                                              GEP->getName()+".offs"), I);
5311         continue;
5312       }
5313       
5314       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5315       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5316       Scale = ConstantExpr::getMul(OC, Scale);
5317       if (Constant *RC = dyn_cast<Constant>(Result))
5318         Result = ConstantExpr::getAdd(RC, Scale);
5319       else {
5320         // Emit an add instruction.
5321         Result = IC.InsertNewInstBefore(
5322            BinaryOperator::CreateAdd(Result, Scale,
5323                                      GEP->getName()+".offs"), I);
5324       }
5325       continue;
5326     }
5327     // Convert to correct type.
5328     if (Op->getType() != IntPtrTy) {
5329       if (Constant *OpC = dyn_cast<Constant>(Op))
5330         Op = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true);
5331       else
5332         Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5333                                                                 true,
5334                                                       Op->getName()+".c"), I);
5335     }
5336     if (Size != 1) {
5337       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5338       if (Constant *OpC = dyn_cast<Constant>(Op))
5339         Op = ConstantExpr::getMul(OpC, Scale);
5340       else    // We'll let instcombine(mul) convert this to a shl if possible.
5341         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5342                                                   GEP->getName()+".idx"), I);
5343     }
5344
5345     // Emit an add instruction.
5346     if (isa<Constant>(Op) && isa<Constant>(Result))
5347       Result = ConstantExpr::getAdd(cast<Constant>(Op),
5348                                     cast<Constant>(Result));
5349     else
5350       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5351                                                   GEP->getName()+".offs"), I);
5352   }
5353   return Result;
5354 }
5355
5356
5357 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5358 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
5359 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
5360 /// complex, and scales are involved.  The above expression would also be legal
5361 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
5362 /// later form is less amenable to optimization though, and we are allowed to
5363 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5364 ///
5365 /// If we can't emit an optimized form for this expression, this returns null.
5366 /// 
5367 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5368                                           InstCombiner &IC) {
5369   TargetData &TD = IC.getTargetData();
5370   gep_type_iterator GTI = gep_type_begin(GEP);
5371
5372   // Check to see if this gep only has a single variable index.  If so, and if
5373   // any constant indices are a multiple of its scale, then we can compute this
5374   // in terms of the scale of the variable index.  For example, if the GEP
5375   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5376   // because the expression will cross zero at the same point.
5377   unsigned i, e = GEP->getNumOperands();
5378   int64_t Offset = 0;
5379   for (i = 1; i != e; ++i, ++GTI) {
5380     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5381       // Compute the aggregate offset of constant indices.
5382       if (CI->isZero()) continue;
5383
5384       // Handle a struct index, which adds its field offset to the pointer.
5385       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5386         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5387       } else {
5388         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5389         Offset += Size*CI->getSExtValue();
5390       }
5391     } else {
5392       // Found our variable index.
5393       break;
5394     }
5395   }
5396   
5397   // If there are no variable indices, we must have a constant offset, just
5398   // evaluate it the general way.
5399   if (i == e) return 0;
5400   
5401   Value *VariableIdx = GEP->getOperand(i);
5402   // Determine the scale factor of the variable element.  For example, this is
5403   // 4 if the variable index is into an array of i32.
5404   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5405   
5406   // Verify that there are no other variable indices.  If so, emit the hard way.
5407   for (++i, ++GTI; i != e; ++i, ++GTI) {
5408     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5409     if (!CI) return 0;
5410    
5411     // Compute the aggregate offset of constant indices.
5412     if (CI->isZero()) continue;
5413     
5414     // Handle a struct index, which adds its field offset to the pointer.
5415     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5416       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5417     } else {
5418       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5419       Offset += Size*CI->getSExtValue();
5420     }
5421   }
5422   
5423   // Okay, we know we have a single variable index, which must be a
5424   // pointer/array/vector index.  If there is no offset, life is simple, return
5425   // the index.
5426   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5427   if (Offset == 0) {
5428     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5429     // we don't need to bother extending: the extension won't affect where the
5430     // computation crosses zero.
5431     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5432       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5433                                   VariableIdx->getNameStart(), &I);
5434     return VariableIdx;
5435   }
5436   
5437   // Otherwise, there is an index.  The computation we will do will be modulo
5438   // the pointer size, so get it.
5439   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5440   
5441   Offset &= PtrSizeMask;
5442   VariableScale &= PtrSizeMask;
5443
5444   // To do this transformation, any constant index must be a multiple of the
5445   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5446   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5447   // multiple of the variable scale.
5448   int64_t NewOffs = Offset / (int64_t)VariableScale;
5449   if (Offset != NewOffs*(int64_t)VariableScale)
5450     return 0;
5451
5452   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5453   const Type *IntPtrTy = TD.getIntPtrType();
5454   if (VariableIdx->getType() != IntPtrTy)
5455     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5456                                               true /*SExt*/, 
5457                                               VariableIdx->getNameStart(), &I);
5458   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5459   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5460 }
5461
5462
5463 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5464 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5465 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5466                                        ICmpInst::Predicate Cond,
5467                                        Instruction &I) {
5468   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5469
5470   // Look through bitcasts.
5471   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5472     RHS = BCI->getOperand(0);
5473
5474   Value *PtrBase = GEPLHS->getOperand(0);
5475   if (PtrBase == RHS) {
5476     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5477     // This transformation (ignoring the base and scales) is valid because we
5478     // know pointers can't overflow.  See if we can output an optimized form.
5479     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5480     
5481     // If not, synthesize the offset the hard way.
5482     if (Offset == 0)
5483       Offset = EmitGEPOffset(GEPLHS, I, *this);
5484     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5485                         Constant::getNullValue(Offset->getType()));
5486   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5487     // If the base pointers are different, but the indices are the same, just
5488     // compare the base pointer.
5489     if (PtrBase != GEPRHS->getOperand(0)) {
5490       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5491       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5492                         GEPRHS->getOperand(0)->getType();
5493       if (IndicesTheSame)
5494         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5495           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5496             IndicesTheSame = false;
5497             break;
5498           }
5499
5500       // If all indices are the same, just compare the base pointers.
5501       if (IndicesTheSame)
5502         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
5503                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5504
5505       // Otherwise, the base pointers are different and the indices are
5506       // different, bail out.
5507       return 0;
5508     }
5509
5510     // If one of the GEPs has all zero indices, recurse.
5511     bool AllZeros = true;
5512     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5513       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5514           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5515         AllZeros = false;
5516         break;
5517       }
5518     if (AllZeros)
5519       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5520                           ICmpInst::getSwappedPredicate(Cond), I);
5521
5522     // If the other GEP has all zero indices, recurse.
5523     AllZeros = true;
5524     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5525       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5526           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5527         AllZeros = false;
5528         break;
5529       }
5530     if (AllZeros)
5531       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5532
5533     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5534       // If the GEPs only differ by one index, compare it.
5535       unsigned NumDifferences = 0;  // Keep track of # differences.
5536       unsigned DiffOperand = 0;     // The operand that differs.
5537       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5538         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5539           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5540                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5541             // Irreconcilable differences.
5542             NumDifferences = 2;
5543             break;
5544           } else {
5545             if (NumDifferences++) break;
5546             DiffOperand = i;
5547           }
5548         }
5549
5550       if (NumDifferences == 0)   // SAME GEP?
5551         return ReplaceInstUsesWith(I, // No comparison is needed here.
5552                                    ConstantInt::get(Type::Int1Ty,
5553                                              ICmpInst::isTrueWhenEqual(Cond)));
5554
5555       else if (NumDifferences == 1) {
5556         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5557         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5558         // Make sure we do a signed comparison here.
5559         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5560       }
5561     }
5562
5563     // Only lower this if the icmp is the only user of the GEP or if we expect
5564     // the result to fold to a constant!
5565     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5566         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5567       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5568       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5569       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5570       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5571     }
5572   }
5573   return 0;
5574 }
5575
5576 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5577 ///
5578 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5579                                                 Instruction *LHSI,
5580                                                 Constant *RHSC) {
5581   if (!isa<ConstantFP>(RHSC)) return 0;
5582   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5583   
5584   // Get the width of the mantissa.  We don't want to hack on conversions that
5585   // might lose information from the integer, e.g. "i64 -> float"
5586   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5587   if (MantissaWidth == -1) return 0;  // Unknown.
5588   
5589   // Check to see that the input is converted from an integer type that is small
5590   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5591   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5592   unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5593   
5594   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5595   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5596   if (LHSUnsigned)
5597     ++InputSize;
5598   
5599   // If the conversion would lose info, don't hack on this.
5600   if ((int)InputSize > MantissaWidth)
5601     return 0;
5602   
5603   // Otherwise, we can potentially simplify the comparison.  We know that it
5604   // will always come through as an integer value and we know the constant is
5605   // not a NAN (it would have been previously simplified).
5606   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5607   
5608   ICmpInst::Predicate Pred;
5609   switch (I.getPredicate()) {
5610   default: assert(0 && "Unexpected predicate!");
5611   case FCmpInst::FCMP_UEQ:
5612   case FCmpInst::FCMP_OEQ:
5613     Pred = ICmpInst::ICMP_EQ;
5614     break;
5615   case FCmpInst::FCMP_UGT:
5616   case FCmpInst::FCMP_OGT:
5617     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5618     break;
5619   case FCmpInst::FCMP_UGE:
5620   case FCmpInst::FCMP_OGE:
5621     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5622     break;
5623   case FCmpInst::FCMP_ULT:
5624   case FCmpInst::FCMP_OLT:
5625     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5626     break;
5627   case FCmpInst::FCMP_ULE:
5628   case FCmpInst::FCMP_OLE:
5629     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5630     break;
5631   case FCmpInst::FCMP_UNE:
5632   case FCmpInst::FCMP_ONE:
5633     Pred = ICmpInst::ICMP_NE;
5634     break;
5635   case FCmpInst::FCMP_ORD:
5636     return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5637   case FCmpInst::FCMP_UNO:
5638     return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5639   }
5640   
5641   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5642   
5643   // Now we know that the APFloat is a normal number, zero or inf.
5644   
5645   // See if the FP constant is too large for the integer.  For example,
5646   // comparing an i8 to 300.0.
5647   unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5648   
5649   if (!LHSUnsigned) {
5650     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5651     // and large values.
5652     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5653     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5654                           APFloat::rmNearestTiesToEven);
5655     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5656       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5657           Pred == ICmpInst::ICMP_SLE)
5658         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5659       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5660     }
5661   } else {
5662     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5663     // +INF and large values.
5664     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5665     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5666                           APFloat::rmNearestTiesToEven);
5667     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5668       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5669           Pred == ICmpInst::ICMP_ULE)
5670         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5671       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5672     }
5673   }
5674   
5675   if (!LHSUnsigned) {
5676     // See if the RHS value is < SignedMin.
5677     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5678     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5679                           APFloat::rmNearestTiesToEven);
5680     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5681       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5682           Pred == ICmpInst::ICMP_SGE)
5683         return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5684       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5685     }
5686   }
5687
5688   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5689   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5690   // casting the FP value to the integer value and back, checking for equality.
5691   // Don't do this for zero, because -0.0 is not fractional.
5692   Constant *RHSInt = LHSUnsigned
5693     ? ConstantExpr::getFPToUI(RHSC, IntTy)
5694     : ConstantExpr::getFPToSI(RHSC, IntTy);
5695   if (!RHS.isZero()) {
5696     bool Equal = LHSUnsigned
5697       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5698       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5699     if (!Equal) {
5700       // If we had a comparison against a fractional value, we have to adjust
5701       // the compare predicate and sometimes the value.  RHSC is rounded towards
5702       // zero at this point.
5703       switch (Pred) {
5704       default: assert(0 && "Unexpected integer comparison!");
5705       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5706         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5707       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5708         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5709       case ICmpInst::ICMP_ULE:
5710         // (float)int <= 4.4   --> int <= 4
5711         // (float)int <= -4.4  --> false
5712         if (RHS.isNegative())
5713           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5714         break;
5715       case ICmpInst::ICMP_SLE:
5716         // (float)int <= 4.4   --> int <= 4
5717         // (float)int <= -4.4  --> int < -4
5718         if (RHS.isNegative())
5719           Pred = ICmpInst::ICMP_SLT;
5720         break;
5721       case ICmpInst::ICMP_ULT:
5722         // (float)int < -4.4   --> false
5723         // (float)int < 4.4    --> int <= 4
5724         if (RHS.isNegative())
5725           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5726         Pred = ICmpInst::ICMP_ULE;
5727         break;
5728       case ICmpInst::ICMP_SLT:
5729         // (float)int < -4.4   --> int < -4
5730         // (float)int < 4.4    --> int <= 4
5731         if (!RHS.isNegative())
5732           Pred = ICmpInst::ICMP_SLE;
5733         break;
5734       case ICmpInst::ICMP_UGT:
5735         // (float)int > 4.4    --> int > 4
5736         // (float)int > -4.4   --> true
5737         if (RHS.isNegative())
5738           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5739         break;
5740       case ICmpInst::ICMP_SGT:
5741         // (float)int > 4.4    --> int > 4
5742         // (float)int > -4.4   --> int >= -4
5743         if (RHS.isNegative())
5744           Pred = ICmpInst::ICMP_SGE;
5745         break;
5746       case ICmpInst::ICMP_UGE:
5747         // (float)int >= -4.4   --> true
5748         // (float)int >= 4.4    --> int > 4
5749         if (!RHS.isNegative())
5750           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5751         Pred = ICmpInst::ICMP_UGT;
5752         break;
5753       case ICmpInst::ICMP_SGE:
5754         // (float)int >= -4.4   --> int >= -4
5755         // (float)int >= 4.4    --> int > 4
5756         if (!RHS.isNegative())
5757           Pred = ICmpInst::ICMP_SGT;
5758         break;
5759       }
5760     }
5761   }
5762
5763   // Lower this FP comparison into an appropriate integer version of the
5764   // comparison.
5765   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5766 }
5767
5768 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5769   bool Changed = SimplifyCompare(I);
5770   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5771
5772   // Fold trivial predicates.
5773   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5774     return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5775   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5776     return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5777   
5778   // Simplify 'fcmp pred X, X'
5779   if (Op0 == Op1) {
5780     switch (I.getPredicate()) {
5781     default: assert(0 && "Unknown predicate!");
5782     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5783     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5784     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5785       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5786     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5787     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5788     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5789       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5790       
5791     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5792     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5793     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5794     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5795       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5796       I.setPredicate(FCmpInst::FCMP_UNO);
5797       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5798       return &I;
5799       
5800     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5801     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5802     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5803     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5804       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5805       I.setPredicate(FCmpInst::FCMP_ORD);
5806       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5807       return &I;
5808     }
5809   }
5810     
5811   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5812     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5813
5814   // Handle fcmp with constant RHS
5815   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5816     // If the constant is a nan, see if we can fold the comparison based on it.
5817     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5818       if (CFP->getValueAPF().isNaN()) {
5819         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5820           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5821         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5822                "Comparison must be either ordered or unordered!");
5823         // True if unordered.
5824         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5825       }
5826     }
5827     
5828     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5829       switch (LHSI->getOpcode()) {
5830       case Instruction::PHI:
5831         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5832         // block.  If in the same block, we're encouraging jump threading.  If
5833         // not, we are just pessimizing the code by making an i1 phi.
5834         if (LHSI->getParent() == I.getParent())
5835           if (Instruction *NV = FoldOpIntoPhi(I))
5836             return NV;
5837         break;
5838       case Instruction::SIToFP:
5839       case Instruction::UIToFP:
5840         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5841           return NV;
5842         break;
5843       case Instruction::Select:
5844         // If either operand of the select is a constant, we can fold the
5845         // comparison into the select arms, which will cause one to be
5846         // constant folded and the select turned into a bitwise or.
5847         Value *Op1 = 0, *Op2 = 0;
5848         if (LHSI->hasOneUse()) {
5849           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5850             // Fold the known value into the constant operand.
5851             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5852             // Insert a new FCmp of the other select operand.
5853             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5854                                                       LHSI->getOperand(2), RHSC,
5855                                                       I.getName()), I);
5856           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5857             // Fold the known value into the constant operand.
5858             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5859             // Insert a new FCmp of the other select operand.
5860             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5861                                                       LHSI->getOperand(1), RHSC,
5862                                                       I.getName()), I);
5863           }
5864         }
5865
5866         if (Op1)
5867           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5868         break;
5869       }
5870   }
5871
5872   return Changed ? &I : 0;
5873 }
5874
5875 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5876   bool Changed = SimplifyCompare(I);
5877   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5878   const Type *Ty = Op0->getType();
5879
5880   // icmp X, X
5881   if (Op0 == Op1)
5882     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5883                                                    I.isTrueWhenEqual()));
5884
5885   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5886     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5887   
5888   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5889   // addresses never equal each other!  We already know that Op0 != Op1.
5890   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5891        isa<ConstantPointerNull>(Op0)) &&
5892       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5893        isa<ConstantPointerNull>(Op1)))
5894     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5895                                                    !I.isTrueWhenEqual()));
5896
5897   // icmp's with boolean values can always be turned into bitwise operations
5898   if (Ty == Type::Int1Ty) {
5899     switch (I.getPredicate()) {
5900     default: assert(0 && "Invalid icmp instruction!");
5901     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5902       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5903       InsertNewInstBefore(Xor, I);
5904       return BinaryOperator::CreateNot(Xor);
5905     }
5906     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5907       return BinaryOperator::CreateXor(Op0, Op1);
5908
5909     case ICmpInst::ICMP_UGT:
5910       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5911       // FALL THROUGH
5912     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5913       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5914       InsertNewInstBefore(Not, I);
5915       return BinaryOperator::CreateAnd(Not, Op1);
5916     }
5917     case ICmpInst::ICMP_SGT:
5918       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5919       // FALL THROUGH
5920     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5921       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5922       InsertNewInstBefore(Not, I);
5923       return BinaryOperator::CreateAnd(Not, Op0);
5924     }
5925     case ICmpInst::ICMP_UGE:
5926       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
5927       // FALL THROUGH
5928     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
5929       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5930       InsertNewInstBefore(Not, I);
5931       return BinaryOperator::CreateOr(Not, Op1);
5932     }
5933     case ICmpInst::ICMP_SGE:
5934       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
5935       // FALL THROUGH
5936     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
5937       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5938       InsertNewInstBefore(Not, I);
5939       return BinaryOperator::CreateOr(Not, Op0);
5940     }
5941     }
5942   }
5943
5944   unsigned BitWidth = 0;
5945   if (TD)
5946     BitWidth = TD->getTypeSizeInBits(Ty);
5947   else if (isa<IntegerType>(Ty))
5948     BitWidth = Ty->getPrimitiveSizeInBits();
5949
5950   bool isSignBit = false;
5951
5952   // See if we are doing a comparison with a constant.
5953   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5954     Value *A = 0, *B = 0;
5955     
5956     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5957     if (I.isEquality() && CI->isNullValue() &&
5958         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5959       // (icmp cond A B) if cond is equality
5960       return new ICmpInst(I.getPredicate(), A, B);
5961     }
5962     
5963     // If we have an icmp le or icmp ge instruction, turn it into the
5964     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
5965     // them being folded in the code below.
5966     switch (I.getPredicate()) {
5967     default: break;
5968     case ICmpInst::ICMP_ULE:
5969       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5970         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5971       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5972     case ICmpInst::ICMP_SLE:
5973       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5974         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5975       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5976     case ICmpInst::ICMP_UGE:
5977       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5978         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5979       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5980     case ICmpInst::ICMP_SGE:
5981       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5982         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5983       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5984     }
5985     
5986     // If this comparison is a normal comparison, it demands all
5987     // bits, if it is a sign bit comparison, it only demands the sign bit.
5988     bool UnusedBit;
5989     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5990   }
5991
5992   // See if we can fold the comparison based on range information we can get
5993   // by checking whether bits are known to be zero or one in the input.
5994   if (BitWidth != 0) {
5995     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
5996     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
5997
5998     if (SimplifyDemandedBits(I.getOperandUse(0),
5999                              isSignBit ? APInt::getSignBit(BitWidth)
6000                                        : APInt::getAllOnesValue(BitWidth),
6001                              Op0KnownZero, Op0KnownOne, 0))
6002       return &I;
6003     if (SimplifyDemandedBits(I.getOperandUse(1),
6004                              APInt::getAllOnesValue(BitWidth),
6005                              Op1KnownZero, Op1KnownOne, 0))
6006       return &I;
6007
6008     // Given the known and unknown bits, compute a range that the LHS could be
6009     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6010     // EQ and NE we use unsigned values.
6011     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6012     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6013     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6014       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6015                                              Op0Min, Op0Max);
6016       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6017                                              Op1Min, Op1Max);
6018     } else {
6019       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6020                                                Op0Min, Op0Max);
6021       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6022                                                Op1Min, Op1Max);
6023     }
6024
6025     // If Min and Max are known to be the same, then SimplifyDemandedBits
6026     // figured out that the LHS is a constant.  Just constant fold this now so
6027     // that code below can assume that Min != Max.
6028     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6029       return new ICmpInst(I.getPredicate(), ConstantInt::get(Op0Min), Op1);
6030     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6031       return new ICmpInst(I.getPredicate(), Op0, ConstantInt::get(Op1Min));
6032
6033     // Based on the range information we know about the LHS, see if we can
6034     // simplify this comparison.  For example, (x&4) < 8  is always true.
6035     switch (I.getPredicate()) {
6036     default: assert(0 && "Unknown icmp opcode!");
6037     case ICmpInst::ICMP_EQ:
6038       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6039         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6040       break;
6041     case ICmpInst::ICMP_NE:
6042       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6043         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6044       break;
6045     case ICmpInst::ICMP_ULT:
6046       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6047         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6048       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6049         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6050       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6051         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6052       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6053         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6054           return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
6055
6056         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6057         if (CI->isMinValue(true))
6058           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6059                             ConstantInt::getAllOnesValue(Op0->getType()));
6060       }
6061       break;
6062     case ICmpInst::ICMP_UGT:
6063       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6064         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6065       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6066         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6067
6068       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6069         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6070       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6071         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6072           return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
6073
6074         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6075         if (CI->isMaxValue(true))
6076           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6077                               ConstantInt::getNullValue(Op0->getType()));
6078       }
6079       break;
6080     case ICmpInst::ICMP_SLT:
6081       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6082         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6083       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6084         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6085       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6086         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6087       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6088         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6089           return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
6090       }
6091       break;
6092     case ICmpInst::ICMP_SGT:
6093       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6094         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6095       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6096         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6097
6098       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6099         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6100       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6101         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6102           return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
6103       }
6104       break;
6105     case ICmpInst::ICMP_SGE:
6106       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6107       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6108         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6109       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6110         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6111       break;
6112     case ICmpInst::ICMP_SLE:
6113       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6114       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6115         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6116       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6117         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6118       break;
6119     case ICmpInst::ICMP_UGE:
6120       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6121       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6122         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6123       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6124         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6125       break;
6126     case ICmpInst::ICMP_ULE:
6127       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6128       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6129         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6130       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6131         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6132       break;
6133     }
6134
6135     // Turn a signed comparison into an unsigned one if both operands
6136     // are known to have the same sign.
6137     if (I.isSignedPredicate() &&
6138         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6139          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6140       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6141   }
6142
6143   // Test if the ICmpInst instruction is used exclusively by a select as
6144   // part of a minimum or maximum operation. If so, refrain from doing
6145   // any other folding. This helps out other analyses which understand
6146   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6147   // and CodeGen. And in this case, at least one of the comparison
6148   // operands has at least one user besides the compare (the select),
6149   // which would often largely negate the benefit of folding anyway.
6150   if (I.hasOneUse())
6151     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6152       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6153           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6154         return 0;
6155
6156   // See if we are doing a comparison between a constant and an instruction that
6157   // can be folded into the comparison.
6158   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6159     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6160     // instruction, see if that instruction also has constants so that the 
6161     // instruction can be folded into the icmp 
6162     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6163       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6164         return Res;
6165   }
6166
6167   // Handle icmp with constant (but not simple integer constant) RHS
6168   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6169     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6170       switch (LHSI->getOpcode()) {
6171       case Instruction::GetElementPtr:
6172         if (RHSC->isNullValue()) {
6173           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6174           bool isAllZeros = true;
6175           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6176             if (!isa<Constant>(LHSI->getOperand(i)) ||
6177                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6178               isAllZeros = false;
6179               break;
6180             }
6181           if (isAllZeros)
6182             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6183                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
6184         }
6185         break;
6186
6187       case Instruction::PHI:
6188         // Only fold icmp into the PHI if the phi and fcmp are in the same
6189         // block.  If in the same block, we're encouraging jump threading.  If
6190         // not, we are just pessimizing the code by making an i1 phi.
6191         if (LHSI->getParent() == I.getParent())
6192           if (Instruction *NV = FoldOpIntoPhi(I))
6193             return NV;
6194         break;
6195       case Instruction::Select: {
6196         // If either operand of the select is a constant, we can fold the
6197         // comparison into the select arms, which will cause one to be
6198         // constant folded and the select turned into a bitwise or.
6199         Value *Op1 = 0, *Op2 = 0;
6200         if (LHSI->hasOneUse()) {
6201           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6202             // Fold the known value into the constant operand.
6203             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6204             // Insert a new ICmp of the other select operand.
6205             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6206                                                    LHSI->getOperand(2), RHSC,
6207                                                    I.getName()), I);
6208           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6209             // Fold the known value into the constant operand.
6210             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6211             // Insert a new ICmp of the other select operand.
6212             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6213                                                    LHSI->getOperand(1), RHSC,
6214                                                    I.getName()), I);
6215           }
6216         }
6217
6218         if (Op1)
6219           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6220         break;
6221       }
6222       case Instruction::Malloc:
6223         // If we have (malloc != null), and if the malloc has a single use, we
6224         // can assume it is successful and remove the malloc.
6225         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6226           AddToWorkList(LHSI);
6227           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
6228                                                          !I.isTrueWhenEqual()));
6229         }
6230         break;
6231       }
6232   }
6233
6234   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6235   if (User *GEP = dyn_castGetElementPtr(Op0))
6236     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6237       return NI;
6238   if (User *GEP = dyn_castGetElementPtr(Op1))
6239     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6240                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6241       return NI;
6242
6243   // Test to see if the operands of the icmp are casted versions of other
6244   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6245   // now.
6246   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6247     if (isa<PointerType>(Op0->getType()) && 
6248         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6249       // We keep moving the cast from the left operand over to the right
6250       // operand, where it can often be eliminated completely.
6251       Op0 = CI->getOperand(0);
6252
6253       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6254       // so eliminate it as well.
6255       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6256         Op1 = CI2->getOperand(0);
6257
6258       // If Op1 is a constant, we can fold the cast into the constant.
6259       if (Op0->getType() != Op1->getType()) {
6260         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6261           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6262         } else {
6263           // Otherwise, cast the RHS right before the icmp
6264           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6265         }
6266       }
6267       return new ICmpInst(I.getPredicate(), Op0, Op1);
6268     }
6269   }
6270   
6271   if (isa<CastInst>(Op0)) {
6272     // Handle the special case of: icmp (cast bool to X), <cst>
6273     // This comes up when you have code like
6274     //   int X = A < B;
6275     //   if (X) ...
6276     // For generality, we handle any zero-extension of any operand comparison
6277     // with a constant or another cast from the same type.
6278     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6279       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6280         return R;
6281   }
6282   
6283   // See if it's the same type of instruction on the left and right.
6284   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6285     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6286       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6287           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6288         switch (Op0I->getOpcode()) {
6289         default: break;
6290         case Instruction::Add:
6291         case Instruction::Sub:
6292         case Instruction::Xor:
6293           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6294             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6295                                 Op1I->getOperand(0));
6296           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6297           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6298             if (CI->getValue().isSignBit()) {
6299               ICmpInst::Predicate Pred = I.isSignedPredicate()
6300                                              ? I.getUnsignedPredicate()
6301                                              : I.getSignedPredicate();
6302               return new ICmpInst(Pred, Op0I->getOperand(0),
6303                                   Op1I->getOperand(0));
6304             }
6305             
6306             if (CI->getValue().isMaxSignedValue()) {
6307               ICmpInst::Predicate Pred = I.isSignedPredicate()
6308                                              ? I.getUnsignedPredicate()
6309                                              : I.getSignedPredicate();
6310               Pred = I.getSwappedPredicate(Pred);
6311               return new ICmpInst(Pred, Op0I->getOperand(0),
6312                                   Op1I->getOperand(0));
6313             }
6314           }
6315           break;
6316         case Instruction::Mul:
6317           if (!I.isEquality())
6318             break;
6319
6320           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6321             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6322             // Mask = -1 >> count-trailing-zeros(Cst).
6323             if (!CI->isZero() && !CI->isOne()) {
6324               const APInt &AP = CI->getValue();
6325               ConstantInt *Mask = ConstantInt::get(
6326                                       APInt::getLowBitsSet(AP.getBitWidth(),
6327                                                            AP.getBitWidth() -
6328                                                       AP.countTrailingZeros()));
6329               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6330                                                             Mask);
6331               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6332                                                             Mask);
6333               InsertNewInstBefore(And1, I);
6334               InsertNewInstBefore(And2, I);
6335               return new ICmpInst(I.getPredicate(), And1, And2);
6336             }
6337           }
6338           break;
6339         }
6340       }
6341     }
6342   }
6343   
6344   // ~x < ~y --> y < x
6345   { Value *A, *B;
6346     if (match(Op0, m_Not(m_Value(A))) &&
6347         match(Op1, m_Not(m_Value(B))))
6348       return new ICmpInst(I.getPredicate(), B, A);
6349   }
6350   
6351   if (I.isEquality()) {
6352     Value *A, *B, *C, *D;
6353     
6354     // -x == -y --> x == y
6355     if (match(Op0, m_Neg(m_Value(A))) &&
6356         match(Op1, m_Neg(m_Value(B))))
6357       return new ICmpInst(I.getPredicate(), A, B);
6358     
6359     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6360       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6361         Value *OtherVal = A == Op1 ? B : A;
6362         return new ICmpInst(I.getPredicate(), OtherVal,
6363                             Constant::getNullValue(A->getType()));
6364       }
6365
6366       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6367         // A^c1 == C^c2 --> A == C^(c1^c2)
6368         ConstantInt *C1, *C2;
6369         if (match(B, m_ConstantInt(C1)) &&
6370             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6371           Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6372           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6373           return new ICmpInst(I.getPredicate(), A,
6374                               InsertNewInstBefore(Xor, I));
6375         }
6376         
6377         // A^B == A^D -> B == D
6378         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6379         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6380         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6381         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6382       }
6383     }
6384     
6385     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6386         (A == Op0 || B == Op0)) {
6387       // A == (A^B)  ->  B == 0
6388       Value *OtherVal = A == Op0 ? B : A;
6389       return new ICmpInst(I.getPredicate(), OtherVal,
6390                           Constant::getNullValue(A->getType()));
6391     }
6392
6393     // (A-B) == A  ->  B == 0
6394     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6395       return new ICmpInst(I.getPredicate(), B, 
6396                           Constant::getNullValue(B->getType()));
6397
6398     // A == (A-B)  ->  B == 0
6399     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6400       return new ICmpInst(I.getPredicate(), B,
6401                           Constant::getNullValue(B->getType()));
6402     
6403     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6404     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6405         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6406         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6407       Value *X = 0, *Y = 0, *Z = 0;
6408       
6409       if (A == C) {
6410         X = B; Y = D; Z = A;
6411       } else if (A == D) {
6412         X = B; Y = C; Z = A;
6413       } else if (B == C) {
6414         X = A; Y = D; Z = B;
6415       } else if (B == D) {
6416         X = A; Y = C; Z = B;
6417       }
6418       
6419       if (X) {   // Build (X^Y) & Z
6420         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6421         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6422         I.setOperand(0, Op1);
6423         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6424         return &I;
6425       }
6426     }
6427   }
6428   return Changed ? &I : 0;
6429 }
6430
6431
6432 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6433 /// and CmpRHS are both known to be integer constants.
6434 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6435                                           ConstantInt *DivRHS) {
6436   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6437   const APInt &CmpRHSV = CmpRHS->getValue();
6438   
6439   // FIXME: If the operand types don't match the type of the divide 
6440   // then don't attempt this transform. The code below doesn't have the
6441   // logic to deal with a signed divide and an unsigned compare (and
6442   // vice versa). This is because (x /s C1) <s C2  produces different 
6443   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6444   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6445   // work. :(  The if statement below tests that condition and bails 
6446   // if it finds it. 
6447   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6448   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6449     return 0;
6450   if (DivRHS->isZero())
6451     return 0; // The ProdOV computation fails on divide by zero.
6452   if (DivIsSigned && DivRHS->isAllOnesValue())
6453     return 0; // The overflow computation also screws up here
6454   if (DivRHS->isOne())
6455     return 0; // Not worth bothering, and eliminates some funny cases
6456               // with INT_MIN.
6457
6458   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6459   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6460   // C2 (CI). By solving for X we can turn this into a range check 
6461   // instead of computing a divide. 
6462   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6463
6464   // Determine if the product overflows by seeing if the product is
6465   // not equal to the divide. Make sure we do the same kind of divide
6466   // as in the LHS instruction that we're folding. 
6467   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6468                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6469
6470   // Get the ICmp opcode
6471   ICmpInst::Predicate Pred = ICI.getPredicate();
6472
6473   // Figure out the interval that is being checked.  For example, a comparison
6474   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6475   // Compute this interval based on the constants involved and the signedness of
6476   // the compare/divide.  This computes a half-open interval, keeping track of
6477   // whether either value in the interval overflows.  After analysis each
6478   // overflow variable is set to 0 if it's corresponding bound variable is valid
6479   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6480   int LoOverflow = 0, HiOverflow = 0;
6481   ConstantInt *LoBound = 0, *HiBound = 0;
6482   
6483   if (!DivIsSigned) {  // udiv
6484     // e.g. X/5 op 3  --> [15, 20)
6485     LoBound = Prod;
6486     HiOverflow = LoOverflow = ProdOV;
6487     if (!HiOverflow)
6488       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
6489   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6490     if (CmpRHSV == 0) {       // (X / pos) op 0
6491       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6492       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6493       HiBound = DivRHS;
6494     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6495       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6496       HiOverflow = LoOverflow = ProdOV;
6497       if (!HiOverflow)
6498         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6499     } else {                       // (X / pos) op neg
6500       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6501       HiBound = AddOne(Prod);
6502       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6503       if (!LoOverflow) {
6504         ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6505         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6506                                      true) ? -1 : 0;
6507        }
6508     }
6509   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6510     if (CmpRHSV == 0) {       // (X / neg) op 0
6511       // e.g. X/-5 op 0  --> [-4, 5)
6512       LoBound = AddOne(DivRHS);
6513       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6514       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6515         HiOverflow = 1;            // [INTMIN+1, overflow)
6516         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6517       }
6518     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6519       // e.g. X/-5 op 3  --> [-19, -14)
6520       HiBound = AddOne(Prod);
6521       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6522       if (!LoOverflow)
6523         LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
6524     } else {                       // (X / neg) op neg
6525       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6526       LoOverflow = HiOverflow = ProdOV;
6527       if (!HiOverflow)
6528         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
6529     }
6530     
6531     // Dividing by a negative swaps the condition.  LT <-> GT
6532     Pred = ICmpInst::getSwappedPredicate(Pred);
6533   }
6534
6535   Value *X = DivI->getOperand(0);
6536   switch (Pred) {
6537   default: assert(0 && "Unhandled icmp opcode!");
6538   case ICmpInst::ICMP_EQ:
6539     if (LoOverflow && HiOverflow)
6540       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6541     else if (HiOverflow)
6542       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6543                           ICmpInst::ICMP_UGE, X, LoBound);
6544     else if (LoOverflow)
6545       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6546                           ICmpInst::ICMP_ULT, X, HiBound);
6547     else
6548       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6549   case ICmpInst::ICMP_NE:
6550     if (LoOverflow && HiOverflow)
6551       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6552     else if (HiOverflow)
6553       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6554                           ICmpInst::ICMP_ULT, X, LoBound);
6555     else if (LoOverflow)
6556       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6557                           ICmpInst::ICMP_UGE, X, HiBound);
6558     else
6559       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6560   case ICmpInst::ICMP_ULT:
6561   case ICmpInst::ICMP_SLT:
6562     if (LoOverflow == +1)   // Low bound is greater than input range.
6563       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6564     if (LoOverflow == -1)   // Low bound is less than input range.
6565       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6566     return new ICmpInst(Pred, X, LoBound);
6567   case ICmpInst::ICMP_UGT:
6568   case ICmpInst::ICMP_SGT:
6569     if (HiOverflow == +1)       // High bound greater than input range.
6570       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6571     else if (HiOverflow == -1)  // High bound less than input range.
6572       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6573     if (Pred == ICmpInst::ICMP_UGT)
6574       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6575     else
6576       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6577   }
6578 }
6579
6580
6581 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6582 ///
6583 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6584                                                           Instruction *LHSI,
6585                                                           ConstantInt *RHS) {
6586   const APInt &RHSV = RHS->getValue();
6587   
6588   switch (LHSI->getOpcode()) {
6589   case Instruction::Trunc:
6590     if (ICI.isEquality() && LHSI->hasOneUse()) {
6591       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6592       // of the high bits truncated out of x are known.
6593       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6594              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6595       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6596       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6597       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6598       
6599       // If all the high bits are known, we can do this xform.
6600       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6601         // Pull in the high bits from known-ones set.
6602         APInt NewRHS(RHS->getValue());
6603         NewRHS.zext(SrcBits);
6604         NewRHS |= KnownOne;
6605         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6606                             ConstantInt::get(NewRHS));
6607       }
6608     }
6609     break;
6610       
6611   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6612     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6613       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6614       // fold the xor.
6615       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6616           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6617         Value *CompareVal = LHSI->getOperand(0);
6618         
6619         // If the sign bit of the XorCST is not set, there is no change to
6620         // the operation, just stop using the Xor.
6621         if (!XorCST->getValue().isNegative()) {
6622           ICI.setOperand(0, CompareVal);
6623           AddToWorkList(LHSI);
6624           return &ICI;
6625         }
6626         
6627         // Was the old condition true if the operand is positive?
6628         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6629         
6630         // If so, the new one isn't.
6631         isTrueIfPositive ^= true;
6632         
6633         if (isTrueIfPositive)
6634           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6635         else
6636           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6637       }
6638
6639       if (LHSI->hasOneUse()) {
6640         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6641         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6642           const APInt &SignBit = XorCST->getValue();
6643           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6644                                          ? ICI.getUnsignedPredicate()
6645                                          : ICI.getSignedPredicate();
6646           return new ICmpInst(Pred, LHSI->getOperand(0),
6647                               ConstantInt::get(RHSV ^ SignBit));
6648         }
6649
6650         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6651         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6652           const APInt &NotSignBit = XorCST->getValue();
6653           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6654                                          ? ICI.getUnsignedPredicate()
6655                                          : ICI.getSignedPredicate();
6656           Pred = ICI.getSwappedPredicate(Pred);
6657           return new ICmpInst(Pred, LHSI->getOperand(0),
6658                               ConstantInt::get(RHSV ^ NotSignBit));
6659         }
6660       }
6661     }
6662     break;
6663   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6664     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6665         LHSI->getOperand(0)->hasOneUse()) {
6666       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6667       
6668       // If the LHS is an AND of a truncating cast, we can widen the
6669       // and/compare to be the input width without changing the value
6670       // produced, eliminating a cast.
6671       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6672         // We can do this transformation if either the AND constant does not
6673         // have its sign bit set or if it is an equality comparison. 
6674         // Extending a relational comparison when we're checking the sign
6675         // bit would not work.
6676         if (Cast->hasOneUse() &&
6677             (ICI.isEquality() ||
6678              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6679           uint32_t BitWidth = 
6680             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6681           APInt NewCST = AndCST->getValue();
6682           NewCST.zext(BitWidth);
6683           APInt NewCI = RHSV;
6684           NewCI.zext(BitWidth);
6685           Instruction *NewAnd = 
6686             BinaryOperator::CreateAnd(Cast->getOperand(0),
6687                                       ConstantInt::get(NewCST),LHSI->getName());
6688           InsertNewInstBefore(NewAnd, ICI);
6689           return new ICmpInst(ICI.getPredicate(), NewAnd,
6690                               ConstantInt::get(NewCI));
6691         }
6692       }
6693       
6694       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6695       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6696       // happens a LOT in code produced by the C front-end, for bitfield
6697       // access.
6698       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6699       if (Shift && !Shift->isShift())
6700         Shift = 0;
6701       
6702       ConstantInt *ShAmt;
6703       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6704       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6705       const Type *AndTy = AndCST->getType();          // Type of the and.
6706       
6707       // We can fold this as long as we can't shift unknown bits
6708       // into the mask.  This can only happen with signed shift
6709       // rights, as they sign-extend.
6710       if (ShAmt) {
6711         bool CanFold = Shift->isLogicalShift();
6712         if (!CanFold) {
6713           // To test for the bad case of the signed shr, see if any
6714           // of the bits shifted in could be tested after the mask.
6715           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6716           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6717           
6718           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6719           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6720                AndCST->getValue()) == 0)
6721             CanFold = true;
6722         }
6723         
6724         if (CanFold) {
6725           Constant *NewCst;
6726           if (Shift->getOpcode() == Instruction::Shl)
6727             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6728           else
6729             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6730           
6731           // Check to see if we are shifting out any of the bits being
6732           // compared.
6733           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6734             // If we shifted bits out, the fold is not going to work out.
6735             // As a special case, check to see if this means that the
6736             // result is always true or false now.
6737             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6738               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6739             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6740               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6741           } else {
6742             ICI.setOperand(1, NewCst);
6743             Constant *NewAndCST;
6744             if (Shift->getOpcode() == Instruction::Shl)
6745               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6746             else
6747               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6748             LHSI->setOperand(1, NewAndCST);
6749             LHSI->setOperand(0, Shift->getOperand(0));
6750             AddToWorkList(Shift); // Shift is dead.
6751             AddUsesToWorkList(ICI);
6752             return &ICI;
6753           }
6754         }
6755       }
6756       
6757       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6758       // preferable because it allows the C<<Y expression to be hoisted out
6759       // of a loop if Y is invariant and X is not.
6760       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6761           ICI.isEquality() && !Shift->isArithmeticShift() &&
6762           !isa<Constant>(Shift->getOperand(0))) {
6763         // Compute C << Y.
6764         Value *NS;
6765         if (Shift->getOpcode() == Instruction::LShr) {
6766           NS = BinaryOperator::CreateShl(AndCST, 
6767                                          Shift->getOperand(1), "tmp");
6768         } else {
6769           // Insert a logical shift.
6770           NS = BinaryOperator::CreateLShr(AndCST,
6771                                           Shift->getOperand(1), "tmp");
6772         }
6773         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6774         
6775         // Compute X & (C << Y).
6776         Instruction *NewAnd = 
6777           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6778         InsertNewInstBefore(NewAnd, ICI);
6779         
6780         ICI.setOperand(0, NewAnd);
6781         return &ICI;
6782       }
6783     }
6784     break;
6785     
6786   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6787     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6788     if (!ShAmt) break;
6789     
6790     uint32_t TypeBits = RHSV.getBitWidth();
6791     
6792     // Check that the shift amount is in range.  If not, don't perform
6793     // undefined shifts.  When the shift is visited it will be
6794     // simplified.
6795     if (ShAmt->uge(TypeBits))
6796       break;
6797     
6798     if (ICI.isEquality()) {
6799       // If we are comparing against bits always shifted out, the
6800       // comparison cannot succeed.
6801       Constant *Comp =
6802         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6803       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6804         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6805         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6806         return ReplaceInstUsesWith(ICI, Cst);
6807       }
6808       
6809       if (LHSI->hasOneUse()) {
6810         // Otherwise strength reduce the shift into an and.
6811         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6812         Constant *Mask =
6813           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6814         
6815         Instruction *AndI =
6816           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6817                                     Mask, LHSI->getName()+".mask");
6818         Value *And = InsertNewInstBefore(AndI, ICI);
6819         return new ICmpInst(ICI.getPredicate(), And,
6820                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
6821       }
6822     }
6823     
6824     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6825     bool TrueIfSigned = false;
6826     if (LHSI->hasOneUse() &&
6827         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6828       // (X << 31) <s 0  --> (X&1) != 0
6829       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6830                                            (TypeBits-ShAmt->getZExtValue()-1));
6831       Instruction *AndI =
6832         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6833                                   Mask, LHSI->getName()+".mask");
6834       Value *And = InsertNewInstBefore(AndI, ICI);
6835       
6836       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6837                           And, Constant::getNullValue(And->getType()));
6838     }
6839     break;
6840   }
6841     
6842   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6843   case Instruction::AShr: {
6844     // Only handle equality comparisons of shift-by-constant.
6845     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6846     if (!ShAmt || !ICI.isEquality()) break;
6847
6848     // Check that the shift amount is in range.  If not, don't perform
6849     // undefined shifts.  When the shift is visited it will be
6850     // simplified.
6851     uint32_t TypeBits = RHSV.getBitWidth();
6852     if (ShAmt->uge(TypeBits))
6853       break;
6854     
6855     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6856       
6857     // If we are comparing against bits always shifted out, the
6858     // comparison cannot succeed.
6859     APInt Comp = RHSV << ShAmtVal;
6860     if (LHSI->getOpcode() == Instruction::LShr)
6861       Comp = Comp.lshr(ShAmtVal);
6862     else
6863       Comp = Comp.ashr(ShAmtVal);
6864     
6865     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6866       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6867       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6868       return ReplaceInstUsesWith(ICI, Cst);
6869     }
6870     
6871     // Otherwise, check to see if the bits shifted out are known to be zero.
6872     // If so, we can compare against the unshifted value:
6873     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6874     if (LHSI->hasOneUse() &&
6875         MaskedValueIsZero(LHSI->getOperand(0), 
6876                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6877       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6878                           ConstantExpr::getShl(RHS, ShAmt));
6879     }
6880       
6881     if (LHSI->hasOneUse()) {
6882       // Otherwise strength reduce the shift into an and.
6883       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6884       Constant *Mask = ConstantInt::get(Val);
6885       
6886       Instruction *AndI =
6887         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6888                                   Mask, LHSI->getName()+".mask");
6889       Value *And = InsertNewInstBefore(AndI, ICI);
6890       return new ICmpInst(ICI.getPredicate(), And,
6891                           ConstantExpr::getShl(RHS, ShAmt));
6892     }
6893     break;
6894   }
6895     
6896   case Instruction::SDiv:
6897   case Instruction::UDiv:
6898     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6899     // Fold this div into the comparison, producing a range check. 
6900     // Determine, based on the divide type, what the range is being 
6901     // checked.  If there is an overflow on the low or high side, remember 
6902     // it, otherwise compute the range [low, hi) bounding the new value.
6903     // See: InsertRangeTest above for the kinds of replacements possible.
6904     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6905       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6906                                           DivRHS))
6907         return R;
6908     break;
6909
6910   case Instruction::Add:
6911     // Fold: icmp pred (add, X, C1), C2
6912
6913     if (!ICI.isEquality()) {
6914       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6915       if (!LHSC) break;
6916       const APInt &LHSV = LHSC->getValue();
6917
6918       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6919                             .subtract(LHSV);
6920
6921       if (ICI.isSignedPredicate()) {
6922         if (CR.getLower().isSignBit()) {
6923           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6924                               ConstantInt::get(CR.getUpper()));
6925         } else if (CR.getUpper().isSignBit()) {
6926           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6927                               ConstantInt::get(CR.getLower()));
6928         }
6929       } else {
6930         if (CR.getLower().isMinValue()) {
6931           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6932                               ConstantInt::get(CR.getUpper()));
6933         } else if (CR.getUpper().isMinValue()) {
6934           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6935                               ConstantInt::get(CR.getLower()));
6936         }
6937       }
6938     }
6939     break;
6940   }
6941   
6942   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6943   if (ICI.isEquality()) {
6944     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6945     
6946     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6947     // the second operand is a constant, simplify a bit.
6948     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6949       switch (BO->getOpcode()) {
6950       case Instruction::SRem:
6951         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6952         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6953           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6954           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6955             Instruction *NewRem =
6956               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6957                                          BO->getName());
6958             InsertNewInstBefore(NewRem, ICI);
6959             return new ICmpInst(ICI.getPredicate(), NewRem, 
6960                                 Constant::getNullValue(BO->getType()));
6961           }
6962         }
6963         break;
6964       case Instruction::Add:
6965         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6966         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6967           if (BO->hasOneUse())
6968             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6969                                 Subtract(RHS, BOp1C));
6970         } else if (RHSV == 0) {
6971           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6972           // efficiently invertible, or if the add has just this one use.
6973           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6974           
6975           if (Value *NegVal = dyn_castNegVal(BOp1))
6976             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6977           else if (Value *NegVal = dyn_castNegVal(BOp0))
6978             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6979           else if (BO->hasOneUse()) {
6980             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6981             InsertNewInstBefore(Neg, ICI);
6982             Neg->takeName(BO);
6983             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6984           }
6985         }
6986         break;
6987       case Instruction::Xor:
6988         // For the xor case, we can xor two constants together, eliminating
6989         // the explicit xor.
6990         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6991           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6992                               ConstantExpr::getXor(RHS, BOC));
6993         
6994         // FALLTHROUGH
6995       case Instruction::Sub:
6996         // Replace (([sub|xor] A, B) != 0) with (A != B)
6997         if (RHSV == 0)
6998           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6999                               BO->getOperand(1));
7000         break;
7001         
7002       case Instruction::Or:
7003         // If bits are being or'd in that are not present in the constant we
7004         // are comparing against, then the comparison could never succeed!
7005         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7006           Constant *NotCI = ConstantExpr::getNot(RHS);
7007           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7008             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
7009                                                              isICMP_NE));
7010         }
7011         break;
7012         
7013       case Instruction::And:
7014         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7015           // If bits are being compared against that are and'd out, then the
7016           // comparison can never succeed!
7017           if ((RHSV & ~BOC->getValue()) != 0)
7018             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
7019                                                              isICMP_NE));
7020           
7021           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7022           if (RHS == BOC && RHSV.isPowerOf2())
7023             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7024                                 ICmpInst::ICMP_NE, LHSI,
7025                                 Constant::getNullValue(RHS->getType()));
7026           
7027           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7028           if (BOC->getValue().isSignBit()) {
7029             Value *X = BO->getOperand(0);
7030             Constant *Zero = Constant::getNullValue(X->getType());
7031             ICmpInst::Predicate pred = isICMP_NE ? 
7032               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7033             return new ICmpInst(pred, X, Zero);
7034           }
7035           
7036           // ((X & ~7) == 0) --> X < 8
7037           if (RHSV == 0 && isHighOnes(BOC)) {
7038             Value *X = BO->getOperand(0);
7039             Constant *NegX = ConstantExpr::getNeg(BOC);
7040             ICmpInst::Predicate pred = isICMP_NE ? 
7041               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7042             return new ICmpInst(pred, X, NegX);
7043           }
7044         }
7045       default: break;
7046       }
7047     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7048       // Handle icmp {eq|ne} <intrinsic>, intcst.
7049       if (II->getIntrinsicID() == Intrinsic::bswap) {
7050         AddToWorkList(II);
7051         ICI.setOperand(0, II->getOperand(1));
7052         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
7053         return &ICI;
7054       }
7055     }
7056   }
7057   return 0;
7058 }
7059
7060 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7061 /// We only handle extending casts so far.
7062 ///
7063 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7064   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7065   Value *LHSCIOp        = LHSCI->getOperand(0);
7066   const Type *SrcTy     = LHSCIOp->getType();
7067   const Type *DestTy    = LHSCI->getType();
7068   Value *RHSCIOp;
7069
7070   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7071   // integer type is the same size as the pointer type.
7072   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7073       getTargetData().getPointerSizeInBits() == 
7074          cast<IntegerType>(DestTy)->getBitWidth()) {
7075     Value *RHSOp = 0;
7076     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7077       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7078     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7079       RHSOp = RHSC->getOperand(0);
7080       // If the pointer types don't match, insert a bitcast.
7081       if (LHSCIOp->getType() != RHSOp->getType())
7082         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
7083     }
7084
7085     if (RHSOp)
7086       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7087   }
7088   
7089   // The code below only handles extension cast instructions, so far.
7090   // Enforce this.
7091   if (LHSCI->getOpcode() != Instruction::ZExt &&
7092       LHSCI->getOpcode() != Instruction::SExt)
7093     return 0;
7094
7095   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7096   bool isSignedCmp = ICI.isSignedPredicate();
7097
7098   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7099     // Not an extension from the same type?
7100     RHSCIOp = CI->getOperand(0);
7101     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7102       return 0;
7103     
7104     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7105     // and the other is a zext), then we can't handle this.
7106     if (CI->getOpcode() != LHSCI->getOpcode())
7107       return 0;
7108
7109     // Deal with equality cases early.
7110     if (ICI.isEquality())
7111       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7112
7113     // A signed comparison of sign extended values simplifies into a
7114     // signed comparison.
7115     if (isSignedCmp && isSignedExt)
7116       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7117
7118     // The other three cases all fold into an unsigned comparison.
7119     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7120   }
7121
7122   // If we aren't dealing with a constant on the RHS, exit early
7123   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7124   if (!CI)
7125     return 0;
7126
7127   // Compute the constant that would happen if we truncated to SrcTy then
7128   // reextended to DestTy.
7129   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7130   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
7131
7132   // If the re-extended constant didn't change...
7133   if (Res2 == CI) {
7134     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7135     // For example, we might have:
7136     //    %A = sext i16 %X to i32
7137     //    %B = icmp ugt i32 %A, 1330
7138     // It is incorrect to transform this into 
7139     //    %B = icmp ugt i16 %X, 1330
7140     // because %A may have negative value. 
7141     //
7142     // However, we allow this when the compare is EQ/NE, because they are
7143     // signless.
7144     if (isSignedExt == isSignedCmp || ICI.isEquality())
7145       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7146     return 0;
7147   }
7148
7149   // The re-extended constant changed so the constant cannot be represented 
7150   // in the shorter type. Consequently, we cannot emit a simple comparison.
7151
7152   // First, handle some easy cases. We know the result cannot be equal at this
7153   // point so handle the ICI.isEquality() cases
7154   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7155     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
7156   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7157     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
7158
7159   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7160   // should have been folded away previously and not enter in here.
7161   Value *Result;
7162   if (isSignedCmp) {
7163     // We're performing a signed comparison.
7164     if (cast<ConstantInt>(CI)->getValue().isNegative())
7165       Result = ConstantInt::getFalse();          // X < (small) --> false
7166     else
7167       Result = ConstantInt::getTrue();           // X < (large) --> true
7168   } else {
7169     // We're performing an unsigned comparison.
7170     if (isSignedExt) {
7171       // We're performing an unsigned comp with a sign extended value.
7172       // This is true if the input is >= 0. [aka >s -1]
7173       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
7174       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
7175                                    NegOne, ICI.getName()), ICI);
7176     } else {
7177       // Unsigned extend & unsigned compare -> always true.
7178       Result = ConstantInt::getTrue();
7179     }
7180   }
7181
7182   // Finally, return the value computed.
7183   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7184       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7185     return ReplaceInstUsesWith(ICI, Result);
7186
7187   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7188           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7189          "ICmp should be folded!");
7190   if (Constant *CI = dyn_cast<Constant>(Result))
7191     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7192   return BinaryOperator::CreateNot(Result);
7193 }
7194
7195 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7196   return commonShiftTransforms(I);
7197 }
7198
7199 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7200   return commonShiftTransforms(I);
7201 }
7202
7203 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7204   if (Instruction *R = commonShiftTransforms(I))
7205     return R;
7206   
7207   Value *Op0 = I.getOperand(0);
7208   
7209   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7210   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7211     if (CSI->isAllOnesValue())
7212       return ReplaceInstUsesWith(I, CSI);
7213   
7214   // See if we can turn a signed shr into an unsigned shr.
7215   if (!isa<VectorType>(I.getType())) {
7216     if (MaskedValueIsZero(Op0,
7217                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
7218       return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7219
7220     // Arithmetic shifting an all-sign-bit value is a no-op.
7221     unsigned NumSignBits = ComputeNumSignBits(Op0);
7222     if (NumSignBits == Op0->getType()->getPrimitiveSizeInBits())
7223       return ReplaceInstUsesWith(I, Op0);
7224   }
7225
7226   return 0;
7227 }
7228
7229 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7230   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7231   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7232
7233   // shl X, 0 == X and shr X, 0 == X
7234   // shl 0, X == 0 and shr 0, X == 0
7235   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7236       Op0 == Constant::getNullValue(Op0->getType()))
7237     return ReplaceInstUsesWith(I, Op0);
7238   
7239   if (isa<UndefValue>(Op0)) {            
7240     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7241       return ReplaceInstUsesWith(I, Op0);
7242     else                                    // undef << X -> 0, undef >>u X -> 0
7243       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7244   }
7245   if (isa<UndefValue>(Op1)) {
7246     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7247       return ReplaceInstUsesWith(I, Op0);          
7248     else                                     // X << undef, X >>u undef -> 0
7249       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7250   }
7251
7252   // See if we can fold away this shift.
7253   if (!isa<VectorType>(I.getType()) && SimplifyDemandedInstructionBits(I))
7254     return &I;
7255
7256   // Try to fold constant and into select arguments.
7257   if (isa<Constant>(Op0))
7258     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7259       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7260         return R;
7261
7262   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7263     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7264       return Res;
7265   return 0;
7266 }
7267
7268 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7269                                                BinaryOperator &I) {
7270   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7271
7272   // See if we can simplify any instructions used by the instruction whose sole 
7273   // purpose is to compute bits we don't care about.
7274   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
7275   
7276   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7277   // a signed shift.
7278   //
7279   if (Op1->uge(TypeBits)) {
7280     if (I.getOpcode() != Instruction::AShr)
7281       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7282     else {
7283       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7284       return &I;
7285     }
7286   }
7287   
7288   // ((X*C1) << C2) == (X * (C1 << C2))
7289   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7290     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7291       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7292         return BinaryOperator::CreateMul(BO->getOperand(0),
7293                                          ConstantExpr::getShl(BOOp, Op1));
7294   
7295   // Try to fold constant and into select arguments.
7296   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7297     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7298       return R;
7299   if (isa<PHINode>(Op0))
7300     if (Instruction *NV = FoldOpIntoPhi(I))
7301       return NV;
7302   
7303   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7304   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7305     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7306     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7307     // place.  Don't try to do this transformation in this case.  Also, we
7308     // require that the input operand is a shift-by-constant so that we have
7309     // confidence that the shifts will get folded together.  We could do this
7310     // xform in more cases, but it is unlikely to be profitable.
7311     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7312         isa<ConstantInt>(TrOp->getOperand(1))) {
7313       // Okay, we'll do this xform.  Make the shift of shift.
7314       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7315       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7316                                                 I.getName());
7317       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7318
7319       // For logical shifts, the truncation has the effect of making the high
7320       // part of the register be zeros.  Emulate this by inserting an AND to
7321       // clear the top bits as needed.  This 'and' will usually be zapped by
7322       // other xforms later if dead.
7323       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7324       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7325       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7326       
7327       // The mask we constructed says what the trunc would do if occurring
7328       // between the shifts.  We want to know the effect *after* the second
7329       // shift.  We know that it is a logical shift by a constant, so adjust the
7330       // mask as appropriate.
7331       if (I.getOpcode() == Instruction::Shl)
7332         MaskV <<= Op1->getZExtValue();
7333       else {
7334         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7335         MaskV = MaskV.lshr(Op1->getZExtValue());
7336       }
7337
7338       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
7339                                                    TI->getName());
7340       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7341
7342       // Return the value truncated to the interesting size.
7343       return new TruncInst(And, I.getType());
7344     }
7345   }
7346   
7347   if (Op0->hasOneUse()) {
7348     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7349       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7350       Value *V1, *V2;
7351       ConstantInt *CC;
7352       switch (Op0BO->getOpcode()) {
7353         default: break;
7354         case Instruction::Add:
7355         case Instruction::And:
7356         case Instruction::Or:
7357         case Instruction::Xor: {
7358           // These operators commute.
7359           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7360           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7361               match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
7362             Instruction *YS = BinaryOperator::CreateShl(
7363                                             Op0BO->getOperand(0), Op1,
7364                                             Op0BO->getName());
7365             InsertNewInstBefore(YS, I); // (Y << C)
7366             Instruction *X = 
7367               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7368                                      Op0BO->getOperand(1)->getName());
7369             InsertNewInstBefore(X, I);  // (X + (Y << C))
7370             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7371             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7372                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7373           }
7374           
7375           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7376           Value *Op0BOOp1 = Op0BO->getOperand(1);
7377           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7378               match(Op0BOOp1, 
7379                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7380                           m_ConstantInt(CC))) &&
7381               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7382             Instruction *YS = BinaryOperator::CreateShl(
7383                                                      Op0BO->getOperand(0), Op1,
7384                                                      Op0BO->getName());
7385             InsertNewInstBefore(YS, I); // (Y << C)
7386             Instruction *XM =
7387               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7388                                         V1->getName()+".mask");
7389             InsertNewInstBefore(XM, I); // X & (CC << C)
7390             
7391             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7392           }
7393         }
7394           
7395         // FALL THROUGH.
7396         case Instruction::Sub: {
7397           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7398           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7399               match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
7400             Instruction *YS = BinaryOperator::CreateShl(
7401                                                      Op0BO->getOperand(1), Op1,
7402                                                      Op0BO->getName());
7403             InsertNewInstBefore(YS, I); // (Y << C)
7404             Instruction *X =
7405               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7406                                      Op0BO->getOperand(0)->getName());
7407             InsertNewInstBefore(X, I);  // (X + (Y << C))
7408             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7409             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7410                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7411           }
7412           
7413           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7414           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7415               match(Op0BO->getOperand(0),
7416                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7417                           m_ConstantInt(CC))) && V2 == Op1 &&
7418               cast<BinaryOperator>(Op0BO->getOperand(0))
7419                   ->getOperand(0)->hasOneUse()) {
7420             Instruction *YS = BinaryOperator::CreateShl(
7421                                                      Op0BO->getOperand(1), Op1,
7422                                                      Op0BO->getName());
7423             InsertNewInstBefore(YS, I); // (Y << C)
7424             Instruction *XM =
7425               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7426                                         V1->getName()+".mask");
7427             InsertNewInstBefore(XM, I); // X & (CC << C)
7428             
7429             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7430           }
7431           
7432           break;
7433         }
7434       }
7435       
7436       
7437       // If the operand is an bitwise operator with a constant RHS, and the
7438       // shift is the only use, we can pull it out of the shift.
7439       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7440         bool isValid = true;     // Valid only for And, Or, Xor
7441         bool highBitSet = false; // Transform if high bit of constant set?
7442         
7443         switch (Op0BO->getOpcode()) {
7444           default: isValid = false; break;   // Do not perform transform!
7445           case Instruction::Add:
7446             isValid = isLeftShift;
7447             break;
7448           case Instruction::Or:
7449           case Instruction::Xor:
7450             highBitSet = false;
7451             break;
7452           case Instruction::And:
7453             highBitSet = true;
7454             break;
7455         }
7456         
7457         // If this is a signed shift right, and the high bit is modified
7458         // by the logical operation, do not perform the transformation.
7459         // The highBitSet boolean indicates the value of the high bit of
7460         // the constant which would cause it to be modified for this
7461         // operation.
7462         //
7463         if (isValid && I.getOpcode() == Instruction::AShr)
7464           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7465         
7466         if (isValid) {
7467           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7468           
7469           Instruction *NewShift =
7470             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7471           InsertNewInstBefore(NewShift, I);
7472           NewShift->takeName(Op0BO);
7473           
7474           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7475                                         NewRHS);
7476         }
7477       }
7478     }
7479   }
7480   
7481   // Find out if this is a shift of a shift by a constant.
7482   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7483   if (ShiftOp && !ShiftOp->isShift())
7484     ShiftOp = 0;
7485   
7486   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7487     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7488     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7489     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7490     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7491     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7492     Value *X = ShiftOp->getOperand(0);
7493     
7494     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7495     
7496     const IntegerType *Ty = cast<IntegerType>(I.getType());
7497     
7498     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7499     if (I.getOpcode() == ShiftOp->getOpcode()) {
7500       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7501       // saturates.
7502       if (AmtSum >= TypeBits) {
7503         if (I.getOpcode() != Instruction::AShr)
7504           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7505         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7506       }
7507       
7508       return BinaryOperator::Create(I.getOpcode(), X,
7509                                     ConstantInt::get(Ty, AmtSum));
7510     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7511                I.getOpcode() == Instruction::AShr) {
7512       if (AmtSum >= TypeBits)
7513         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7514       
7515       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7516       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7517     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7518                I.getOpcode() == Instruction::LShr) {
7519       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7520       if (AmtSum >= TypeBits)
7521         AmtSum = TypeBits-1;
7522       
7523       Instruction *Shift =
7524         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7525       InsertNewInstBefore(Shift, I);
7526
7527       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7528       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7529     }
7530     
7531     // Okay, if we get here, one shift must be left, and the other shift must be
7532     // right.  See if the amounts are equal.
7533     if (ShiftAmt1 == ShiftAmt2) {
7534       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7535       if (I.getOpcode() == Instruction::Shl) {
7536         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7537         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7538       }
7539       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7540       if (I.getOpcode() == Instruction::LShr) {
7541         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7542         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7543       }
7544       // We can simplify ((X << C) >>s C) into a trunc + sext.
7545       // NOTE: we could do this for any C, but that would make 'unusual' integer
7546       // types.  For now, just stick to ones well-supported by the code
7547       // generators.
7548       const Type *SExtType = 0;
7549       switch (Ty->getBitWidth() - ShiftAmt1) {
7550       case 1  :
7551       case 8  :
7552       case 16 :
7553       case 32 :
7554       case 64 :
7555       case 128:
7556         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7557         break;
7558       default: break;
7559       }
7560       if (SExtType) {
7561         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7562         InsertNewInstBefore(NewTrunc, I);
7563         return new SExtInst(NewTrunc, Ty);
7564       }
7565       // Otherwise, we can't handle it yet.
7566     } else if (ShiftAmt1 < ShiftAmt2) {
7567       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7568       
7569       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7570       if (I.getOpcode() == Instruction::Shl) {
7571         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7572                ShiftOp->getOpcode() == Instruction::AShr);
7573         Instruction *Shift =
7574           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7575         InsertNewInstBefore(Shift, I);
7576         
7577         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7578         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7579       }
7580       
7581       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7582       if (I.getOpcode() == Instruction::LShr) {
7583         assert(ShiftOp->getOpcode() == Instruction::Shl);
7584         Instruction *Shift =
7585           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7586         InsertNewInstBefore(Shift, I);
7587         
7588         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7589         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7590       }
7591       
7592       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7593     } else {
7594       assert(ShiftAmt2 < ShiftAmt1);
7595       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7596
7597       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7598       if (I.getOpcode() == Instruction::Shl) {
7599         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7600                ShiftOp->getOpcode() == Instruction::AShr);
7601         Instruction *Shift =
7602           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7603                                  ConstantInt::get(Ty, ShiftDiff));
7604         InsertNewInstBefore(Shift, I);
7605         
7606         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7607         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7608       }
7609       
7610       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7611       if (I.getOpcode() == Instruction::LShr) {
7612         assert(ShiftOp->getOpcode() == Instruction::Shl);
7613         Instruction *Shift =
7614           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7615         InsertNewInstBefore(Shift, I);
7616         
7617         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7618         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7619       }
7620       
7621       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7622     }
7623   }
7624   return 0;
7625 }
7626
7627
7628 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7629 /// expression.  If so, decompose it, returning some value X, such that Val is
7630 /// X*Scale+Offset.
7631 ///
7632 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7633                                         int &Offset) {
7634   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7635   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7636     Offset = CI->getZExtValue();
7637     Scale  = 0;
7638     return ConstantInt::get(Type::Int32Ty, 0);
7639   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7640     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7641       if (I->getOpcode() == Instruction::Shl) {
7642         // This is a value scaled by '1 << the shift amt'.
7643         Scale = 1U << RHS->getZExtValue();
7644         Offset = 0;
7645         return I->getOperand(0);
7646       } else if (I->getOpcode() == Instruction::Mul) {
7647         // This value is scaled by 'RHS'.
7648         Scale = RHS->getZExtValue();
7649         Offset = 0;
7650         return I->getOperand(0);
7651       } else if (I->getOpcode() == Instruction::Add) {
7652         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7653         // where C1 is divisible by C2.
7654         unsigned SubScale;
7655         Value *SubVal = 
7656           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7657         Offset += RHS->getZExtValue();
7658         Scale = SubScale;
7659         return SubVal;
7660       }
7661     }
7662   }
7663
7664   // Otherwise, we can't look past this.
7665   Scale = 1;
7666   Offset = 0;
7667   return Val;
7668 }
7669
7670
7671 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7672 /// try to eliminate the cast by moving the type information into the alloc.
7673 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7674                                                    AllocationInst &AI) {
7675   const PointerType *PTy = cast<PointerType>(CI.getType());
7676   
7677   // Remove any uses of AI that are dead.
7678   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7679   
7680   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7681     Instruction *User = cast<Instruction>(*UI++);
7682     if (isInstructionTriviallyDead(User)) {
7683       while (UI != E && *UI == User)
7684         ++UI; // If this instruction uses AI more than once, don't break UI.
7685       
7686       ++NumDeadInst;
7687       DOUT << "IC: DCE: " << *User;
7688       EraseInstFromFunction(*User);
7689     }
7690   }
7691   
7692   // Get the type really allocated and the type casted to.
7693   const Type *AllocElTy = AI.getAllocatedType();
7694   const Type *CastElTy = PTy->getElementType();
7695   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7696
7697   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7698   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7699   if (CastElTyAlign < AllocElTyAlign) return 0;
7700
7701   // If the allocation has multiple uses, only promote it if we are strictly
7702   // increasing the alignment of the resultant allocation.  If we keep it the
7703   // same, we open the door to infinite loops of various kinds.  (A reference
7704   // from a dbg.declare doesn't count as a use for this purpose.)
7705   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7706       CastElTyAlign == AllocElTyAlign) return 0;
7707
7708   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7709   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7710   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7711
7712   // See if we can satisfy the modulus by pulling a scale out of the array
7713   // size argument.
7714   unsigned ArraySizeScale;
7715   int ArrayOffset;
7716   Value *NumElements = // See if the array size is a decomposable linear expr.
7717     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7718  
7719   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7720   // do the xform.
7721   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7722       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7723
7724   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7725   Value *Amt = 0;
7726   if (Scale == 1) {
7727     Amt = NumElements;
7728   } else {
7729     // If the allocation size is constant, form a constant mul expression
7730     Amt = ConstantInt::get(Type::Int32Ty, Scale);
7731     if (isa<ConstantInt>(NumElements))
7732       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
7733     // otherwise multiply the amount and the number of elements
7734     else {
7735       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7736       Amt = InsertNewInstBefore(Tmp, AI);
7737     }
7738   }
7739   
7740   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7741     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
7742     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7743     Amt = InsertNewInstBefore(Tmp, AI);
7744   }
7745   
7746   AllocationInst *New;
7747   if (isa<MallocInst>(AI))
7748     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7749   else
7750     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7751   InsertNewInstBefore(New, AI);
7752   New->takeName(&AI);
7753   
7754   // If the allocation has one real use plus a dbg.declare, just remove the
7755   // declare.
7756   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7757     EraseInstFromFunction(*DI);
7758   }
7759   // If the allocation has multiple real uses, insert a cast and change all
7760   // things that used it to use the new cast.  This will also hack on CI, but it
7761   // will die soon.
7762   else if (!AI.hasOneUse()) {
7763     AddUsesToWorkList(AI);
7764     // New is the allocation instruction, pointer typed. AI is the original
7765     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7766     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7767     InsertNewInstBefore(NewCast, AI);
7768     AI.replaceAllUsesWith(NewCast);
7769   }
7770   return ReplaceInstUsesWith(CI, New);
7771 }
7772
7773 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7774 /// and return it as type Ty without inserting any new casts and without
7775 /// changing the computed value.  This is used by code that tries to decide
7776 /// whether promoting or shrinking integer operations to wider or smaller types
7777 /// will allow us to eliminate a truncate or extend.
7778 ///
7779 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7780 /// extension operation if Ty is larger.
7781 ///
7782 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7783 /// should return true if trunc(V) can be computed by computing V in the smaller
7784 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7785 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7786 /// efficiently truncated.
7787 ///
7788 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7789 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7790 /// the final result.
7791 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7792                                               unsigned CastOpc,
7793                                               int &NumCastsRemoved){
7794   // We can always evaluate constants in another type.
7795   if (isa<ConstantInt>(V))
7796     return true;
7797   
7798   Instruction *I = dyn_cast<Instruction>(V);
7799   if (!I) return false;
7800   
7801   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7802   
7803   // If this is an extension or truncate, we can often eliminate it.
7804   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7805     // If this is a cast from the destination type, we can trivially eliminate
7806     // it, and this will remove a cast overall.
7807     if (I->getOperand(0)->getType() == Ty) {
7808       // If the first operand is itself a cast, and is eliminable, do not count
7809       // this as an eliminable cast.  We would prefer to eliminate those two
7810       // casts first.
7811       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7812         ++NumCastsRemoved;
7813       return true;
7814     }
7815   }
7816
7817   // We can't extend or shrink something that has multiple uses: doing so would
7818   // require duplicating the instruction in general, which isn't profitable.
7819   if (!I->hasOneUse()) return false;
7820
7821   unsigned Opc = I->getOpcode();
7822   switch (Opc) {
7823   case Instruction::Add:
7824   case Instruction::Sub:
7825   case Instruction::Mul:
7826   case Instruction::And:
7827   case Instruction::Or:
7828   case Instruction::Xor:
7829     // These operators can all arbitrarily be extended or truncated.
7830     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7831                                       NumCastsRemoved) &&
7832            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7833                                       NumCastsRemoved);
7834
7835   case Instruction::Shl:
7836     // If we are truncating the result of this SHL, and if it's a shift of a
7837     // constant amount, we can always perform a SHL in a smaller type.
7838     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7839       uint32_t BitWidth = Ty->getBitWidth();
7840       if (BitWidth < OrigTy->getBitWidth() && 
7841           CI->getLimitedValue(BitWidth) < BitWidth)
7842         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7843                                           NumCastsRemoved);
7844     }
7845     break;
7846   case Instruction::LShr:
7847     // If this is a truncate of a logical shr, we can truncate it to a smaller
7848     // lshr iff we know that the bits we would otherwise be shifting in are
7849     // already zeros.
7850     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7851       uint32_t OrigBitWidth = OrigTy->getBitWidth();
7852       uint32_t BitWidth = Ty->getBitWidth();
7853       if (BitWidth < OrigBitWidth &&
7854           MaskedValueIsZero(I->getOperand(0),
7855             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7856           CI->getLimitedValue(BitWidth) < BitWidth) {
7857         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7858                                           NumCastsRemoved);
7859       }
7860     }
7861     break;
7862   case Instruction::ZExt:
7863   case Instruction::SExt:
7864   case Instruction::Trunc:
7865     // If this is the same kind of case as our original (e.g. zext+zext), we
7866     // can safely replace it.  Note that replacing it does not reduce the number
7867     // of casts in the input.
7868     if (Opc == CastOpc)
7869       return true;
7870
7871     // sext (zext ty1), ty2 -> zext ty2
7872     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7873       return true;
7874     break;
7875   case Instruction::Select: {
7876     SelectInst *SI = cast<SelectInst>(I);
7877     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7878                                       NumCastsRemoved) &&
7879            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7880                                       NumCastsRemoved);
7881   }
7882   case Instruction::PHI: {
7883     // We can change a phi if we can change all operands.
7884     PHINode *PN = cast<PHINode>(I);
7885     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7886       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7887                                       NumCastsRemoved))
7888         return false;
7889     return true;
7890   }
7891   default:
7892     // TODO: Can handle more cases here.
7893     break;
7894   }
7895   
7896   return false;
7897 }
7898
7899 /// EvaluateInDifferentType - Given an expression that 
7900 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7901 /// evaluate the expression.
7902 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7903                                              bool isSigned) {
7904   if (Constant *C = dyn_cast<Constant>(V))
7905     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7906
7907   // Otherwise, it must be an instruction.
7908   Instruction *I = cast<Instruction>(V);
7909   Instruction *Res = 0;
7910   unsigned Opc = I->getOpcode();
7911   switch (Opc) {
7912   case Instruction::Add:
7913   case Instruction::Sub:
7914   case Instruction::Mul:
7915   case Instruction::And:
7916   case Instruction::Or:
7917   case Instruction::Xor:
7918   case Instruction::AShr:
7919   case Instruction::LShr:
7920   case Instruction::Shl: {
7921     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7922     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7923     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7924     break;
7925   }    
7926   case Instruction::Trunc:
7927   case Instruction::ZExt:
7928   case Instruction::SExt:
7929     // If the source type of the cast is the type we're trying for then we can
7930     // just return the source.  There's no need to insert it because it is not
7931     // new.
7932     if (I->getOperand(0)->getType() == Ty)
7933       return I->getOperand(0);
7934     
7935     // Otherwise, must be the same type of cast, so just reinsert a new one.
7936     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7937                            Ty);
7938     break;
7939   case Instruction::Select: {
7940     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7941     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7942     Res = SelectInst::Create(I->getOperand(0), True, False);
7943     break;
7944   }
7945   case Instruction::PHI: {
7946     PHINode *OPN = cast<PHINode>(I);
7947     PHINode *NPN = PHINode::Create(Ty);
7948     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7949       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7950       NPN->addIncoming(V, OPN->getIncomingBlock(i));
7951     }
7952     Res = NPN;
7953     break;
7954   }
7955   default: 
7956     // TODO: Can handle more cases here.
7957     assert(0 && "Unreachable!");
7958     break;
7959   }
7960   
7961   Res->takeName(I);
7962   return InsertNewInstBefore(Res, *I);
7963 }
7964
7965 /// @brief Implement the transforms common to all CastInst visitors.
7966 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7967   Value *Src = CI.getOperand(0);
7968
7969   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7970   // eliminate it now.
7971   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7972     if (Instruction::CastOps opc = 
7973         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7974       // The first cast (CSrc) is eliminable so we need to fix up or replace
7975       // the second cast (CI). CSrc will then have a good chance of being dead.
7976       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7977     }
7978   }
7979
7980   // If we are casting a select then fold the cast into the select
7981   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7982     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7983       return NV;
7984
7985   // If we are casting a PHI then fold the cast into the PHI
7986   if (isa<PHINode>(Src))
7987     if (Instruction *NV = FoldOpIntoPhi(CI))
7988       return NV;
7989   
7990   return 0;
7991 }
7992
7993 /// FindElementAtOffset - Given a type and a constant offset, determine whether
7994 /// or not there is a sequence of GEP indices into the type that will land us at
7995 /// the specified offset.  If so, fill them into NewIndices and return the
7996 /// resultant element type, otherwise return null.
7997 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
7998                                        SmallVectorImpl<Value*> &NewIndices,
7999                                        const TargetData *TD) {
8000   if (!Ty->isSized()) return 0;
8001   
8002   // Start with the index over the outer type.  Note that the type size
8003   // might be zero (even if the offset isn't zero) if the indexed type
8004   // is something like [0 x {int, int}]
8005   const Type *IntPtrTy = TD->getIntPtrType();
8006   int64_t FirstIdx = 0;
8007   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8008     FirstIdx = Offset/TySize;
8009     Offset -= FirstIdx*TySize;
8010     
8011     // Handle hosts where % returns negative instead of values [0..TySize).
8012     if (Offset < 0) {
8013       --FirstIdx;
8014       Offset += TySize;
8015       assert(Offset >= 0);
8016     }
8017     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8018   }
8019   
8020   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8021     
8022   // Index into the types.  If we fail, set OrigBase to null.
8023   while (Offset) {
8024     // Indexing into tail padding between struct/array elements.
8025     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8026       return 0;
8027     
8028     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8029       const StructLayout *SL = TD->getStructLayout(STy);
8030       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8031              "Offset must stay within the indexed type");
8032       
8033       unsigned Elt = SL->getElementContainingOffset(Offset);
8034       NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
8035       
8036       Offset -= SL->getElementOffset(Elt);
8037       Ty = STy->getElementType(Elt);
8038     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8039       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8040       assert(EltSize && "Cannot index into a zero-sized array");
8041       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8042       Offset %= EltSize;
8043       Ty = AT->getElementType();
8044     } else {
8045       // Otherwise, we can't index into the middle of this atomic type, bail.
8046       return 0;
8047     }
8048   }
8049   
8050   return Ty;
8051 }
8052
8053 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8054 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8055   Value *Src = CI.getOperand(0);
8056   
8057   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8058     // If casting the result of a getelementptr instruction with no offset, turn
8059     // this into a cast of the original pointer!
8060     if (GEP->hasAllZeroIndices()) {
8061       // Changing the cast operand is usually not a good idea but it is safe
8062       // here because the pointer operand is being replaced with another 
8063       // pointer operand so the opcode doesn't need to change.
8064       AddToWorkList(GEP);
8065       CI.setOperand(0, GEP->getOperand(0));
8066       return &CI;
8067     }
8068     
8069     // If the GEP has a single use, and the base pointer is a bitcast, and the
8070     // GEP computes a constant offset, see if we can convert these three
8071     // instructions into fewer.  This typically happens with unions and other
8072     // non-type-safe code.
8073     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8074       if (GEP->hasAllConstantIndices()) {
8075         // We are guaranteed to get a constant from EmitGEPOffset.
8076         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8077         int64_t Offset = OffsetV->getSExtValue();
8078         
8079         // Get the base pointer input of the bitcast, and the type it points to.
8080         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8081         const Type *GEPIdxTy =
8082           cast<PointerType>(OrigBase->getType())->getElementType();
8083         SmallVector<Value*, 8> NewIndices;
8084         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
8085           // If we were able to index down into an element, create the GEP
8086           // and bitcast the result.  This eliminates one bitcast, potentially
8087           // two.
8088           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
8089                                                         NewIndices.begin(),
8090                                                         NewIndices.end(), "");
8091           InsertNewInstBefore(NGEP, CI);
8092           NGEP->takeName(GEP);
8093           
8094           if (isa<BitCastInst>(CI))
8095             return new BitCastInst(NGEP, CI.getType());
8096           assert(isa<PtrToIntInst>(CI));
8097           return new PtrToIntInst(NGEP, CI.getType());
8098         }
8099       }      
8100     }
8101   }
8102     
8103   return commonCastTransforms(CI);
8104 }
8105
8106 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8107 /// type like i42.  We don't want to introduce operations on random non-legal
8108 /// integer types where they don't already exist in the code.  In the future,
8109 /// we should consider making this based off target-data, so that 32-bit targets
8110 /// won't get i64 operations etc.
8111 static bool isSafeIntegerType(const Type *Ty) {
8112   switch (Ty->getPrimitiveSizeInBits()) {
8113   case 8:
8114   case 16:
8115   case 32:
8116   case 64:
8117     return true;
8118   default: 
8119     return false;
8120   }
8121 }
8122
8123 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
8124 /// integer types. This function implements the common transforms for all those
8125 /// cases.
8126 /// @brief Implement the transforms common to CastInst with integer operands
8127 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8128   if (Instruction *Result = commonCastTransforms(CI))
8129     return Result;
8130
8131   Value *Src = CI.getOperand(0);
8132   const Type *SrcTy = Src->getType();
8133   const Type *DestTy = CI.getType();
8134   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
8135   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
8136
8137   // See if we can simplify any instructions used by the LHS whose sole 
8138   // purpose is to compute bits we don't care about.
8139   if (SimplifyDemandedInstructionBits(CI))
8140     return &CI;
8141
8142   // If the source isn't an instruction or has more than one use then we
8143   // can't do anything more. 
8144   Instruction *SrcI = dyn_cast<Instruction>(Src);
8145   if (!SrcI || !Src->hasOneUse())
8146     return 0;
8147
8148   // Attempt to propagate the cast into the instruction for int->int casts.
8149   int NumCastsRemoved = 0;
8150   if (!isa<BitCastInst>(CI) &&
8151       // Only do this if the dest type is a simple type, don't convert the
8152       // expression tree to something weird like i93 unless the source is also
8153       // strange.
8154       (isSafeIntegerType(DestTy) || !isSafeIntegerType(SrcI->getType())) &&
8155       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
8156                                  CI.getOpcode(), NumCastsRemoved)) {
8157     // If this cast is a truncate, evaluting in a different type always
8158     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8159     // we need to do an AND to maintain the clear top-part of the computation,
8160     // so we require that the input have eliminated at least one cast.  If this
8161     // is a sign extension, we insert two new casts (to do the extension) so we
8162     // require that two casts have been eliminated.
8163     bool DoXForm = false;
8164     bool JustReplace = false;
8165     switch (CI.getOpcode()) {
8166     default:
8167       // All the others use floating point so we shouldn't actually 
8168       // get here because of the check above.
8169       assert(0 && "Unknown cast type");
8170     case Instruction::Trunc:
8171       DoXForm = true;
8172       break;
8173     case Instruction::ZExt: {
8174       DoXForm = NumCastsRemoved >= 1;
8175       if (!DoXForm && 0) {
8176         // If it's unnecessary to issue an AND to clear the high bits, it's
8177         // always profitable to do this xform.
8178         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8179         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8180         if (MaskedValueIsZero(TryRes, Mask))
8181           return ReplaceInstUsesWith(CI, TryRes);
8182         
8183         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8184           if (TryI->use_empty())
8185             EraseInstFromFunction(*TryI);
8186       }
8187       break;
8188     }
8189     case Instruction::SExt: {
8190       DoXForm = NumCastsRemoved >= 2;
8191       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8192         // If we do not have to emit the truncate + sext pair, then it's always
8193         // profitable to do this xform.
8194         //
8195         // It's not safe to eliminate the trunc + sext pair if one of the
8196         // eliminated cast is a truncate. e.g.
8197         // t2 = trunc i32 t1 to i16
8198         // t3 = sext i16 t2 to i32
8199         // !=
8200         // i32 t1
8201         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8202         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8203         if (NumSignBits > (DestBitSize - SrcBitSize))
8204           return ReplaceInstUsesWith(CI, TryRes);
8205         
8206         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8207           if (TryI->use_empty())
8208             EraseInstFromFunction(*TryI);
8209       }
8210       break;
8211     }
8212     }
8213     
8214     if (DoXForm) {
8215       DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8216            << " cast: " << CI;
8217       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8218                                            CI.getOpcode() == Instruction::SExt);
8219       if (JustReplace)
8220         // Just replace this cast with the result.
8221         return ReplaceInstUsesWith(CI, Res);
8222
8223       assert(Res->getType() == DestTy);
8224       switch (CI.getOpcode()) {
8225       default: assert(0 && "Unknown cast type!");
8226       case Instruction::Trunc:
8227       case Instruction::BitCast:
8228         // Just replace this cast with the result.
8229         return ReplaceInstUsesWith(CI, Res);
8230       case Instruction::ZExt: {
8231         assert(SrcBitSize < DestBitSize && "Not a zext?");
8232
8233         // If the high bits are already zero, just replace this cast with the
8234         // result.
8235         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8236         if (MaskedValueIsZero(Res, Mask))
8237           return ReplaceInstUsesWith(CI, Res);
8238
8239         // We need to emit an AND to clear the high bits.
8240         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
8241                                                             SrcBitSize));
8242         return BinaryOperator::CreateAnd(Res, C);
8243       }
8244       case Instruction::SExt: {
8245         // If the high bits are already filled with sign bit, just replace this
8246         // cast with the result.
8247         unsigned NumSignBits = ComputeNumSignBits(Res);
8248         if (NumSignBits > (DestBitSize - SrcBitSize))
8249           return ReplaceInstUsesWith(CI, Res);
8250
8251         // We need to emit a cast to truncate, then a cast to sext.
8252         return CastInst::Create(Instruction::SExt,
8253             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8254                              CI), DestTy);
8255       }
8256       }
8257     }
8258   }
8259   
8260   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8261   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8262
8263   switch (SrcI->getOpcode()) {
8264   case Instruction::Add:
8265   case Instruction::Mul:
8266   case Instruction::And:
8267   case Instruction::Or:
8268   case Instruction::Xor:
8269     // If we are discarding information, rewrite.
8270     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8271       // Don't insert two casts if they cannot be eliminated.  We allow 
8272       // two casts to be inserted if the sizes are the same.  This could 
8273       // only be converting signedness, which is a noop.
8274       if (DestBitSize == SrcBitSize || 
8275           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8276           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8277         Instruction::CastOps opcode = CI.getOpcode();
8278         Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8279         Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8280         return BinaryOperator::Create(
8281             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8282       }
8283     }
8284
8285     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8286     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8287         SrcI->getOpcode() == Instruction::Xor &&
8288         Op1 == ConstantInt::getTrue() &&
8289         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8290       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8291       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
8292     }
8293     break;
8294   case Instruction::SDiv:
8295   case Instruction::UDiv:
8296   case Instruction::SRem:
8297   case Instruction::URem:
8298     // If we are just changing the sign, rewrite.
8299     if (DestBitSize == SrcBitSize) {
8300       // Don't insert two casts if they cannot be eliminated.  We allow 
8301       // two casts to be inserted if the sizes are the same.  This could 
8302       // only be converting signedness, which is a noop.
8303       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
8304           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8305         Value *Op0c = InsertCastBefore(Instruction::BitCast, 
8306                                        Op0, DestTy, *SrcI);
8307         Value *Op1c = InsertCastBefore(Instruction::BitCast, 
8308                                        Op1, DestTy, *SrcI);
8309         return BinaryOperator::Create(
8310           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8311       }
8312     }
8313     break;
8314
8315   case Instruction::Shl:
8316     // Allow changing the sign of the source operand.  Do not allow 
8317     // changing the size of the shift, UNLESS the shift amount is a 
8318     // constant.  We must not change variable sized shifts to a smaller 
8319     // size, because it is undefined to shift more bits out than exist 
8320     // in the value.
8321     if (DestBitSize == SrcBitSize ||
8322         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
8323       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8324           Instruction::BitCast : Instruction::Trunc);
8325       Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8326       Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8327       return BinaryOperator::CreateShl(Op0c, Op1c);
8328     }
8329     break;
8330   case Instruction::AShr:
8331     // If this is a signed shr, and if all bits shifted in are about to be
8332     // truncated off, turn it into an unsigned shr to allow greater
8333     // simplifications.
8334     if (DestBitSize < SrcBitSize &&
8335         isa<ConstantInt>(Op1)) {
8336       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
8337       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8338         // Insert the new logical shift right.
8339         return BinaryOperator::CreateLShr(Op0, Op1);
8340       }
8341     }
8342     break;
8343   }
8344   return 0;
8345 }
8346
8347 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8348   if (Instruction *Result = commonIntCastTransforms(CI))
8349     return Result;
8350   
8351   Value *Src = CI.getOperand(0);
8352   const Type *Ty = CI.getType();
8353   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
8354   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
8355
8356   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8357   if (DestBitWidth == 1) {
8358     Constant *One = ConstantInt::get(Src->getType(), 1);
8359     Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8360     Value *Zero = Constant::getNullValue(Src->getType());
8361     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8362   }
8363   
8364   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8365   ConstantInt *ShAmtV = 0;
8366   Value *ShiftOp = 0;
8367   if (Src->hasOneUse() &&
8368       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8369     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8370     
8371     // Get a mask for the bits shifting in.
8372     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8373     if (MaskedValueIsZero(ShiftOp, Mask)) {
8374       if (ShAmt >= DestBitWidth)        // All zeros.
8375         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8376       
8377       // Okay, we can shrink this.  Truncate the input, then return a new
8378       // shift.
8379       Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8380       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8381       return BinaryOperator::CreateLShr(V1, V2);
8382     }
8383   }
8384   
8385   return 0;
8386 }
8387
8388 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8389 /// in order to eliminate the icmp.
8390 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8391                                              bool DoXform) {
8392   // If we are just checking for a icmp eq of a single bit and zext'ing it
8393   // to an integer, then shift the bit to the appropriate place and then
8394   // cast to integer to avoid the comparison.
8395   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8396     const APInt &Op1CV = Op1C->getValue();
8397       
8398     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8399     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8400     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8401         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8402       if (!DoXform) return ICI;
8403
8404       Value *In = ICI->getOperand(0);
8405       Value *Sh = ConstantInt::get(In->getType(),
8406                                    In->getType()->getPrimitiveSizeInBits()-1);
8407       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8408                                                         In->getName()+".lobit"),
8409                                CI);
8410       if (In->getType() != CI.getType())
8411         In = CastInst::CreateIntegerCast(In, CI.getType(),
8412                                          false/*ZExt*/, "tmp", &CI);
8413
8414       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8415         Constant *One = ConstantInt::get(In->getType(), 1);
8416         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8417                                                          In->getName()+".not"),
8418                                  CI);
8419       }
8420
8421       return ReplaceInstUsesWith(CI, In);
8422     }
8423       
8424       
8425       
8426     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8427     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8428     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8429     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8430     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8431     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8432     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8433     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8434     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8435         // This only works for EQ and NE
8436         ICI->isEquality()) {
8437       // If Op1C some other power of two, convert:
8438       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8439       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8440       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8441       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8442         
8443       APInt KnownZeroMask(~KnownZero);
8444       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8445         if (!DoXform) return ICI;
8446
8447         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8448         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8449           // (X&4) == 2 --> false
8450           // (X&4) != 2 --> true
8451           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8452           Res = ConstantExpr::getZExt(Res, CI.getType());
8453           return ReplaceInstUsesWith(CI, Res);
8454         }
8455           
8456         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8457         Value *In = ICI->getOperand(0);
8458         if (ShiftAmt) {
8459           // Perform a logical shr by shiftamt.
8460           // Insert the shift to put the result in the low bit.
8461           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8462                                   ConstantInt::get(In->getType(), ShiftAmt),
8463                                                    In->getName()+".lobit"), CI);
8464         }
8465           
8466         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8467           Constant *One = ConstantInt::get(In->getType(), 1);
8468           In = BinaryOperator::CreateXor(In, One, "tmp");
8469           InsertNewInstBefore(cast<Instruction>(In), CI);
8470         }
8471           
8472         if (CI.getType() == In->getType())
8473           return ReplaceInstUsesWith(CI, In);
8474         else
8475           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8476       }
8477     }
8478   }
8479
8480   return 0;
8481 }
8482
8483 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8484   // If one of the common conversion will work ..
8485   if (Instruction *Result = commonIntCastTransforms(CI))
8486     return Result;
8487
8488   Value *Src = CI.getOperand(0);
8489
8490   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8491   // types and if the sizes are just right we can convert this into a logical
8492   // 'and' which will be much cheaper than the pair of casts.
8493   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8494     // Get the sizes of the types involved.  We know that the intermediate type
8495     // will be smaller than A or C, but don't know the relation between A and C.
8496     Value *A = CSrc->getOperand(0);
8497     unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
8498     unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8499     unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8500     // If we're actually extending zero bits, then if
8501     // SrcSize <  DstSize: zext(a & mask)
8502     // SrcSize == DstSize: a & mask
8503     // SrcSize  > DstSize: trunc(a) & mask
8504     if (SrcSize < DstSize) {
8505       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8506       Constant *AndConst = ConstantInt::get(AndValue);
8507       Instruction *And =
8508         BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8509       InsertNewInstBefore(And, CI);
8510       return new ZExtInst(And, CI.getType());
8511     } else if (SrcSize == DstSize) {
8512       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8513       return BinaryOperator::CreateAnd(A, ConstantInt::get(AndValue));
8514     } else if (SrcSize > DstSize) {
8515       Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8516       InsertNewInstBefore(Trunc, CI);
8517       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8518       return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(AndValue));
8519     }
8520   }
8521
8522   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8523     return transformZExtICmp(ICI, CI);
8524
8525   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8526   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8527     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8528     // of the (zext icmp) will be transformed.
8529     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8530     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8531     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8532         (transformZExtICmp(LHS, CI, false) ||
8533          transformZExtICmp(RHS, CI, false))) {
8534       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8535       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8536       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8537     }
8538   }
8539
8540   return 0;
8541 }
8542
8543 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8544   if (Instruction *I = commonIntCastTransforms(CI))
8545     return I;
8546   
8547   Value *Src = CI.getOperand(0);
8548   
8549   // Canonicalize sign-extend from i1 to a select.
8550   if (Src->getType() == Type::Int1Ty)
8551     return SelectInst::Create(Src,
8552                               ConstantInt::getAllOnesValue(CI.getType()),
8553                               Constant::getNullValue(CI.getType()));
8554
8555   // See if the value being truncated is already sign extended.  If so, just
8556   // eliminate the trunc/sext pair.
8557   if (getOpcode(Src) == Instruction::Trunc) {
8558     Value *Op = cast<User>(Src)->getOperand(0);
8559     unsigned OpBits   = cast<IntegerType>(Op->getType())->getBitWidth();
8560     unsigned MidBits  = cast<IntegerType>(Src->getType())->getBitWidth();
8561     unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8562     unsigned NumSignBits = ComputeNumSignBits(Op);
8563
8564     if (OpBits == DestBits) {
8565       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8566       // bits, it is already ready.
8567       if (NumSignBits > DestBits-MidBits)
8568         return ReplaceInstUsesWith(CI, Op);
8569     } else if (OpBits < DestBits) {
8570       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8571       // bits, just sext from i32.
8572       if (NumSignBits > OpBits-MidBits)
8573         return new SExtInst(Op, CI.getType(), "tmp");
8574     } else {
8575       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8576       // bits, just truncate to i32.
8577       if (NumSignBits > OpBits-MidBits)
8578         return new TruncInst(Op, CI.getType(), "tmp");
8579     }
8580   }
8581
8582   // If the input is a shl/ashr pair of a same constant, then this is a sign
8583   // extension from a smaller value.  If we could trust arbitrary bitwidth
8584   // integers, we could turn this into a truncate to the smaller bit and then
8585   // use a sext for the whole extension.  Since we don't, look deeper and check
8586   // for a truncate.  If the source and dest are the same type, eliminate the
8587   // trunc and extend and just do shifts.  For example, turn:
8588   //   %a = trunc i32 %i to i8
8589   //   %b = shl i8 %a, 6
8590   //   %c = ashr i8 %b, 6
8591   //   %d = sext i8 %c to i32
8592   // into:
8593   //   %a = shl i32 %i, 30
8594   //   %d = ashr i32 %a, 30
8595   Value *A = 0;
8596   ConstantInt *BA = 0, *CA = 0;
8597   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8598                         m_ConstantInt(CA))) &&
8599       BA == CA && isa<TruncInst>(A)) {
8600     Value *I = cast<TruncInst>(A)->getOperand(0);
8601     if (I->getType() == CI.getType()) {
8602       unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8603       unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8604       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8605       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8606       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8607                                                         CI.getName()), CI);
8608       return BinaryOperator::CreateAShr(I, ShAmtV);
8609     }
8610   }
8611   
8612   return 0;
8613 }
8614
8615 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8616 /// in the specified FP type without changing its value.
8617 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
8618   bool losesInfo;
8619   APFloat F = CFP->getValueAPF();
8620   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8621   if (!losesInfo)
8622     return ConstantFP::get(F);
8623   return 0;
8624 }
8625
8626 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8627 /// through it until we get the source value.
8628 static Value *LookThroughFPExtensions(Value *V) {
8629   if (Instruction *I = dyn_cast<Instruction>(V))
8630     if (I->getOpcode() == Instruction::FPExt)
8631       return LookThroughFPExtensions(I->getOperand(0));
8632   
8633   // If this value is a constant, return the constant in the smallest FP type
8634   // that can accurately represent it.  This allows us to turn
8635   // (float)((double)X+2.0) into x+2.0f.
8636   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8637     if (CFP->getType() == Type::PPC_FP128Ty)
8638       return V;  // No constant folding of this.
8639     // See if the value can be truncated to float and then reextended.
8640     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
8641       return V;
8642     if (CFP->getType() == Type::DoubleTy)
8643       return V;  // Won't shrink.
8644     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
8645       return V;
8646     // Don't try to shrink to various long double types.
8647   }
8648   
8649   return V;
8650 }
8651
8652 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8653   if (Instruction *I = commonCastTransforms(CI))
8654     return I;
8655   
8656   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8657   // smaller than the destination type, we can eliminate the truncate by doing
8658   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8659   // many builtins (sqrt, etc).
8660   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8661   if (OpI && OpI->hasOneUse()) {
8662     switch (OpI->getOpcode()) {
8663     default: break;
8664     case Instruction::FAdd:
8665     case Instruction::FSub:
8666     case Instruction::FMul:
8667     case Instruction::FDiv:
8668     case Instruction::FRem:
8669       const Type *SrcTy = OpI->getType();
8670       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8671       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8672       if (LHSTrunc->getType() != SrcTy && 
8673           RHSTrunc->getType() != SrcTy) {
8674         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8675         // If the source types were both smaller than the destination type of
8676         // the cast, do this xform.
8677         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8678             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8679           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8680                                       CI.getType(), CI);
8681           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8682                                       CI.getType(), CI);
8683           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8684         }
8685       }
8686       break;  
8687     }
8688   }
8689   return 0;
8690 }
8691
8692 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8693   return commonCastTransforms(CI);
8694 }
8695
8696 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8697   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8698   if (OpI == 0)
8699     return commonCastTransforms(FI);
8700
8701   // fptoui(uitofp(X)) --> X
8702   // fptoui(sitofp(X)) --> X
8703   // This is safe if the intermediate type has enough bits in its mantissa to
8704   // accurately represent all values of X.  For example, do not do this with
8705   // i64->float->i64.  This is also safe for sitofp case, because any negative
8706   // 'X' value would cause an undefined result for the fptoui. 
8707   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8708       OpI->getOperand(0)->getType() == FI.getType() &&
8709       (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8710                     OpI->getType()->getFPMantissaWidth())
8711     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8712
8713   return commonCastTransforms(FI);
8714 }
8715
8716 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8717   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8718   if (OpI == 0)
8719     return commonCastTransforms(FI);
8720   
8721   // fptosi(sitofp(X)) --> X
8722   // fptosi(uitofp(X)) --> X
8723   // This is safe if the intermediate type has enough bits in its mantissa to
8724   // accurately represent all values of X.  For example, do not do this with
8725   // i64->float->i64.  This is also safe for sitofp case, because any negative
8726   // 'X' value would cause an undefined result for the fptoui. 
8727   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8728       OpI->getOperand(0)->getType() == FI.getType() &&
8729       (int)FI.getType()->getPrimitiveSizeInBits() <= 
8730                     OpI->getType()->getFPMantissaWidth())
8731     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8732   
8733   return commonCastTransforms(FI);
8734 }
8735
8736 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8737   return commonCastTransforms(CI);
8738 }
8739
8740 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8741   return commonCastTransforms(CI);
8742 }
8743
8744 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8745   // If the destination integer type is smaller than the intptr_t type for
8746   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8747   // trunc to be exposed to other transforms.  Don't do this for extending
8748   // ptrtoint's, because we don't know if the target sign or zero extends its
8749   // pointers.
8750   if (CI.getType()->getPrimitiveSizeInBits() < TD->getPointerSizeInBits()) {
8751     Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8752                                                     TD->getIntPtrType(),
8753                                                     "tmp"), CI);
8754     return new TruncInst(P, CI.getType());
8755   }
8756   
8757   return commonPointerCastTransforms(CI);
8758 }
8759
8760 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8761   // If the source integer type is larger than the intptr_t type for
8762   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8763   // allows the trunc to be exposed to other transforms.  Don't do this for
8764   // extending inttoptr's, because we don't know if the target sign or zero
8765   // extends to pointers.
8766   if (CI.getOperand(0)->getType()->getPrimitiveSizeInBits() >
8767       TD->getPointerSizeInBits()) {
8768     Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8769                                                  TD->getIntPtrType(),
8770                                                  "tmp"), CI);
8771     return new IntToPtrInst(P, CI.getType());
8772   }
8773   
8774   if (Instruction *I = commonCastTransforms(CI))
8775     return I;
8776   
8777   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8778   if (!DestPointee->isSized()) return 0;
8779
8780   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8781   ConstantInt *Cst;
8782   Value *X;
8783   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8784                                     m_ConstantInt(Cst)))) {
8785     // If the source and destination operands have the same type, see if this
8786     // is a single-index GEP.
8787     if (X->getType() == CI.getType()) {
8788       // Get the size of the pointee type.
8789       uint64_t Size = TD->getTypeAllocSize(DestPointee);
8790
8791       // Convert the constant to intptr type.
8792       APInt Offset = Cst->getValue();
8793       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8794
8795       // If Offset is evenly divisible by Size, we can do this xform.
8796       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8797         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8798         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
8799       }
8800     }
8801     // TODO: Could handle other cases, e.g. where add is indexing into field of
8802     // struct etc.
8803   } else if (CI.getOperand(0)->hasOneUse() &&
8804              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8805     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8806     // "inttoptr+GEP" instead of "add+intptr".
8807     
8808     // Get the size of the pointee type.
8809     uint64_t Size = TD->getTypeAllocSize(DestPointee);
8810     
8811     // Convert the constant to intptr type.
8812     APInt Offset = Cst->getValue();
8813     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8814     
8815     // If Offset is evenly divisible by Size, we can do this xform.
8816     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8817       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8818       
8819       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8820                                                             "tmp"), CI);
8821       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
8822     }
8823   }
8824   return 0;
8825 }
8826
8827 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8828   // If the operands are integer typed then apply the integer transforms,
8829   // otherwise just apply the common ones.
8830   Value *Src = CI.getOperand(0);
8831   const Type *SrcTy = Src->getType();
8832   const Type *DestTy = CI.getType();
8833
8834   if (SrcTy->isInteger() && DestTy->isInteger()) {
8835     if (Instruction *Result = commonIntCastTransforms(CI))
8836       return Result;
8837   } else if (isa<PointerType>(SrcTy)) {
8838     if (Instruction *I = commonPointerCastTransforms(CI))
8839       return I;
8840   } else {
8841     if (Instruction *Result = commonCastTransforms(CI))
8842       return Result;
8843   }
8844
8845
8846   // Get rid of casts from one type to the same type. These are useless and can
8847   // be replaced by the operand.
8848   if (DestTy == Src->getType())
8849     return ReplaceInstUsesWith(CI, Src);
8850
8851   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8852     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8853     const Type *DstElTy = DstPTy->getElementType();
8854     const Type *SrcElTy = SrcPTy->getElementType();
8855     
8856     // If the address spaces don't match, don't eliminate the bitcast, which is
8857     // required for changing types.
8858     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8859       return 0;
8860     
8861     // If we are casting a malloc or alloca to a pointer to a type of the same
8862     // size, rewrite the allocation instruction to allocate the "right" type.
8863     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8864       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8865         return V;
8866     
8867     // If the source and destination are pointers, and this cast is equivalent
8868     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8869     // This can enhance SROA and other transforms that want type-safe pointers.
8870     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8871     unsigned NumZeros = 0;
8872     while (SrcElTy != DstElTy && 
8873            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8874            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8875       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8876       ++NumZeros;
8877     }
8878
8879     // If we found a path from the src to dest, create the getelementptr now.
8880     if (SrcElTy == DstElTy) {
8881       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8882       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
8883                                        ((Instruction*) NULL));
8884     }
8885   }
8886
8887   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8888     if (SVI->hasOneUse()) {
8889       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8890       // a bitconvert to a vector with the same # elts.
8891       if (isa<VectorType>(DestTy) && 
8892           cast<VectorType>(DestTy)->getNumElements() ==
8893                 SVI->getType()->getNumElements() &&
8894           SVI->getType()->getNumElements() ==
8895             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8896         CastInst *Tmp;
8897         // If either of the operands is a cast from CI.getType(), then
8898         // evaluating the shuffle in the casted destination's type will allow
8899         // us to eliminate at least one cast.
8900         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8901              Tmp->getOperand(0)->getType() == DestTy) ||
8902             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8903              Tmp->getOperand(0)->getType() == DestTy)) {
8904           Value *LHS = InsertCastBefore(Instruction::BitCast,
8905                                         SVI->getOperand(0), DestTy, CI);
8906           Value *RHS = InsertCastBefore(Instruction::BitCast,
8907                                         SVI->getOperand(1), DestTy, CI);
8908           // Return a new shuffle vector.  Use the same element ID's, as we
8909           // know the vector types match #elts.
8910           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8911         }
8912       }
8913     }
8914   }
8915   return 0;
8916 }
8917
8918 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8919 ///   %C = or %A, %B
8920 ///   %D = select %cond, %C, %A
8921 /// into:
8922 ///   %C = select %cond, %B, 0
8923 ///   %D = or %A, %C
8924 ///
8925 /// Assuming that the specified instruction is an operand to the select, return
8926 /// a bitmask indicating which operands of this instruction are foldable if they
8927 /// equal the other incoming value of the select.
8928 ///
8929 static unsigned GetSelectFoldableOperands(Instruction *I) {
8930   switch (I->getOpcode()) {
8931   case Instruction::Add:
8932   case Instruction::Mul:
8933   case Instruction::And:
8934   case Instruction::Or:
8935   case Instruction::Xor:
8936     return 3;              // Can fold through either operand.
8937   case Instruction::Sub:   // Can only fold on the amount subtracted.
8938   case Instruction::Shl:   // Can only fold on the shift amount.
8939   case Instruction::LShr:
8940   case Instruction::AShr:
8941     return 1;
8942   default:
8943     return 0;              // Cannot fold
8944   }
8945 }
8946
8947 /// GetSelectFoldableConstant - For the same transformation as the previous
8948 /// function, return the identity constant that goes into the select.
8949 static Constant *GetSelectFoldableConstant(Instruction *I) {
8950   switch (I->getOpcode()) {
8951   default: assert(0 && "This cannot happen!"); abort();
8952   case Instruction::Add:
8953   case Instruction::Sub:
8954   case Instruction::Or:
8955   case Instruction::Xor:
8956   case Instruction::Shl:
8957   case Instruction::LShr:
8958   case Instruction::AShr:
8959     return Constant::getNullValue(I->getType());
8960   case Instruction::And:
8961     return Constant::getAllOnesValue(I->getType());
8962   case Instruction::Mul:
8963     return ConstantInt::get(I->getType(), 1);
8964   }
8965 }
8966
8967 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8968 /// have the same opcode and only one use each.  Try to simplify this.
8969 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8970                                           Instruction *FI) {
8971   if (TI->getNumOperands() == 1) {
8972     // If this is a non-volatile load or a cast from the same type,
8973     // merge.
8974     if (TI->isCast()) {
8975       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8976         return 0;
8977     } else {
8978       return 0;  // unknown unary op.
8979     }
8980
8981     // Fold this by inserting a select from the input values.
8982     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8983                                            FI->getOperand(0), SI.getName()+".v");
8984     InsertNewInstBefore(NewSI, SI);
8985     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
8986                             TI->getType());
8987   }
8988
8989   // Only handle binary operators here.
8990   if (!isa<BinaryOperator>(TI))
8991     return 0;
8992
8993   // Figure out if the operations have any operands in common.
8994   Value *MatchOp, *OtherOpT, *OtherOpF;
8995   bool MatchIsOpZero;
8996   if (TI->getOperand(0) == FI->getOperand(0)) {
8997     MatchOp  = TI->getOperand(0);
8998     OtherOpT = TI->getOperand(1);
8999     OtherOpF = FI->getOperand(1);
9000     MatchIsOpZero = true;
9001   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9002     MatchOp  = TI->getOperand(1);
9003     OtherOpT = TI->getOperand(0);
9004     OtherOpF = FI->getOperand(0);
9005     MatchIsOpZero = false;
9006   } else if (!TI->isCommutative()) {
9007     return 0;
9008   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9009     MatchOp  = TI->getOperand(0);
9010     OtherOpT = TI->getOperand(1);
9011     OtherOpF = FI->getOperand(0);
9012     MatchIsOpZero = true;
9013   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9014     MatchOp  = TI->getOperand(1);
9015     OtherOpT = TI->getOperand(0);
9016     OtherOpF = FI->getOperand(1);
9017     MatchIsOpZero = true;
9018   } else {
9019     return 0;
9020   }
9021
9022   // If we reach here, they do have operations in common.
9023   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9024                                          OtherOpF, SI.getName()+".v");
9025   InsertNewInstBefore(NewSI, SI);
9026
9027   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9028     if (MatchIsOpZero)
9029       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9030     else
9031       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9032   }
9033   assert(0 && "Shouldn't get here");
9034   return 0;
9035 }
9036
9037 static bool isSelect01(Constant *C1, Constant *C2) {
9038   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9039   if (!C1I)
9040     return false;
9041   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9042   if (!C2I)
9043     return false;
9044   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9045 }
9046
9047 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9048 /// facilitate further optimization.
9049 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9050                                             Value *FalseVal) {
9051   // See the comment above GetSelectFoldableOperands for a description of the
9052   // transformation we are doing here.
9053   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9054     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9055         !isa<Constant>(FalseVal)) {
9056       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9057         unsigned OpToFold = 0;
9058         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9059           OpToFold = 1;
9060         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9061           OpToFold = 2;
9062         }
9063
9064         if (OpToFold) {
9065           Constant *C = GetSelectFoldableConstant(TVI);
9066           Value *OOp = TVI->getOperand(2-OpToFold);
9067           // Avoid creating select between 2 constants unless it's selecting
9068           // between 0 and 1.
9069           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9070             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9071             InsertNewInstBefore(NewSel, SI);
9072             NewSel->takeName(TVI);
9073             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9074               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9075             assert(0 && "Unknown instruction!!");
9076           }
9077         }
9078       }
9079     }
9080   }
9081
9082   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9083     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9084         !isa<Constant>(TrueVal)) {
9085       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9086         unsigned OpToFold = 0;
9087         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9088           OpToFold = 1;
9089         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9090           OpToFold = 2;
9091         }
9092
9093         if (OpToFold) {
9094           Constant *C = GetSelectFoldableConstant(FVI);
9095           Value *OOp = FVI->getOperand(2-OpToFold);
9096           // Avoid creating select between 2 constants unless it's selecting
9097           // between 0 and 1.
9098           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9099             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9100             InsertNewInstBefore(NewSel, SI);
9101             NewSel->takeName(FVI);
9102             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9103               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9104             assert(0 && "Unknown instruction!!");
9105           }
9106         }
9107       }
9108     }
9109   }
9110
9111   return 0;
9112 }
9113
9114 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9115 /// ICmpInst as its first operand.
9116 ///
9117 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9118                                                    ICmpInst *ICI) {
9119   bool Changed = false;
9120   ICmpInst::Predicate Pred = ICI->getPredicate();
9121   Value *CmpLHS = ICI->getOperand(0);
9122   Value *CmpRHS = ICI->getOperand(1);
9123   Value *TrueVal = SI.getTrueValue();
9124   Value *FalseVal = SI.getFalseValue();
9125
9126   // Check cases where the comparison is with a constant that
9127   // can be adjusted to fit the min/max idiom. We may edit ICI in
9128   // place here, so make sure the select is the only user.
9129   if (ICI->hasOneUse())
9130     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9131       switch (Pred) {
9132       default: break;
9133       case ICmpInst::ICMP_ULT:
9134       case ICmpInst::ICMP_SLT: {
9135         // X < MIN ? T : F  -->  F
9136         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9137           return ReplaceInstUsesWith(SI, FalseVal);
9138         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9139         Constant *AdjustedRHS = SubOne(CI);
9140         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9141             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9142           Pred = ICmpInst::getSwappedPredicate(Pred);
9143           CmpRHS = AdjustedRHS;
9144           std::swap(FalseVal, TrueVal);
9145           ICI->setPredicate(Pred);
9146           ICI->setOperand(1, CmpRHS);
9147           SI.setOperand(1, TrueVal);
9148           SI.setOperand(2, FalseVal);
9149           Changed = true;
9150         }
9151         break;
9152       }
9153       case ICmpInst::ICMP_UGT:
9154       case ICmpInst::ICMP_SGT: {
9155         // X > MAX ? T : F  -->  F
9156         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9157           return ReplaceInstUsesWith(SI, FalseVal);
9158         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9159         Constant *AdjustedRHS = AddOne(CI);
9160         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9161             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9162           Pred = ICmpInst::getSwappedPredicate(Pred);
9163           CmpRHS = AdjustedRHS;
9164           std::swap(FalseVal, TrueVal);
9165           ICI->setPredicate(Pred);
9166           ICI->setOperand(1, CmpRHS);
9167           SI.setOperand(1, TrueVal);
9168           SI.setOperand(2, FalseVal);
9169           Changed = true;
9170         }
9171         break;
9172       }
9173       }
9174
9175       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9176       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9177       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9178       if (match(TrueVal, m_ConstantInt<-1>()) &&
9179           match(FalseVal, m_ConstantInt<0>()))
9180         Pred = ICI->getPredicate();
9181       else if (match(TrueVal, m_ConstantInt<0>()) &&
9182                match(FalseVal, m_ConstantInt<-1>()))
9183         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9184       
9185       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9186         // If we are just checking for a icmp eq of a single bit and zext'ing it
9187         // to an integer, then shift the bit to the appropriate place and then
9188         // cast to integer to avoid the comparison.
9189         const APInt &Op1CV = CI->getValue();
9190     
9191         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9192         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9193         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9194             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9195           Value *In = ICI->getOperand(0);
9196           Value *Sh = ConstantInt::get(In->getType(),
9197                                        In->getType()->getPrimitiveSizeInBits()-1);
9198           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9199                                                           In->getName()+".lobit"),
9200                                    *ICI);
9201           if (In->getType() != SI.getType())
9202             In = CastInst::CreateIntegerCast(In, SI.getType(),
9203                                              true/*SExt*/, "tmp", ICI);
9204     
9205           if (Pred == ICmpInst::ICMP_SGT)
9206             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9207                                        In->getName()+".not"), *ICI);
9208     
9209           return ReplaceInstUsesWith(SI, In);
9210         }
9211       }
9212     }
9213
9214   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9215     // Transform (X == Y) ? X : Y  -> Y
9216     if (Pred == ICmpInst::ICMP_EQ)
9217       return ReplaceInstUsesWith(SI, FalseVal);
9218     // Transform (X != Y) ? X : Y  -> X
9219     if (Pred == ICmpInst::ICMP_NE)
9220       return ReplaceInstUsesWith(SI, TrueVal);
9221     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9222
9223   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9224     // Transform (X == Y) ? Y : X  -> X
9225     if (Pred == ICmpInst::ICMP_EQ)
9226       return ReplaceInstUsesWith(SI, FalseVal);
9227     // Transform (X != Y) ? Y : X  -> Y
9228     if (Pred == ICmpInst::ICMP_NE)
9229       return ReplaceInstUsesWith(SI, TrueVal);
9230     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9231   }
9232
9233   /// NOTE: if we wanted to, this is where to detect integer ABS
9234
9235   return Changed ? &SI : 0;
9236 }
9237
9238 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9239   Value *CondVal = SI.getCondition();
9240   Value *TrueVal = SI.getTrueValue();
9241   Value *FalseVal = SI.getFalseValue();
9242
9243   // select true, X, Y  -> X
9244   // select false, X, Y -> Y
9245   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9246     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9247
9248   // select C, X, X -> X
9249   if (TrueVal == FalseVal)
9250     return ReplaceInstUsesWith(SI, TrueVal);
9251
9252   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9253     return ReplaceInstUsesWith(SI, FalseVal);
9254   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9255     return ReplaceInstUsesWith(SI, TrueVal);
9256   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9257     if (isa<Constant>(TrueVal))
9258       return ReplaceInstUsesWith(SI, TrueVal);
9259     else
9260       return ReplaceInstUsesWith(SI, FalseVal);
9261   }
9262
9263   if (SI.getType() == Type::Int1Ty) {
9264     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9265       if (C->getZExtValue()) {
9266         // Change: A = select B, true, C --> A = or B, C
9267         return BinaryOperator::CreateOr(CondVal, FalseVal);
9268       } else {
9269         // Change: A = select B, false, C --> A = and !B, C
9270         Value *NotCond =
9271           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9272                                              "not."+CondVal->getName()), SI);
9273         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9274       }
9275     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9276       if (C->getZExtValue() == false) {
9277         // Change: A = select B, C, false --> A = and B, C
9278         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9279       } else {
9280         // Change: A = select B, C, true --> A = or !B, C
9281         Value *NotCond =
9282           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9283                                              "not."+CondVal->getName()), SI);
9284         return BinaryOperator::CreateOr(NotCond, TrueVal);
9285       }
9286     }
9287     
9288     // select a, b, a  -> a&b
9289     // select a, a, b  -> a|b
9290     if (CondVal == TrueVal)
9291       return BinaryOperator::CreateOr(CondVal, FalseVal);
9292     else if (CondVal == FalseVal)
9293       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9294   }
9295
9296   // Selecting between two integer constants?
9297   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9298     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9299       // select C, 1, 0 -> zext C to int
9300       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9301         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9302       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9303         // select C, 0, 1 -> zext !C to int
9304         Value *NotCond =
9305           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9306                                                "not."+CondVal->getName()), SI);
9307         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9308       }
9309
9310       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9311
9312         // (x <s 0) ? -1 : 0 -> ashr x, 31
9313         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
9314           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
9315             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
9316               // The comparison constant and the result are not neccessarily the
9317               // same width. Make an all-ones value by inserting a AShr.
9318               Value *X = IC->getOperand(0);
9319               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
9320               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
9321               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
9322                                                         ShAmt, "ones");
9323               InsertNewInstBefore(SRA, SI);
9324
9325               // Then cast to the appropriate width.
9326               return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
9327             }
9328           }
9329
9330
9331         // If one of the constants is zero (we know they can't both be) and we
9332         // have an icmp instruction with zero, and we have an 'and' with the
9333         // non-constant value, eliminate this whole mess.  This corresponds to
9334         // cases like this: ((X & 27) ? 27 : 0)
9335         if (TrueValC->isZero() || FalseValC->isZero())
9336           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9337               cast<Constant>(IC->getOperand(1))->isNullValue())
9338             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9339               if (ICA->getOpcode() == Instruction::And &&
9340                   isa<ConstantInt>(ICA->getOperand(1)) &&
9341                   (ICA->getOperand(1) == TrueValC ||
9342                    ICA->getOperand(1) == FalseValC) &&
9343                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9344                 // Okay, now we know that everything is set up, we just don't
9345                 // know whether we have a icmp_ne or icmp_eq and whether the 
9346                 // true or false val is the zero.
9347                 bool ShouldNotVal = !TrueValC->isZero();
9348                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9349                 Value *V = ICA;
9350                 if (ShouldNotVal)
9351                   V = InsertNewInstBefore(BinaryOperator::Create(
9352                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9353                 return ReplaceInstUsesWith(SI, V);
9354               }
9355       }
9356     }
9357
9358   // See if we are selecting two values based on a comparison of the two values.
9359   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9360     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9361       // Transform (X == Y) ? X : Y  -> Y
9362       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9363         // This is not safe in general for floating point:  
9364         // consider X== -0, Y== +0.
9365         // It becomes safe if either operand is a nonzero constant.
9366         ConstantFP *CFPt, *CFPf;
9367         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9368               !CFPt->getValueAPF().isZero()) ||
9369             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9370              !CFPf->getValueAPF().isZero()))
9371         return ReplaceInstUsesWith(SI, FalseVal);
9372       }
9373       // Transform (X != Y) ? X : Y  -> X
9374       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9375         return ReplaceInstUsesWith(SI, TrueVal);
9376       // NOTE: if we wanted to, this is where to detect MIN/MAX
9377
9378     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9379       // Transform (X == Y) ? Y : X  -> X
9380       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9381         // This is not safe in general for floating point:  
9382         // consider X== -0, Y== +0.
9383         // It becomes safe if either operand is a nonzero constant.
9384         ConstantFP *CFPt, *CFPf;
9385         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9386               !CFPt->getValueAPF().isZero()) ||
9387             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9388              !CFPf->getValueAPF().isZero()))
9389           return ReplaceInstUsesWith(SI, FalseVal);
9390       }
9391       // Transform (X != Y) ? Y : X  -> Y
9392       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9393         return ReplaceInstUsesWith(SI, TrueVal);
9394       // NOTE: if we wanted to, this is where to detect MIN/MAX
9395     }
9396     // NOTE: if we wanted to, this is where to detect ABS
9397   }
9398
9399   // See if we are selecting two values based on a comparison of the two values.
9400   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9401     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9402       return Result;
9403
9404   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9405     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9406       if (TI->hasOneUse() && FI->hasOneUse()) {
9407         Instruction *AddOp = 0, *SubOp = 0;
9408
9409         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9410         if (TI->getOpcode() == FI->getOpcode())
9411           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9412             return IV;
9413
9414         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9415         // even legal for FP.
9416         if ((TI->getOpcode() == Instruction::Sub &&
9417              FI->getOpcode() == Instruction::Add) ||
9418             (TI->getOpcode() == Instruction::FSub &&
9419              FI->getOpcode() == Instruction::FAdd)) {
9420           AddOp = FI; SubOp = TI;
9421         } else if ((FI->getOpcode() == Instruction::Sub &&
9422                     TI->getOpcode() == Instruction::Add) ||
9423                    (FI->getOpcode() == Instruction::FSub &&
9424                     TI->getOpcode() == Instruction::FAdd)) {
9425           AddOp = TI; SubOp = FI;
9426         }
9427
9428         if (AddOp) {
9429           Value *OtherAddOp = 0;
9430           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9431             OtherAddOp = AddOp->getOperand(1);
9432           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9433             OtherAddOp = AddOp->getOperand(0);
9434           }
9435
9436           if (OtherAddOp) {
9437             // So at this point we know we have (Y -> OtherAddOp):
9438             //        select C, (add X, Y), (sub X, Z)
9439             Value *NegVal;  // Compute -Z
9440             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9441               NegVal = ConstantExpr::getNeg(C);
9442             } else {
9443               NegVal = InsertNewInstBefore(
9444                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
9445             }
9446
9447             Value *NewTrueOp = OtherAddOp;
9448             Value *NewFalseOp = NegVal;
9449             if (AddOp != TI)
9450               std::swap(NewTrueOp, NewFalseOp);
9451             Instruction *NewSel =
9452               SelectInst::Create(CondVal, NewTrueOp,
9453                                  NewFalseOp, SI.getName() + ".p");
9454
9455             NewSel = InsertNewInstBefore(NewSel, SI);
9456             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9457           }
9458         }
9459       }
9460
9461   // See if we can fold the select into one of our operands.
9462   if (SI.getType()->isInteger()) {
9463     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9464     if (FoldI)
9465       return FoldI;
9466   }
9467
9468   if (BinaryOperator::isNot(CondVal)) {
9469     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9470     SI.setOperand(1, FalseVal);
9471     SI.setOperand(2, TrueVal);
9472     return &SI;
9473   }
9474
9475   return 0;
9476 }
9477
9478 /// EnforceKnownAlignment - If the specified pointer points to an object that
9479 /// we control, modify the object's alignment to PrefAlign. This isn't
9480 /// often possible though. If alignment is important, a more reliable approach
9481 /// is to simply align all global variables and allocation instructions to
9482 /// their preferred alignment from the beginning.
9483 ///
9484 static unsigned EnforceKnownAlignment(Value *V,
9485                                       unsigned Align, unsigned PrefAlign) {
9486
9487   User *U = dyn_cast<User>(V);
9488   if (!U) return Align;
9489
9490   switch (getOpcode(U)) {
9491   default: break;
9492   case Instruction::BitCast:
9493     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9494   case Instruction::GetElementPtr: {
9495     // If all indexes are zero, it is just the alignment of the base pointer.
9496     bool AllZeroOperands = true;
9497     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9498       if (!isa<Constant>(*i) ||
9499           !cast<Constant>(*i)->isNullValue()) {
9500         AllZeroOperands = false;
9501         break;
9502       }
9503
9504     if (AllZeroOperands) {
9505       // Treat this like a bitcast.
9506       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9507     }
9508     break;
9509   }
9510   }
9511
9512   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9513     // If there is a large requested alignment and we can, bump up the alignment
9514     // of the global.
9515     if (!GV->isDeclaration()) {
9516       if (GV->getAlignment() >= PrefAlign)
9517         Align = GV->getAlignment();
9518       else {
9519         GV->setAlignment(PrefAlign);
9520         Align = PrefAlign;
9521       }
9522     }
9523   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9524     // If there is a requested alignment and if this is an alloca, round up.  We
9525     // don't do this for malloc, because some systems can't respect the request.
9526     if (isa<AllocaInst>(AI)) {
9527       if (AI->getAlignment() >= PrefAlign)
9528         Align = AI->getAlignment();
9529       else {
9530         AI->setAlignment(PrefAlign);
9531         Align = PrefAlign;
9532       }
9533     }
9534   }
9535
9536   return Align;
9537 }
9538
9539 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9540 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9541 /// and it is more than the alignment of the ultimate object, see if we can
9542 /// increase the alignment of the ultimate object, making this check succeed.
9543 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9544                                                   unsigned PrefAlign) {
9545   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9546                       sizeof(PrefAlign) * CHAR_BIT;
9547   APInt Mask = APInt::getAllOnesValue(BitWidth);
9548   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9549   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9550   unsigned TrailZ = KnownZero.countTrailingOnes();
9551   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9552
9553   if (PrefAlign > Align)
9554     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9555   
9556     // We don't need to make any adjustment.
9557   return Align;
9558 }
9559
9560 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9561   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9562   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9563   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9564   unsigned CopyAlign = MI->getAlignment();
9565
9566   if (CopyAlign < MinAlign) {
9567     MI->setAlignment(MinAlign);
9568     return MI;
9569   }
9570   
9571   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9572   // load/store.
9573   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9574   if (MemOpLength == 0) return 0;
9575   
9576   // Source and destination pointer types are always "i8*" for intrinsic.  See
9577   // if the size is something we can handle with a single primitive load/store.
9578   // A single load+store correctly handles overlapping memory in the memmove
9579   // case.
9580   unsigned Size = MemOpLength->getZExtValue();
9581   if (Size == 0) return MI;  // Delete this mem transfer.
9582   
9583   if (Size > 8 || (Size&(Size-1)))
9584     return 0;  // If not 1/2/4/8 bytes, exit.
9585   
9586   // Use an integer load+store unless we can find something better.
9587   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
9588   
9589   // Memcpy forces the use of i8* for the source and destination.  That means
9590   // that if you're using memcpy to move one double around, you'll get a cast
9591   // from double* to i8*.  We'd much rather use a double load+store rather than
9592   // an i64 load+store, here because this improves the odds that the source or
9593   // dest address will be promotable.  See if we can find a better type than the
9594   // integer datatype.
9595   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9596     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9597     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9598       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9599       // down through these levels if so.
9600       while (!SrcETy->isSingleValueType()) {
9601         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9602           if (STy->getNumElements() == 1)
9603             SrcETy = STy->getElementType(0);
9604           else
9605             break;
9606         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9607           if (ATy->getNumElements() == 1)
9608             SrcETy = ATy->getElementType();
9609           else
9610             break;
9611         } else
9612           break;
9613       }
9614       
9615       if (SrcETy->isSingleValueType())
9616         NewPtrTy = PointerType::getUnqual(SrcETy);
9617     }
9618   }
9619   
9620   
9621   // If the memcpy/memmove provides better alignment info than we can
9622   // infer, use it.
9623   SrcAlign = std::max(SrcAlign, CopyAlign);
9624   DstAlign = std::max(DstAlign, CopyAlign);
9625   
9626   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9627   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9628   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9629   InsertNewInstBefore(L, *MI);
9630   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9631
9632   // Set the size of the copy to 0, it will be deleted on the next iteration.
9633   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9634   return MI;
9635 }
9636
9637 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9638   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9639   if (MI->getAlignment() < Alignment) {
9640     MI->setAlignment(Alignment);
9641     return MI;
9642   }
9643   
9644   // Extract the length and alignment and fill if they are constant.
9645   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9646   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9647   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9648     return 0;
9649   uint64_t Len = LenC->getZExtValue();
9650   Alignment = MI->getAlignment();
9651   
9652   // If the length is zero, this is a no-op
9653   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9654   
9655   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9656   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9657     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
9658     
9659     Value *Dest = MI->getDest();
9660     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9661
9662     // Alignment 0 is identity for alignment 1 for memset, but not store.
9663     if (Alignment == 0) Alignment = 1;
9664     
9665     // Extract the fill value and store.
9666     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9667     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9668                                       Alignment), *MI);
9669     
9670     // Set the size of the copy to 0, it will be deleted on the next iteration.
9671     MI->setLength(Constant::getNullValue(LenC->getType()));
9672     return MI;
9673   }
9674
9675   return 0;
9676 }
9677
9678
9679 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9680 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9681 /// the heavy lifting.
9682 ///
9683 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9684   // If the caller function is nounwind, mark the call as nounwind, even if the
9685   // callee isn't.
9686   if (CI.getParent()->getParent()->doesNotThrow() &&
9687       !CI.doesNotThrow()) {
9688     CI.setDoesNotThrow();
9689     return &CI;
9690   }
9691   
9692   
9693   
9694   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9695   if (!II) return visitCallSite(&CI);
9696   
9697   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9698   // visitCallSite.
9699   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9700     bool Changed = false;
9701
9702     // memmove/cpy/set of zero bytes is a noop.
9703     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9704       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9705
9706       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9707         if (CI->getZExtValue() == 1) {
9708           // Replace the instruction with just byte operations.  We would
9709           // transform other cases to loads/stores, but we don't know if
9710           // alignment is sufficient.
9711         }
9712     }
9713
9714     // If we have a memmove and the source operation is a constant global,
9715     // then the source and dest pointers can't alias, so we can change this
9716     // into a call to memcpy.
9717     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9718       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9719         if (GVSrc->isConstant()) {
9720           Module *M = CI.getParent()->getParent()->getParent();
9721           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9722           const Type *Tys[1];
9723           Tys[0] = CI.getOperand(3)->getType();
9724           CI.setOperand(0, 
9725                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9726           Changed = true;
9727         }
9728
9729       // memmove(x,x,size) -> noop.
9730       if (MMI->getSource() == MMI->getDest())
9731         return EraseInstFromFunction(CI);
9732     }
9733
9734     // If we can determine a pointer alignment that is bigger than currently
9735     // set, update the alignment.
9736     if (isa<MemTransferInst>(MI)) {
9737       if (Instruction *I = SimplifyMemTransfer(MI))
9738         return I;
9739     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9740       if (Instruction *I = SimplifyMemSet(MSI))
9741         return I;
9742     }
9743           
9744     if (Changed) return II;
9745   }
9746   
9747   switch (II->getIntrinsicID()) {
9748   default: break;
9749   case Intrinsic::bswap:
9750     // bswap(bswap(x)) -> x
9751     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9752       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9753         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9754     break;
9755   case Intrinsic::ppc_altivec_lvx:
9756   case Intrinsic::ppc_altivec_lvxl:
9757   case Intrinsic::x86_sse_loadu_ps:
9758   case Intrinsic::x86_sse2_loadu_pd:
9759   case Intrinsic::x86_sse2_loadu_dq:
9760     // Turn PPC lvx     -> load if the pointer is known aligned.
9761     // Turn X86 loadups -> load if the pointer is known aligned.
9762     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9763       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9764                                        PointerType::getUnqual(II->getType()),
9765                                        CI);
9766       return new LoadInst(Ptr);
9767     }
9768     break;
9769   case Intrinsic::ppc_altivec_stvx:
9770   case Intrinsic::ppc_altivec_stvxl:
9771     // Turn stvx -> store if the pointer is known aligned.
9772     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9773       const Type *OpPtrTy = 
9774         PointerType::getUnqual(II->getOperand(1)->getType());
9775       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9776       return new StoreInst(II->getOperand(1), Ptr);
9777     }
9778     break;
9779   case Intrinsic::x86_sse_storeu_ps:
9780   case Intrinsic::x86_sse2_storeu_pd:
9781   case Intrinsic::x86_sse2_storeu_dq:
9782     // Turn X86 storeu -> store if the pointer is known aligned.
9783     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9784       const Type *OpPtrTy = 
9785         PointerType::getUnqual(II->getOperand(2)->getType());
9786       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9787       return new StoreInst(II->getOperand(2), Ptr);
9788     }
9789     break;
9790     
9791   case Intrinsic::x86_sse_cvttss2si: {
9792     // These intrinsics only demands the 0th element of its input vector.  If
9793     // we can simplify the input based on that, do so now.
9794     unsigned VWidth =
9795       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9796     APInt DemandedElts(VWidth, 1);
9797     APInt UndefElts(VWidth, 0);
9798     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9799                                               UndefElts)) {
9800       II->setOperand(1, V);
9801       return II;
9802     }
9803     break;
9804   }
9805     
9806   case Intrinsic::ppc_altivec_vperm:
9807     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9808     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9809       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9810       
9811       // Check that all of the elements are integer constants or undefs.
9812       bool AllEltsOk = true;
9813       for (unsigned i = 0; i != 16; ++i) {
9814         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9815             !isa<UndefValue>(Mask->getOperand(i))) {
9816           AllEltsOk = false;
9817           break;
9818         }
9819       }
9820       
9821       if (AllEltsOk) {
9822         // Cast the input vectors to byte vectors.
9823         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9824         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9825         Value *Result = UndefValue::get(Op0->getType());
9826         
9827         // Only extract each element once.
9828         Value *ExtractedElts[32];
9829         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9830         
9831         for (unsigned i = 0; i != 16; ++i) {
9832           if (isa<UndefValue>(Mask->getOperand(i)))
9833             continue;
9834           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9835           Idx &= 31;  // Match the hardware behavior.
9836           
9837           if (ExtractedElts[Idx] == 0) {
9838             Instruction *Elt = 
9839               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9840             InsertNewInstBefore(Elt, CI);
9841             ExtractedElts[Idx] = Elt;
9842           }
9843         
9844           // Insert this value into the result vector.
9845           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9846                                              i, "tmp");
9847           InsertNewInstBefore(cast<Instruction>(Result), CI);
9848         }
9849         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9850       }
9851     }
9852     break;
9853
9854   case Intrinsic::stackrestore: {
9855     // If the save is right next to the restore, remove the restore.  This can
9856     // happen when variable allocas are DCE'd.
9857     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9858       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9859         BasicBlock::iterator BI = SS;
9860         if (&*++BI == II)
9861           return EraseInstFromFunction(CI);
9862       }
9863     }
9864     
9865     // Scan down this block to see if there is another stack restore in the
9866     // same block without an intervening call/alloca.
9867     BasicBlock::iterator BI = II;
9868     TerminatorInst *TI = II->getParent()->getTerminator();
9869     bool CannotRemove = false;
9870     for (++BI; &*BI != TI; ++BI) {
9871       if (isa<AllocaInst>(BI)) {
9872         CannotRemove = true;
9873         break;
9874       }
9875       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9876         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9877           // If there is a stackrestore below this one, remove this one.
9878           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9879             return EraseInstFromFunction(CI);
9880           // Otherwise, ignore the intrinsic.
9881         } else {
9882           // If we found a non-intrinsic call, we can't remove the stack
9883           // restore.
9884           CannotRemove = true;
9885           break;
9886         }
9887       }
9888     }
9889     
9890     // If the stack restore is in a return/unwind block and if there are no
9891     // allocas or calls between the restore and the return, nuke the restore.
9892     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9893       return EraseInstFromFunction(CI);
9894     break;
9895   }
9896   }
9897
9898   return visitCallSite(II);
9899 }
9900
9901 // InvokeInst simplification
9902 //
9903 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9904   return visitCallSite(&II);
9905 }
9906
9907 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9908 /// passed through the varargs area, we can eliminate the use of the cast.
9909 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9910                                          const CastInst * const CI,
9911                                          const TargetData * const TD,
9912                                          const int ix) {
9913   if (!CI->isLosslessCast())
9914     return false;
9915
9916   // The size of ByVal arguments is derived from the type, so we
9917   // can't change to a type with a different size.  If the size were
9918   // passed explicitly we could avoid this check.
9919   if (!CS.paramHasAttr(ix, Attribute::ByVal))
9920     return true;
9921
9922   const Type* SrcTy = 
9923             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9924   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9925   if (!SrcTy->isSized() || !DstTy->isSized())
9926     return false;
9927   if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
9928     return false;
9929   return true;
9930 }
9931
9932 // visitCallSite - Improvements for call and invoke instructions.
9933 //
9934 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9935   bool Changed = false;
9936
9937   // If the callee is a constexpr cast of a function, attempt to move the cast
9938   // to the arguments of the call/invoke.
9939   if (transformConstExprCastCall(CS)) return 0;
9940
9941   Value *Callee = CS.getCalledValue();
9942
9943   if (Function *CalleeF = dyn_cast<Function>(Callee))
9944     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9945       Instruction *OldCall = CS.getInstruction();
9946       // If the call and callee calling conventions don't match, this call must
9947       // be unreachable, as the call is undefined.
9948       new StoreInst(ConstantInt::getTrue(),
9949                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
9950                                     OldCall);
9951       if (!OldCall->use_empty())
9952         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9953       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
9954         return EraseInstFromFunction(*OldCall);
9955       return 0;
9956     }
9957
9958   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9959     // This instruction is not reachable, just remove it.  We insert a store to
9960     // undef so that we know that this code is not reachable, despite the fact
9961     // that we can't modify the CFG here.
9962     new StoreInst(ConstantInt::getTrue(),
9963                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9964                   CS.getInstruction());
9965
9966     if (!CS.getInstruction()->use_empty())
9967       CS.getInstruction()->
9968         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9969
9970     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9971       // Don't break the CFG, insert a dummy cond branch.
9972       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9973                          ConstantInt::getTrue(), II);
9974     }
9975     return EraseInstFromFunction(*CS.getInstruction());
9976   }
9977
9978   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9979     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9980       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9981         return transformCallThroughTrampoline(CS);
9982
9983   const PointerType *PTy = cast<PointerType>(Callee->getType());
9984   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9985   if (FTy->isVarArg()) {
9986     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9987     // See if we can optimize any arguments passed through the varargs area of
9988     // the call.
9989     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9990            E = CS.arg_end(); I != E; ++I, ++ix) {
9991       CastInst *CI = dyn_cast<CastInst>(*I);
9992       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9993         *I = CI->getOperand(0);
9994         Changed = true;
9995       }
9996     }
9997   }
9998
9999   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10000     // Inline asm calls cannot throw - mark them 'nounwind'.
10001     CS.setDoesNotThrow();
10002     Changed = true;
10003   }
10004
10005   return Changed ? CS.getInstruction() : 0;
10006 }
10007
10008 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10009 // attempt to move the cast to the arguments of the call/invoke.
10010 //
10011 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10012   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10013   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10014   if (CE->getOpcode() != Instruction::BitCast || 
10015       !isa<Function>(CE->getOperand(0)))
10016     return false;
10017   Function *Callee = cast<Function>(CE->getOperand(0));
10018   Instruction *Caller = CS.getInstruction();
10019   const AttrListPtr &CallerPAL = CS.getAttributes();
10020
10021   // Okay, this is a cast from a function to a different type.  Unless doing so
10022   // would cause a type conversion of one of our arguments, change this call to
10023   // be a direct call with arguments casted to the appropriate types.
10024   //
10025   const FunctionType *FT = Callee->getFunctionType();
10026   const Type *OldRetTy = Caller->getType();
10027   const Type *NewRetTy = FT->getReturnType();
10028
10029   if (isa<StructType>(NewRetTy))
10030     return false; // TODO: Handle multiple return values.
10031
10032   // Check to see if we are changing the return type...
10033   if (OldRetTy != NewRetTy) {
10034     if (Callee->isDeclaration() &&
10035         // Conversion is ok if changing from one pointer type to another or from
10036         // a pointer to an integer of the same size.
10037         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
10038           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
10039       return false;   // Cannot transform this return value.
10040
10041     if (!Caller->use_empty() &&
10042         // void -> non-void is handled specially
10043         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
10044       return false;   // Cannot transform this return value.
10045
10046     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10047       Attributes RAttrs = CallerPAL.getRetAttributes();
10048       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10049         return false;   // Attribute not compatible with transformed value.
10050     }
10051
10052     // If the callsite is an invoke instruction, and the return value is used by
10053     // a PHI node in a successor, we cannot change the return type of the call
10054     // because there is no place to put the cast instruction (without breaking
10055     // the critical edge).  Bail out in this case.
10056     if (!Caller->use_empty())
10057       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10058         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10059              UI != E; ++UI)
10060           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10061             if (PN->getParent() == II->getNormalDest() ||
10062                 PN->getParent() == II->getUnwindDest())
10063               return false;
10064   }
10065
10066   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10067   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10068
10069   CallSite::arg_iterator AI = CS.arg_begin();
10070   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10071     const Type *ParamTy = FT->getParamType(i);
10072     const Type *ActTy = (*AI)->getType();
10073
10074     if (!CastInst::isCastable(ActTy, ParamTy))
10075       return false;   // Cannot transform this parameter value.
10076
10077     if (CallerPAL.getParamAttributes(i + 1) 
10078         & Attribute::typeIncompatible(ParamTy))
10079       return false;   // Attribute not compatible with transformed value.
10080
10081     // Converting from one pointer type to another or between a pointer and an
10082     // integer of the same size is safe even if we do not have a body.
10083     bool isConvertible = ActTy == ParamTy ||
10084       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10085        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
10086     if (Callee->isDeclaration() && !isConvertible) return false;
10087   }
10088
10089   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10090       Callee->isDeclaration())
10091     return false;   // Do not delete arguments unless we have a function body.
10092
10093   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10094       !CallerPAL.isEmpty())
10095     // In this case we have more arguments than the new function type, but we
10096     // won't be dropping them.  Check that these extra arguments have attributes
10097     // that are compatible with being a vararg call argument.
10098     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10099       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10100         break;
10101       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10102       if (PAttrs & Attribute::VarArgsIncompatible)
10103         return false;
10104     }
10105
10106   // Okay, we decided that this is a safe thing to do: go ahead and start
10107   // inserting cast instructions as necessary...
10108   std::vector<Value*> Args;
10109   Args.reserve(NumActualArgs);
10110   SmallVector<AttributeWithIndex, 8> attrVec;
10111   attrVec.reserve(NumCommonArgs);
10112
10113   // Get any return attributes.
10114   Attributes RAttrs = CallerPAL.getRetAttributes();
10115
10116   // If the return value is not being used, the type may not be compatible
10117   // with the existing attributes.  Wipe out any problematic attributes.
10118   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10119
10120   // Add the new return attributes.
10121   if (RAttrs)
10122     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10123
10124   AI = CS.arg_begin();
10125   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10126     const Type *ParamTy = FT->getParamType(i);
10127     if ((*AI)->getType() == ParamTy) {
10128       Args.push_back(*AI);
10129     } else {
10130       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10131           false, ParamTy, false);
10132       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10133       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10134     }
10135
10136     // Add any parameter attributes.
10137     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10138       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10139   }
10140
10141   // If the function takes more arguments than the call was taking, add them
10142   // now...
10143   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10144     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10145
10146   // If we are removing arguments to the function, emit an obnoxious warning...
10147   if (FT->getNumParams() < NumActualArgs) {
10148     if (!FT->isVarArg()) {
10149       cerr << "WARNING: While resolving call to function '"
10150            << Callee->getName() << "' arguments were dropped!\n";
10151     } else {
10152       // Add all of the arguments in their promoted form to the arg list...
10153       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10154         const Type *PTy = getPromotedType((*AI)->getType());
10155         if (PTy != (*AI)->getType()) {
10156           // Must promote to pass through va_arg area!
10157           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
10158                                                                 PTy, false);
10159           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10160           InsertNewInstBefore(Cast, *Caller);
10161           Args.push_back(Cast);
10162         } else {
10163           Args.push_back(*AI);
10164         }
10165
10166         // Add any parameter attributes.
10167         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10168           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10169       }
10170     }
10171   }
10172
10173   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10174     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10175
10176   if (NewRetTy == Type::VoidTy)
10177     Caller->setName("");   // Void type should not have a name.
10178
10179   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
10180
10181   Instruction *NC;
10182   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10183     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10184                             Args.begin(), Args.end(),
10185                             Caller->getName(), Caller);
10186     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10187     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10188   } else {
10189     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10190                           Caller->getName(), Caller);
10191     CallInst *CI = cast<CallInst>(Caller);
10192     if (CI->isTailCall())
10193       cast<CallInst>(NC)->setTailCall();
10194     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10195     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10196   }
10197
10198   // Insert a cast of the return type as necessary.
10199   Value *NV = NC;
10200   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10201     if (NV->getType() != Type::VoidTy) {
10202       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10203                                                             OldRetTy, false);
10204       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10205
10206       // If this is an invoke instruction, we should insert it after the first
10207       // non-phi, instruction in the normal successor block.
10208       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10209         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10210         InsertNewInstBefore(NC, *I);
10211       } else {
10212         // Otherwise, it's a call, just insert cast right after the call instr
10213         InsertNewInstBefore(NC, *Caller);
10214       }
10215       AddUsersToWorkList(*Caller);
10216     } else {
10217       NV = UndefValue::get(Caller->getType());
10218     }
10219   }
10220
10221   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10222     Caller->replaceAllUsesWith(NV);
10223   Caller->eraseFromParent();
10224   RemoveFromWorkList(Caller);
10225   return true;
10226 }
10227
10228 // transformCallThroughTrampoline - Turn a call to a function created by the
10229 // init_trampoline intrinsic into a direct call to the underlying function.
10230 //
10231 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10232   Value *Callee = CS.getCalledValue();
10233   const PointerType *PTy = cast<PointerType>(Callee->getType());
10234   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10235   const AttrListPtr &Attrs = CS.getAttributes();
10236
10237   // If the call already has the 'nest' attribute somewhere then give up -
10238   // otherwise 'nest' would occur twice after splicing in the chain.
10239   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10240     return 0;
10241
10242   IntrinsicInst *Tramp =
10243     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10244
10245   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10246   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10247   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10248
10249   const AttrListPtr &NestAttrs = NestF->getAttributes();
10250   if (!NestAttrs.isEmpty()) {
10251     unsigned NestIdx = 1;
10252     const Type *NestTy = 0;
10253     Attributes NestAttr = Attribute::None;
10254
10255     // Look for a parameter marked with the 'nest' attribute.
10256     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10257          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10258       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10259         // Record the parameter type and any other attributes.
10260         NestTy = *I;
10261         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10262         break;
10263       }
10264
10265     if (NestTy) {
10266       Instruction *Caller = CS.getInstruction();
10267       std::vector<Value*> NewArgs;
10268       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10269
10270       SmallVector<AttributeWithIndex, 8> NewAttrs;
10271       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10272
10273       // Insert the nest argument into the call argument list, which may
10274       // mean appending it.  Likewise for attributes.
10275
10276       // Add any result attributes.
10277       if (Attributes Attr = Attrs.getRetAttributes())
10278         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10279
10280       {
10281         unsigned Idx = 1;
10282         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10283         do {
10284           if (Idx == NestIdx) {
10285             // Add the chain argument and attributes.
10286             Value *NestVal = Tramp->getOperand(3);
10287             if (NestVal->getType() != NestTy)
10288               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10289             NewArgs.push_back(NestVal);
10290             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10291           }
10292
10293           if (I == E)
10294             break;
10295
10296           // Add the original argument and attributes.
10297           NewArgs.push_back(*I);
10298           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10299             NewAttrs.push_back
10300               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10301
10302           ++Idx, ++I;
10303         } while (1);
10304       }
10305
10306       // Add any function attributes.
10307       if (Attributes Attr = Attrs.getFnAttributes())
10308         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10309
10310       // The trampoline may have been bitcast to a bogus type (FTy).
10311       // Handle this by synthesizing a new function type, equal to FTy
10312       // with the chain parameter inserted.
10313
10314       std::vector<const Type*> NewTypes;
10315       NewTypes.reserve(FTy->getNumParams()+1);
10316
10317       // Insert the chain's type into the list of parameter types, which may
10318       // mean appending it.
10319       {
10320         unsigned Idx = 1;
10321         FunctionType::param_iterator I = FTy->param_begin(),
10322           E = FTy->param_end();
10323
10324         do {
10325           if (Idx == NestIdx)
10326             // Add the chain's type.
10327             NewTypes.push_back(NestTy);
10328
10329           if (I == E)
10330             break;
10331
10332           // Add the original type.
10333           NewTypes.push_back(*I);
10334
10335           ++Idx, ++I;
10336         } while (1);
10337       }
10338
10339       // Replace the trampoline call with a direct call.  Let the generic
10340       // code sort out any function type mismatches.
10341       FunctionType *NewFTy =
10342         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
10343       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
10344         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
10345       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
10346
10347       Instruction *NewCaller;
10348       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10349         NewCaller = InvokeInst::Create(NewCallee,
10350                                        II->getNormalDest(), II->getUnwindDest(),
10351                                        NewArgs.begin(), NewArgs.end(),
10352                                        Caller->getName(), Caller);
10353         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10354         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10355       } else {
10356         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10357                                      Caller->getName(), Caller);
10358         if (cast<CallInst>(Caller)->isTailCall())
10359           cast<CallInst>(NewCaller)->setTailCall();
10360         cast<CallInst>(NewCaller)->
10361           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10362         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10363       }
10364       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10365         Caller->replaceAllUsesWith(NewCaller);
10366       Caller->eraseFromParent();
10367       RemoveFromWorkList(Caller);
10368       return 0;
10369     }
10370   }
10371
10372   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10373   // parameter, there is no need to adjust the argument list.  Let the generic
10374   // code sort out any function type mismatches.
10375   Constant *NewCallee =
10376     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
10377   CS.setCalledFunction(NewCallee);
10378   return CS.getInstruction();
10379 }
10380
10381 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10382 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10383 /// and a single binop.
10384 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10385   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10386   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10387   unsigned Opc = FirstInst->getOpcode();
10388   Value *LHSVal = FirstInst->getOperand(0);
10389   Value *RHSVal = FirstInst->getOperand(1);
10390     
10391   const Type *LHSType = LHSVal->getType();
10392   const Type *RHSType = RHSVal->getType();
10393   
10394   // Scan to see if all operands are the same opcode, all have one use, and all
10395   // kill their operands (i.e. the operands have one use).
10396   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10397     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10398     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10399         // Verify type of the LHS matches so we don't fold cmp's of different
10400         // types or GEP's with different index types.
10401         I->getOperand(0)->getType() != LHSType ||
10402         I->getOperand(1)->getType() != RHSType)
10403       return 0;
10404
10405     // If they are CmpInst instructions, check their predicates
10406     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10407       if (cast<CmpInst>(I)->getPredicate() !=
10408           cast<CmpInst>(FirstInst)->getPredicate())
10409         return 0;
10410     
10411     // Keep track of which operand needs a phi node.
10412     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10413     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10414   }
10415   
10416   // Otherwise, this is safe to transform!
10417   
10418   Value *InLHS = FirstInst->getOperand(0);
10419   Value *InRHS = FirstInst->getOperand(1);
10420   PHINode *NewLHS = 0, *NewRHS = 0;
10421   if (LHSVal == 0) {
10422     NewLHS = PHINode::Create(LHSType,
10423                              FirstInst->getOperand(0)->getName() + ".pn");
10424     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10425     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10426     InsertNewInstBefore(NewLHS, PN);
10427     LHSVal = NewLHS;
10428   }
10429   
10430   if (RHSVal == 0) {
10431     NewRHS = PHINode::Create(RHSType,
10432                              FirstInst->getOperand(1)->getName() + ".pn");
10433     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10434     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10435     InsertNewInstBefore(NewRHS, PN);
10436     RHSVal = NewRHS;
10437   }
10438   
10439   // Add all operands to the new PHIs.
10440   if (NewLHS || NewRHS) {
10441     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10442       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10443       if (NewLHS) {
10444         Value *NewInLHS = InInst->getOperand(0);
10445         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10446       }
10447       if (NewRHS) {
10448         Value *NewInRHS = InInst->getOperand(1);
10449         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10450       }
10451     }
10452   }
10453     
10454   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10455     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10456   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10457   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10458                          RHSVal);
10459 }
10460
10461 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10462   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10463   
10464   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10465                                         FirstInst->op_end());
10466   // This is true if all GEP bases are allocas and if all indices into them are
10467   // constants.
10468   bool AllBasePointersAreAllocas = true;
10469   
10470   // Scan to see if all operands are the same opcode, all have one use, and all
10471   // kill their operands (i.e. the operands have one use).
10472   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10473     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10474     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10475       GEP->getNumOperands() != FirstInst->getNumOperands())
10476       return 0;
10477
10478     // Keep track of whether or not all GEPs are of alloca pointers.
10479     if (AllBasePointersAreAllocas &&
10480         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10481          !GEP->hasAllConstantIndices()))
10482       AllBasePointersAreAllocas = false;
10483     
10484     // Compare the operand lists.
10485     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10486       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10487         continue;
10488       
10489       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10490       // if one of the PHIs has a constant for the index.  The index may be
10491       // substantially cheaper to compute for the constants, so making it a
10492       // variable index could pessimize the path.  This also handles the case
10493       // for struct indices, which must always be constant.
10494       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10495           isa<ConstantInt>(GEP->getOperand(op)))
10496         return 0;
10497       
10498       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10499         return 0;
10500       FixedOperands[op] = 0;  // Needs a PHI.
10501     }
10502   }
10503   
10504   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10505   // bother doing this transformation.  At best, this will just save a bit of
10506   // offset calculation, but all the predecessors will have to materialize the
10507   // stack address into a register anyway.  We'd actually rather *clone* the
10508   // load up into the predecessors so that we have a load of a gep of an alloca,
10509   // which can usually all be folded into the load.
10510   if (AllBasePointersAreAllocas)
10511     return 0;
10512   
10513   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10514   // that is variable.
10515   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10516   
10517   bool HasAnyPHIs = false;
10518   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10519     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10520     Value *FirstOp = FirstInst->getOperand(i);
10521     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10522                                      FirstOp->getName()+".pn");
10523     InsertNewInstBefore(NewPN, PN);
10524     
10525     NewPN->reserveOperandSpace(e);
10526     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10527     OperandPhis[i] = NewPN;
10528     FixedOperands[i] = NewPN;
10529     HasAnyPHIs = true;
10530   }
10531
10532   
10533   // Add all operands to the new PHIs.
10534   if (HasAnyPHIs) {
10535     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10536       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10537       BasicBlock *InBB = PN.getIncomingBlock(i);
10538       
10539       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10540         if (PHINode *OpPhi = OperandPhis[op])
10541           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10542     }
10543   }
10544   
10545   Value *Base = FixedOperands[0];
10546   return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10547                                    FixedOperands.end());
10548 }
10549
10550
10551 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10552 /// sink the load out of the block that defines it.  This means that it must be
10553 /// obvious the value of the load is not changed from the point of the load to
10554 /// the end of the block it is in.
10555 ///
10556 /// Finally, it is safe, but not profitable, to sink a load targetting a
10557 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10558 /// to a register.
10559 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10560   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10561   
10562   for (++BBI; BBI != E; ++BBI)
10563     if (BBI->mayWriteToMemory())
10564       return false;
10565   
10566   // Check for non-address taken alloca.  If not address-taken already, it isn't
10567   // profitable to do this xform.
10568   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10569     bool isAddressTaken = false;
10570     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10571          UI != E; ++UI) {
10572       if (isa<LoadInst>(UI)) continue;
10573       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10574         // If storing TO the alloca, then the address isn't taken.
10575         if (SI->getOperand(1) == AI) continue;
10576       }
10577       isAddressTaken = true;
10578       break;
10579     }
10580     
10581     if (!isAddressTaken && AI->isStaticAlloca())
10582       return false;
10583   }
10584   
10585   // If this load is a load from a GEP with a constant offset from an alloca,
10586   // then we don't want to sink it.  In its present form, it will be
10587   // load [constant stack offset].  Sinking it will cause us to have to
10588   // materialize the stack addresses in each predecessor in a register only to
10589   // do a shared load from register in the successor.
10590   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10591     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10592       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10593         return false;
10594   
10595   return true;
10596 }
10597
10598
10599 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10600 // operator and they all are only used by the PHI, PHI together their
10601 // inputs, and do the operation once, to the result of the PHI.
10602 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10603   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10604
10605   // Scan the instruction, looking for input operations that can be folded away.
10606   // If all input operands to the phi are the same instruction (e.g. a cast from
10607   // the same type or "+42") we can pull the operation through the PHI, reducing
10608   // code size and simplifying code.
10609   Constant *ConstantOp = 0;
10610   const Type *CastSrcTy = 0;
10611   bool isVolatile = false;
10612   if (isa<CastInst>(FirstInst)) {
10613     CastSrcTy = FirstInst->getOperand(0)->getType();
10614   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10615     // Can fold binop, compare or shift here if the RHS is a constant, 
10616     // otherwise call FoldPHIArgBinOpIntoPHI.
10617     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10618     if (ConstantOp == 0)
10619       return FoldPHIArgBinOpIntoPHI(PN);
10620   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10621     isVolatile = LI->isVolatile();
10622     // We can't sink the load if the loaded value could be modified between the
10623     // load and the PHI.
10624     if (LI->getParent() != PN.getIncomingBlock(0) ||
10625         !isSafeAndProfitableToSinkLoad(LI))
10626       return 0;
10627     
10628     // If the PHI is of volatile loads and the load block has multiple
10629     // successors, sinking it would remove a load of the volatile value from
10630     // the path through the other successor.
10631     if (isVolatile &&
10632         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10633       return 0;
10634     
10635   } else if (isa<GetElementPtrInst>(FirstInst)) {
10636     return FoldPHIArgGEPIntoPHI(PN);
10637   } else {
10638     return 0;  // Cannot fold this operation.
10639   }
10640
10641   // Check to see if all arguments are the same operation.
10642   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10643     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10644     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10645     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10646       return 0;
10647     if (CastSrcTy) {
10648       if (I->getOperand(0)->getType() != CastSrcTy)
10649         return 0;  // Cast operation must match.
10650     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10651       // We can't sink the load if the loaded value could be modified between 
10652       // the load and the PHI.
10653       if (LI->isVolatile() != isVolatile ||
10654           LI->getParent() != PN.getIncomingBlock(i) ||
10655           !isSafeAndProfitableToSinkLoad(LI))
10656         return 0;
10657       
10658       // If the PHI is of volatile loads and the load block has multiple
10659       // successors, sinking it would remove a load of the volatile value from
10660       // the path through the other successor.
10661       if (isVolatile &&
10662           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10663         return 0;
10664       
10665     } else if (I->getOperand(1) != ConstantOp) {
10666       return 0;
10667     }
10668   }
10669
10670   // Okay, they are all the same operation.  Create a new PHI node of the
10671   // correct type, and PHI together all of the LHS's of the instructions.
10672   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10673                                    PN.getName()+".in");
10674   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10675
10676   Value *InVal = FirstInst->getOperand(0);
10677   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10678
10679   // Add all operands to the new PHI.
10680   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10681     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10682     if (NewInVal != InVal)
10683       InVal = 0;
10684     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10685   }
10686
10687   Value *PhiVal;
10688   if (InVal) {
10689     // The new PHI unions all of the same values together.  This is really
10690     // common, so we handle it intelligently here for compile-time speed.
10691     PhiVal = InVal;
10692     delete NewPN;
10693   } else {
10694     InsertNewInstBefore(NewPN, PN);
10695     PhiVal = NewPN;
10696   }
10697
10698   // Insert and return the new operation.
10699   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10700     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10701   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10702     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10703   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10704     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
10705                            PhiVal, ConstantOp);
10706   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10707   
10708   // If this was a volatile load that we are merging, make sure to loop through
10709   // and mark all the input loads as non-volatile.  If we don't do this, we will
10710   // insert a new volatile load and the old ones will not be deletable.
10711   if (isVolatile)
10712     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10713       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10714   
10715   return new LoadInst(PhiVal, "", isVolatile);
10716 }
10717
10718 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10719 /// that is dead.
10720 static bool DeadPHICycle(PHINode *PN,
10721                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10722   if (PN->use_empty()) return true;
10723   if (!PN->hasOneUse()) return false;
10724
10725   // Remember this node, and if we find the cycle, return.
10726   if (!PotentiallyDeadPHIs.insert(PN))
10727     return true;
10728   
10729   // Don't scan crazily complex things.
10730   if (PotentiallyDeadPHIs.size() == 16)
10731     return false;
10732
10733   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10734     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10735
10736   return false;
10737 }
10738
10739 /// PHIsEqualValue - Return true if this phi node is always equal to
10740 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10741 ///   z = some value; x = phi (y, z); y = phi (x, z)
10742 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10743                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10744   // See if we already saw this PHI node.
10745   if (!ValueEqualPHIs.insert(PN))
10746     return true;
10747   
10748   // Don't scan crazily complex things.
10749   if (ValueEqualPHIs.size() == 16)
10750     return false;
10751  
10752   // Scan the operands to see if they are either phi nodes or are equal to
10753   // the value.
10754   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10755     Value *Op = PN->getIncomingValue(i);
10756     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10757       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10758         return false;
10759     } else if (Op != NonPhiInVal)
10760       return false;
10761   }
10762   
10763   return true;
10764 }
10765
10766
10767 // PHINode simplification
10768 //
10769 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10770   // If LCSSA is around, don't mess with Phi nodes
10771   if (MustPreserveLCSSA) return 0;
10772   
10773   if (Value *V = PN.hasConstantValue())
10774     return ReplaceInstUsesWith(PN, V);
10775
10776   // If all PHI operands are the same operation, pull them through the PHI,
10777   // reducing code size.
10778   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10779       isa<Instruction>(PN.getIncomingValue(1)) &&
10780       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10781       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10782       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10783       // than themselves more than once.
10784       PN.getIncomingValue(0)->hasOneUse())
10785     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10786       return Result;
10787
10788   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10789   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10790   // PHI)... break the cycle.
10791   if (PN.hasOneUse()) {
10792     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10793     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10794       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10795       PotentiallyDeadPHIs.insert(&PN);
10796       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10797         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10798     }
10799    
10800     // If this phi has a single use, and if that use just computes a value for
10801     // the next iteration of a loop, delete the phi.  This occurs with unused
10802     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10803     // common case here is good because the only other things that catch this
10804     // are induction variable analysis (sometimes) and ADCE, which is only run
10805     // late.
10806     if (PHIUser->hasOneUse() &&
10807         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10808         PHIUser->use_back() == &PN) {
10809       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10810     }
10811   }
10812
10813   // We sometimes end up with phi cycles that non-obviously end up being the
10814   // same value, for example:
10815   //   z = some value; x = phi (y, z); y = phi (x, z)
10816   // where the phi nodes don't necessarily need to be in the same block.  Do a
10817   // quick check to see if the PHI node only contains a single non-phi value, if
10818   // so, scan to see if the phi cycle is actually equal to that value.
10819   {
10820     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10821     // Scan for the first non-phi operand.
10822     while (InValNo != NumOperandVals && 
10823            isa<PHINode>(PN.getIncomingValue(InValNo)))
10824       ++InValNo;
10825
10826     if (InValNo != NumOperandVals) {
10827       Value *NonPhiInVal = PN.getOperand(InValNo);
10828       
10829       // Scan the rest of the operands to see if there are any conflicts, if so
10830       // there is no need to recursively scan other phis.
10831       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10832         Value *OpVal = PN.getIncomingValue(InValNo);
10833         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10834           break;
10835       }
10836       
10837       // If we scanned over all operands, then we have one unique value plus
10838       // phi values.  Scan PHI nodes to see if they all merge in each other or
10839       // the value.
10840       if (InValNo == NumOperandVals) {
10841         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10842         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10843           return ReplaceInstUsesWith(PN, NonPhiInVal);
10844       }
10845     }
10846   }
10847   return 0;
10848 }
10849
10850 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10851                                    Instruction *InsertPoint,
10852                                    InstCombiner *IC) {
10853   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10854   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
10855   // We must cast correctly to the pointer type. Ensure that we
10856   // sign extend the integer value if it is smaller as this is
10857   // used for address computation.
10858   Instruction::CastOps opcode = 
10859      (VTySize < PtrSize ? Instruction::SExt :
10860       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10861   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10862 }
10863
10864
10865 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10866   Value *PtrOp = GEP.getOperand(0);
10867   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10868   // If so, eliminate the noop.
10869   if (GEP.getNumOperands() == 1)
10870     return ReplaceInstUsesWith(GEP, PtrOp);
10871
10872   if (isa<UndefValue>(GEP.getOperand(0)))
10873     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10874
10875   bool HasZeroPointerIndex = false;
10876   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10877     HasZeroPointerIndex = C->isNullValue();
10878
10879   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10880     return ReplaceInstUsesWith(GEP, PtrOp);
10881
10882   // Eliminate unneeded casts for indices.
10883   bool MadeChange = false;
10884   
10885   gep_type_iterator GTI = gep_type_begin(GEP);
10886   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10887        i != e; ++i, ++GTI) {
10888     if (isa<SequentialType>(*GTI)) {
10889       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
10890         if (CI->getOpcode() == Instruction::ZExt ||
10891             CI->getOpcode() == Instruction::SExt) {
10892           const Type *SrcTy = CI->getOperand(0)->getType();
10893           // We can eliminate a cast from i32 to i64 iff the target 
10894           // is a 32-bit pointer target.
10895           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10896             MadeChange = true;
10897             *i = CI->getOperand(0);
10898           }
10899         }
10900       }
10901       // If we are using a wider index than needed for this platform, shrink it
10902       // to what we need.  If narrower, sign-extend it to what we need.
10903       // If the incoming value needs a cast instruction,
10904       // insert it.  This explicit cast can make subsequent optimizations more
10905       // obvious.
10906       Value *Op = *i;
10907       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
10908         if (Constant *C = dyn_cast<Constant>(Op)) {
10909           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
10910           MadeChange = true;
10911         } else {
10912           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10913                                 GEP);
10914           *i = Op;
10915           MadeChange = true;
10916         }
10917       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10918         if (Constant *C = dyn_cast<Constant>(Op)) {
10919           *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10920           MadeChange = true;
10921         } else {
10922           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10923                                 GEP);
10924           *i = Op;
10925           MadeChange = true;
10926         }
10927       }
10928     }
10929   }
10930   if (MadeChange) return &GEP;
10931
10932   // Combine Indices - If the source pointer to this getelementptr instruction
10933   // is a getelementptr instruction, combine the indices of the two
10934   // getelementptr instructions into a single instruction.
10935   //
10936   SmallVector<Value*, 8> SrcGEPOperands;
10937   if (User *Src = dyn_castGetElementPtr(PtrOp))
10938     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
10939
10940   if (!SrcGEPOperands.empty()) {
10941     // Note that if our source is a gep chain itself that we wait for that
10942     // chain to be resolved before we perform this transformation.  This
10943     // avoids us creating a TON of code in some cases.
10944     //
10945     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10946         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10947       return 0;   // Wait until our source is folded to completion.
10948
10949     SmallVector<Value*, 8> Indices;
10950
10951     // Find out whether the last index in the source GEP is a sequential idx.
10952     bool EndsWithSequential = false;
10953     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10954            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
10955       EndsWithSequential = !isa<StructType>(*I);
10956
10957     // Can we combine the two pointer arithmetics offsets?
10958     if (EndsWithSequential) {
10959       // Replace: gep (gep %P, long B), long A, ...
10960       // With:    T = long A+B; gep %P, T, ...
10961       //
10962       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
10963       if (SO1 == Constant::getNullValue(SO1->getType())) {
10964         Sum = GO1;
10965       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10966         Sum = SO1;
10967       } else {
10968         // If they aren't the same type, convert both to an integer of the
10969         // target's pointer size.
10970         if (SO1->getType() != GO1->getType()) {
10971           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
10972             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
10973           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
10974             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
10975           } else {
10976             unsigned PS = TD->getPointerSizeInBits();
10977             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
10978               // Convert GO1 to SO1's type.
10979               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
10980
10981             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
10982               // Convert SO1 to GO1's type.
10983               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
10984             } else {
10985               const Type *PT = TD->getIntPtrType();
10986               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10987               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
10988             }
10989           }
10990         }
10991         if (isa<Constant>(SO1) && isa<Constant>(GO1))
10992           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10993         else {
10994           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10995           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
10996         }
10997       }
10998
10999       // Recycle the GEP we already have if possible.
11000       if (SrcGEPOperands.size() == 2) {
11001         GEP.setOperand(0, SrcGEPOperands[0]);
11002         GEP.setOperand(1, Sum);
11003         return &GEP;
11004       } else {
11005         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11006                        SrcGEPOperands.end()-1);
11007         Indices.push_back(Sum);
11008         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11009       }
11010     } else if (isa<Constant>(*GEP.idx_begin()) &&
11011                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11012                SrcGEPOperands.size() != 1) {
11013       // Otherwise we can do the fold if the first index of the GEP is a zero
11014       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11015                      SrcGEPOperands.end());
11016       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11017     }
11018
11019     if (!Indices.empty())
11020       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11021                                        Indices.end(), GEP.getName());
11022
11023   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11024     // GEP of global variable.  If all of the indices for this GEP are
11025     // constants, we can promote this to a constexpr instead of an instruction.
11026
11027     // Scan for nonconstants...
11028     SmallVector<Constant*, 8> Indices;
11029     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11030     for (; I != E && isa<Constant>(*I); ++I)
11031       Indices.push_back(cast<Constant>(*I));
11032
11033     if (I == E) {  // If they are all constants...
11034       Constant *CE = ConstantExpr::getGetElementPtr(GV,
11035                                                     &Indices[0],Indices.size());
11036
11037       // Replace all uses of the GEP with the new constexpr...
11038       return ReplaceInstUsesWith(GEP, CE);
11039     }
11040   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
11041     if (!isa<PointerType>(X->getType())) {
11042       // Not interesting.  Source pointer must be a cast from pointer.
11043     } else if (HasZeroPointerIndex) {
11044       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11045       // into     : GEP [10 x i8]* X, i32 0, ...
11046       //
11047       // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11048       //           into     : GEP i8* X, ...
11049       // 
11050       // This occurs when the program declares an array extern like "int X[];"
11051       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11052       const PointerType *XTy = cast<PointerType>(X->getType());
11053       if (const ArrayType *CATy =
11054           dyn_cast<ArrayType>(CPTy->getElementType())) {
11055         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11056         if (CATy->getElementType() == XTy->getElementType()) {
11057           // -> GEP i8* X, ...
11058           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11059           return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11060                                            GEP.getName());
11061         } else if (const ArrayType *XATy =
11062                  dyn_cast<ArrayType>(XTy->getElementType())) {
11063           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11064           if (CATy->getElementType() == XATy->getElementType()) {
11065             // -> GEP [10 x i8]* X, i32 0, ...
11066             // At this point, we know that the cast source type is a pointer
11067             // to an array of the same type as the destination pointer
11068             // array.  Because the array type is never stepped over (there
11069             // is a leading zero) we can fold the cast into this GEP.
11070             GEP.setOperand(0, X);
11071             return &GEP;
11072           }
11073         }
11074       }
11075     } else if (GEP.getNumOperands() == 2) {
11076       // Transform things like:
11077       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11078       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11079       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11080       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11081       if (isa<ArrayType>(SrcElTy) &&
11082           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11083           TD->getTypeAllocSize(ResElTy)) {
11084         Value *Idx[2];
11085         Idx[0] = Constant::getNullValue(Type::Int32Ty);
11086         Idx[1] = GEP.getOperand(1);
11087         Value *V = InsertNewInstBefore(
11088                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
11089         // V and GEP are both pointer types --> BitCast
11090         return new BitCastInst(V, GEP.getType());
11091       }
11092       
11093       // Transform things like:
11094       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11095       //   (where tmp = 8*tmp2) into:
11096       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11097       
11098       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
11099         uint64_t ArrayEltSize =
11100             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11101         
11102         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11103         // allow either a mul, shift, or constant here.
11104         Value *NewIdx = 0;
11105         ConstantInt *Scale = 0;
11106         if (ArrayEltSize == 1) {
11107           NewIdx = GEP.getOperand(1);
11108           Scale = ConstantInt::get(NewIdx->getType(), 1);
11109         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11110           NewIdx = ConstantInt::get(CI->getType(), 1);
11111           Scale = CI;
11112         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11113           if (Inst->getOpcode() == Instruction::Shl &&
11114               isa<ConstantInt>(Inst->getOperand(1))) {
11115             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11116             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11117             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
11118             NewIdx = Inst->getOperand(0);
11119           } else if (Inst->getOpcode() == Instruction::Mul &&
11120                      isa<ConstantInt>(Inst->getOperand(1))) {
11121             Scale = cast<ConstantInt>(Inst->getOperand(1));
11122             NewIdx = Inst->getOperand(0);
11123           }
11124         }
11125         
11126         // If the index will be to exactly the right offset with the scale taken
11127         // out, perform the transformation. Note, we don't know whether Scale is
11128         // signed or not. We'll use unsigned version of division/modulo
11129         // operation after making sure Scale doesn't have the sign bit set.
11130         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11131             Scale->getZExtValue() % ArrayEltSize == 0) {
11132           Scale = ConstantInt::get(Scale->getType(),
11133                                    Scale->getZExtValue() / ArrayEltSize);
11134           if (Scale->getZExtValue() != 1) {
11135             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11136                                                        false /*ZExt*/);
11137             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11138             NewIdx = InsertNewInstBefore(Sc, GEP);
11139           }
11140
11141           // Insert the new GEP instruction.
11142           Value *Idx[2];
11143           Idx[0] = Constant::getNullValue(Type::Int32Ty);
11144           Idx[1] = NewIdx;
11145           Instruction *NewGEP =
11146             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11147           NewGEP = InsertNewInstBefore(NewGEP, GEP);
11148           // The NewGEP must be pointer typed, so must the old one -> BitCast
11149           return new BitCastInst(NewGEP, GEP.getType());
11150         }
11151       }
11152     }
11153   }
11154   
11155   /// See if we can simplify:
11156   ///   X = bitcast A to B*
11157   ///   Y = gep X, <...constant indices...>
11158   /// into a gep of the original struct.  This is important for SROA and alias
11159   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11160   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11161     if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11162       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11163       // a constant back from EmitGEPOffset.
11164       ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11165       int64_t Offset = OffsetV->getSExtValue();
11166       
11167       // If this GEP instruction doesn't move the pointer, just replace the GEP
11168       // with a bitcast of the real input to the dest type.
11169       if (Offset == 0) {
11170         // If the bitcast is of an allocation, and the allocation will be
11171         // converted to match the type of the cast, don't touch this.
11172         if (isa<AllocationInst>(BCI->getOperand(0))) {
11173           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11174           if (Instruction *I = visitBitCast(*BCI)) {
11175             if (I != BCI) {
11176               I->takeName(BCI);
11177               BCI->getParent()->getInstList().insert(BCI, I);
11178               ReplaceInstUsesWith(*BCI, I);
11179             }
11180             return &GEP;
11181           }
11182         }
11183         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11184       }
11185       
11186       // Otherwise, if the offset is non-zero, we need to find out if there is a
11187       // field at Offset in 'A's type.  If so, we can pull the cast through the
11188       // GEP.
11189       SmallVector<Value*, 8> NewIndices;
11190       const Type *InTy =
11191         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11192       if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
11193         Instruction *NGEP =
11194            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11195                                      NewIndices.end());
11196         if (NGEP->getType() == GEP.getType()) return NGEP;
11197         InsertNewInstBefore(NGEP, GEP);
11198         NGEP->takeName(&GEP);
11199         return new BitCastInst(NGEP, GEP.getType());
11200       }
11201     }
11202   }    
11203     
11204   return 0;
11205 }
11206
11207 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11208   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11209   if (AI.isArrayAllocation()) {  // Check C != 1
11210     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11211       const Type *NewTy = 
11212         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11213       AllocationInst *New = 0;
11214
11215       // Create and insert the replacement instruction...
11216       if (isa<MallocInst>(AI))
11217         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11218       else {
11219         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11220         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11221       }
11222
11223       InsertNewInstBefore(New, AI);
11224
11225       // Scan to the end of the allocation instructions, to skip over a block of
11226       // allocas if possible...also skip interleaved debug info
11227       //
11228       BasicBlock::iterator It = New;
11229       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11230
11231       // Now that I is pointing to the first non-allocation-inst in the block,
11232       // insert our getelementptr instruction...
11233       //
11234       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
11235       Value *Idx[2];
11236       Idx[0] = NullIdx;
11237       Idx[1] = NullIdx;
11238       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11239                                            New->getName()+".sub", It);
11240
11241       // Now make everything use the getelementptr instead of the original
11242       // allocation.
11243       return ReplaceInstUsesWith(AI, V);
11244     } else if (isa<UndefValue>(AI.getArraySize())) {
11245       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11246     }
11247   }
11248
11249   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11250     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11251     // Note that we only do this for alloca's, because malloc should allocate
11252     // and return a unique pointer, even for a zero byte allocation.
11253     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11254       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11255
11256     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11257     if (AI.getAlignment() == 0)
11258       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11259   }
11260
11261   return 0;
11262 }
11263
11264 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11265   Value *Op = FI.getOperand(0);
11266
11267   // free undef -> unreachable.
11268   if (isa<UndefValue>(Op)) {
11269     // Insert a new store to null because we cannot modify the CFG here.
11270     new StoreInst(ConstantInt::getTrue(),
11271                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
11272     return EraseInstFromFunction(FI);
11273   }
11274   
11275   // If we have 'free null' delete the instruction.  This can happen in stl code
11276   // when lots of inlining happens.
11277   if (isa<ConstantPointerNull>(Op))
11278     return EraseInstFromFunction(FI);
11279   
11280   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11281   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11282     FI.setOperand(0, CI->getOperand(0));
11283     return &FI;
11284   }
11285   
11286   // Change free (gep X, 0,0,0,0) into free(X)
11287   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11288     if (GEPI->hasAllZeroIndices()) {
11289       AddToWorkList(GEPI);
11290       FI.setOperand(0, GEPI->getOperand(0));
11291       return &FI;
11292     }
11293   }
11294   
11295   // Change free(malloc) into nothing, if the malloc has a single use.
11296   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11297     if (MI->hasOneUse()) {
11298       EraseInstFromFunction(FI);
11299       return EraseInstFromFunction(*MI);
11300     }
11301
11302   return 0;
11303 }
11304
11305
11306 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11307 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11308                                         const TargetData *TD) {
11309   User *CI = cast<User>(LI.getOperand(0));
11310   Value *CastOp = CI->getOperand(0);
11311
11312   if (TD) {
11313     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11314       // Instead of loading constant c string, use corresponding integer value
11315       // directly if string length is small enough.
11316       std::string Str;
11317       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11318         unsigned len = Str.length();
11319         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11320         unsigned numBits = Ty->getPrimitiveSizeInBits();
11321         // Replace LI with immediate integer store.
11322         if ((numBits >> 3) == len + 1) {
11323           APInt StrVal(numBits, 0);
11324           APInt SingleChar(numBits, 0);
11325           if (TD->isLittleEndian()) {
11326             for (signed i = len-1; i >= 0; i--) {
11327               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11328               StrVal = (StrVal << 8) | SingleChar;
11329             }
11330           } else {
11331             for (unsigned i = 0; i < len; i++) {
11332               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11333               StrVal = (StrVal << 8) | SingleChar;
11334             }
11335             // Append NULL at the end.
11336             SingleChar = 0;
11337             StrVal = (StrVal << 8) | SingleChar;
11338           }
11339           Value *NL = ConstantInt::get(StrVal);
11340           return IC.ReplaceInstUsesWith(LI, NL);
11341         }
11342       }
11343     }
11344   }
11345
11346   const PointerType *DestTy = cast<PointerType>(CI->getType());
11347   const Type *DestPTy = DestTy->getElementType();
11348   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11349
11350     // If the address spaces don't match, don't eliminate the cast.
11351     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11352       return 0;
11353
11354     const Type *SrcPTy = SrcTy->getElementType();
11355
11356     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11357          isa<VectorType>(DestPTy)) {
11358       // If the source is an array, the code below will not succeed.  Check to
11359       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11360       // constants.
11361       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11362         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11363           if (ASrcTy->getNumElements() != 0) {
11364             Value *Idxs[2];
11365             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
11366             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11367             SrcTy = cast<PointerType>(CastOp->getType());
11368             SrcPTy = SrcTy->getElementType();
11369           }
11370
11371       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11372             isa<VectorType>(SrcPTy)) &&
11373           // Do not allow turning this into a load of an integer, which is then
11374           // casted to a pointer, this pessimizes pointer analysis a lot.
11375           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11376           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11377                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11378
11379         // Okay, we are casting from one integer or pointer type to another of
11380         // the same size.  Instead of casting the pointer before the load, cast
11381         // the result of the loaded value.
11382         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11383                                                              CI->getName(),
11384                                                          LI.isVolatile()),LI);
11385         // Now cast the result of the load.
11386         return new BitCastInst(NewLoad, LI.getType());
11387       }
11388     }
11389   }
11390   return 0;
11391 }
11392
11393 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
11394 /// from this value cannot trap.  If it is not obviously safe to load from the
11395 /// specified pointer, we do a quick local scan of the basic block containing
11396 /// ScanFrom, to determine if the address is already accessed.
11397 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
11398   // If it is an alloca it is always safe to load from.
11399   if (isa<AllocaInst>(V)) return true;
11400
11401   // If it is a global variable it is mostly safe to load from.
11402   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
11403     // Don't try to evaluate aliases.  External weak GV can be null.
11404     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
11405
11406   // Otherwise, be a little bit agressive by scanning the local block where we
11407   // want to check to see if the pointer is already being loaded or stored
11408   // from/to.  If so, the previous load or store would have already trapped,
11409   // so there is no harm doing an extra load (also, CSE will later eliminate
11410   // the load entirely).
11411   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
11412
11413   while (BBI != E) {
11414     --BBI;
11415
11416     // If we see a free or a call (which might do a free) the pointer could be
11417     // marked invalid.
11418     if (isa<FreeInst>(BBI) || 
11419         (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)))
11420       return false;
11421     
11422     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11423       if (LI->getOperand(0) == V) return true;
11424     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
11425       if (SI->getOperand(1) == V) return true;
11426     }
11427
11428   }
11429   return false;
11430 }
11431
11432 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11433   Value *Op = LI.getOperand(0);
11434
11435   // Attempt to improve the alignment.
11436   unsigned KnownAlign =
11437     GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11438   if (KnownAlign >
11439       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11440                                 LI.getAlignment()))
11441     LI.setAlignment(KnownAlign);
11442
11443   // load (cast X) --> cast (load X) iff safe
11444   if (isa<CastInst>(Op))
11445     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11446       return Res;
11447
11448   // None of the following transforms are legal for volatile loads.
11449   if (LI.isVolatile()) return 0;
11450   
11451   // Do really simple store-to-load forwarding and load CSE, to catch cases
11452   // where there are several consequtive memory accesses to the same location,
11453   // separated by a few arithmetic operations.
11454   BasicBlock::iterator BBI = &LI;
11455   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11456     return ReplaceInstUsesWith(LI, AvailableVal);
11457
11458   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11459     const Value *GEPI0 = GEPI->getOperand(0);
11460     // TODO: Consider a target hook for valid address spaces for this xform.
11461     if (isa<ConstantPointerNull>(GEPI0) &&
11462         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11463       // Insert a new store to null instruction before the load to indicate
11464       // that this code is not reachable.  We do this instead of inserting
11465       // an unreachable instruction directly because we cannot modify the
11466       // CFG.
11467       new StoreInst(UndefValue::get(LI.getType()),
11468                     Constant::getNullValue(Op->getType()), &LI);
11469       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11470     }
11471   } 
11472
11473   if (Constant *C = dyn_cast<Constant>(Op)) {
11474     // load null/undef -> undef
11475     // TODO: Consider a target hook for valid address spaces for this xform.
11476     if (isa<UndefValue>(C) || (C->isNullValue() && 
11477         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11478       // Insert a new store to null instruction before the load to indicate that
11479       // this code is not reachable.  We do this instead of inserting an
11480       // unreachable instruction directly because we cannot modify the CFG.
11481       new StoreInst(UndefValue::get(LI.getType()),
11482                     Constant::getNullValue(Op->getType()), &LI);
11483       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11484     }
11485
11486     // Instcombine load (constant global) into the value loaded.
11487     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11488       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11489         return ReplaceInstUsesWith(LI, GV->getInitializer());
11490
11491     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11492     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11493       if (CE->getOpcode() == Instruction::GetElementPtr) {
11494         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11495           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11496             if (Constant *V = 
11497                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
11498               return ReplaceInstUsesWith(LI, V);
11499         if (CE->getOperand(0)->isNullValue()) {
11500           // Insert a new store to null instruction before the load to indicate
11501           // that this code is not reachable.  We do this instead of inserting
11502           // an unreachable instruction directly because we cannot modify the
11503           // CFG.
11504           new StoreInst(UndefValue::get(LI.getType()),
11505                         Constant::getNullValue(Op->getType()), &LI);
11506           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11507         }
11508
11509       } else if (CE->isCast()) {
11510         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11511           return Res;
11512       }
11513     }
11514   }
11515     
11516   // If this load comes from anywhere in a constant global, and if the global
11517   // is all undef or zero, we know what it loads.
11518   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11519     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11520       if (GV->getInitializer()->isNullValue())
11521         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11522       else if (isa<UndefValue>(GV->getInitializer()))
11523         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11524     }
11525   }
11526
11527   if (Op->hasOneUse()) {
11528     // Change select and PHI nodes to select values instead of addresses: this
11529     // helps alias analysis out a lot, allows many others simplifications, and
11530     // exposes redundancy in the code.
11531     //
11532     // Note that we cannot do the transformation unless we know that the
11533     // introduced loads cannot trap!  Something like this is valid as long as
11534     // the condition is always false: load (select bool %C, int* null, int* %G),
11535     // but it would not be valid if we transformed it to load from null
11536     // unconditionally.
11537     //
11538     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11539       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11540       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11541           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11542         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11543                                      SI->getOperand(1)->getName()+".val"), LI);
11544         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11545                                      SI->getOperand(2)->getName()+".val"), LI);
11546         return SelectInst::Create(SI->getCondition(), V1, V2);
11547       }
11548
11549       // load (select (cond, null, P)) -> load P
11550       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11551         if (C->isNullValue()) {
11552           LI.setOperand(0, SI->getOperand(2));
11553           return &LI;
11554         }
11555
11556       // load (select (cond, P, null)) -> load P
11557       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11558         if (C->isNullValue()) {
11559           LI.setOperand(0, SI->getOperand(1));
11560           return &LI;
11561         }
11562     }
11563   }
11564   return 0;
11565 }
11566
11567 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11568 /// when possible.  This makes it generally easy to do alias analysis and/or
11569 /// SROA/mem2reg of the memory object.
11570 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11571   User *CI = cast<User>(SI.getOperand(1));
11572   Value *CastOp = CI->getOperand(0);
11573
11574   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11575   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11576   if (SrcTy == 0) return 0;
11577   
11578   const Type *SrcPTy = SrcTy->getElementType();
11579
11580   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11581     return 0;
11582   
11583   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11584   /// to its first element.  This allows us to handle things like:
11585   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11586   /// on 32-bit hosts.
11587   SmallVector<Value*, 4> NewGEPIndices;
11588   
11589   // If the source is an array, the code below will not succeed.  Check to
11590   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11591   // constants.
11592   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11593     // Index through pointer.
11594     Constant *Zero = Constant::getNullValue(Type::Int32Ty);
11595     NewGEPIndices.push_back(Zero);
11596     
11597     while (1) {
11598       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11599         if (!STy->getNumElements()) /* Struct can be empty {} */
11600           break;
11601         NewGEPIndices.push_back(Zero);
11602         SrcPTy = STy->getElementType(0);
11603       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11604         NewGEPIndices.push_back(Zero);
11605         SrcPTy = ATy->getElementType();
11606       } else {
11607         break;
11608       }
11609     }
11610     
11611     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11612   }
11613
11614   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11615     return 0;
11616   
11617   // If the pointers point into different address spaces or if they point to
11618   // values with different sizes, we can't do the transformation.
11619   if (SrcTy->getAddressSpace() != 
11620         cast<PointerType>(CI->getType())->getAddressSpace() ||
11621       IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
11622       IC.getTargetData().getTypeSizeInBits(DestPTy))
11623     return 0;
11624
11625   // Okay, we are casting from one integer or pointer type to another of
11626   // the same size.  Instead of casting the pointer before 
11627   // the store, cast the value to be stored.
11628   Value *NewCast;
11629   Value *SIOp0 = SI.getOperand(0);
11630   Instruction::CastOps opcode = Instruction::BitCast;
11631   const Type* CastSrcTy = SIOp0->getType();
11632   const Type* CastDstTy = SrcPTy;
11633   if (isa<PointerType>(CastDstTy)) {
11634     if (CastSrcTy->isInteger())
11635       opcode = Instruction::IntToPtr;
11636   } else if (isa<IntegerType>(CastDstTy)) {
11637     if (isa<PointerType>(SIOp0->getType()))
11638       opcode = Instruction::PtrToInt;
11639   }
11640   
11641   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11642   // emit a GEP to index into its first field.
11643   if (!NewGEPIndices.empty()) {
11644     if (Constant *C = dyn_cast<Constant>(CastOp))
11645       CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0], 
11646                                               NewGEPIndices.size());
11647     else
11648       CastOp = IC.InsertNewInstBefore(
11649               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11650                                         NewGEPIndices.end()), SI);
11651   }
11652   
11653   if (Constant *C = dyn_cast<Constant>(SIOp0))
11654     NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11655   else
11656     NewCast = IC.InsertNewInstBefore(
11657       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11658       SI);
11659   return new StoreInst(NewCast, CastOp);
11660 }
11661
11662 /// equivalentAddressValues - Test if A and B will obviously have the same
11663 /// value. This includes recognizing that %t0 and %t1 will have the same
11664 /// value in code like this:
11665 ///   %t0 = getelementptr \@a, 0, 3
11666 ///   store i32 0, i32* %t0
11667 ///   %t1 = getelementptr \@a, 0, 3
11668 ///   %t2 = load i32* %t1
11669 ///
11670 static bool equivalentAddressValues(Value *A, Value *B) {
11671   // Test if the values are trivially equivalent.
11672   if (A == B) return true;
11673   
11674   // Test if the values come form identical arithmetic instructions.
11675   if (isa<BinaryOperator>(A) ||
11676       isa<CastInst>(A) ||
11677       isa<PHINode>(A) ||
11678       isa<GetElementPtrInst>(A))
11679     if (Instruction *BI = dyn_cast<Instruction>(B))
11680       if (cast<Instruction>(A)->isIdenticalTo(BI))
11681         return true;
11682   
11683   // Otherwise they may not be equivalent.
11684   return false;
11685 }
11686
11687 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11688 // return the llvm.dbg.declare.
11689 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11690   if (!V->hasNUses(2))
11691     return 0;
11692   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11693        UI != E; ++UI) {
11694     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11695       return DI;
11696     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11697       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11698         return DI;
11699       }
11700   }
11701   return 0;
11702 }
11703
11704 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11705   Value *Val = SI.getOperand(0);
11706   Value *Ptr = SI.getOperand(1);
11707
11708   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11709     EraseInstFromFunction(SI);
11710     ++NumCombined;
11711     return 0;
11712   }
11713   
11714   // If the RHS is an alloca with a single use, zapify the store, making the
11715   // alloca dead.
11716   // If the RHS is an alloca with a two uses, the other one being a 
11717   // llvm.dbg.declare, zapify the store and the declare, making the
11718   // alloca dead.  We must do this to prevent declare's from affecting
11719   // codegen.
11720   if (!SI.isVolatile()) {
11721     if (Ptr->hasOneUse()) {
11722       if (isa<AllocaInst>(Ptr)) {
11723         EraseInstFromFunction(SI);
11724         ++NumCombined;
11725         return 0;
11726       }
11727       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11728         if (isa<AllocaInst>(GEP->getOperand(0))) {
11729           if (GEP->getOperand(0)->hasOneUse()) {
11730             EraseInstFromFunction(SI);
11731             ++NumCombined;
11732             return 0;
11733           }
11734           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11735             EraseInstFromFunction(*DI);
11736             EraseInstFromFunction(SI);
11737             ++NumCombined;
11738             return 0;
11739           }
11740         }
11741       }
11742     }
11743     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11744       EraseInstFromFunction(*DI);
11745       EraseInstFromFunction(SI);
11746       ++NumCombined;
11747       return 0;
11748     }
11749   }
11750
11751   // Attempt to improve the alignment.
11752   unsigned KnownAlign =
11753     GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11754   if (KnownAlign >
11755       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11756                                 SI.getAlignment()))
11757     SI.setAlignment(KnownAlign);
11758
11759   // Do really simple DSE, to catch cases where there are several consecutive
11760   // stores to the same location, separated by a few arithmetic operations. This
11761   // situation often occurs with bitfield accesses.
11762   BasicBlock::iterator BBI = &SI;
11763   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11764        --ScanInsts) {
11765     --BBI;
11766     // Don't count debug info directives, lest they affect codegen,
11767     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11768     // It is necessary for correctness to skip those that feed into a
11769     // llvm.dbg.declare, as these are not present when debugging is off.
11770     if (isa<DbgInfoIntrinsic>(BBI) ||
11771         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11772       ScanInsts++;
11773       continue;
11774     }    
11775     
11776     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11777       // Prev store isn't volatile, and stores to the same location?
11778       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11779                                                           SI.getOperand(1))) {
11780         ++NumDeadStore;
11781         ++BBI;
11782         EraseInstFromFunction(*PrevSI);
11783         continue;
11784       }
11785       break;
11786     }
11787     
11788     // If this is a load, we have to stop.  However, if the loaded value is from
11789     // the pointer we're loading and is producing the pointer we're storing,
11790     // then *this* store is dead (X = load P; store X -> P).
11791     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11792       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11793           !SI.isVolatile()) {
11794         EraseInstFromFunction(SI);
11795         ++NumCombined;
11796         return 0;
11797       }
11798       // Otherwise, this is a load from some other location.  Stores before it
11799       // may not be dead.
11800       break;
11801     }
11802     
11803     // Don't skip over loads or things that can modify memory.
11804     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11805       break;
11806   }
11807   
11808   
11809   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11810
11811   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11812   if (isa<ConstantPointerNull>(Ptr) &&
11813       cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11814     if (!isa<UndefValue>(Val)) {
11815       SI.setOperand(0, UndefValue::get(Val->getType()));
11816       if (Instruction *U = dyn_cast<Instruction>(Val))
11817         AddToWorkList(U);  // Dropped a use.
11818       ++NumCombined;
11819     }
11820     return 0;  // Do not modify these!
11821   }
11822
11823   // store undef, Ptr -> noop
11824   if (isa<UndefValue>(Val)) {
11825     EraseInstFromFunction(SI);
11826     ++NumCombined;
11827     return 0;
11828   }
11829
11830   // If the pointer destination is a cast, see if we can fold the cast into the
11831   // source instead.
11832   if (isa<CastInst>(Ptr))
11833     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11834       return Res;
11835   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11836     if (CE->isCast())
11837       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11838         return Res;
11839
11840   
11841   // If this store is the last instruction in the basic block (possibly
11842   // excepting debug info instructions and the pointer bitcasts that feed
11843   // into them), and if the block ends with an unconditional branch, try
11844   // to move it to the successor block.
11845   BBI = &SI; 
11846   do {
11847     ++BBI;
11848   } while (isa<DbgInfoIntrinsic>(BBI) ||
11849            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11850   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11851     if (BI->isUnconditional())
11852       if (SimplifyStoreAtEndOfBlock(SI))
11853         return 0;  // xform done!
11854   
11855   return 0;
11856 }
11857
11858 /// SimplifyStoreAtEndOfBlock - Turn things like:
11859 ///   if () { *P = v1; } else { *P = v2 }
11860 /// into a phi node with a store in the successor.
11861 ///
11862 /// Simplify things like:
11863 ///   *P = v1; if () { *P = v2; }
11864 /// into a phi node with a store in the successor.
11865 ///
11866 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11867   BasicBlock *StoreBB = SI.getParent();
11868   
11869   // Check to see if the successor block has exactly two incoming edges.  If
11870   // so, see if the other predecessor contains a store to the same location.
11871   // if so, insert a PHI node (if needed) and move the stores down.
11872   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11873   
11874   // Determine whether Dest has exactly two predecessors and, if so, compute
11875   // the other predecessor.
11876   pred_iterator PI = pred_begin(DestBB);
11877   BasicBlock *OtherBB = 0;
11878   if (*PI != StoreBB)
11879     OtherBB = *PI;
11880   ++PI;
11881   if (PI == pred_end(DestBB))
11882     return false;
11883   
11884   if (*PI != StoreBB) {
11885     if (OtherBB)
11886       return false;
11887     OtherBB = *PI;
11888   }
11889   if (++PI != pred_end(DestBB))
11890     return false;
11891
11892   // Bail out if all the relevant blocks aren't distinct (this can happen,
11893   // for example, if SI is in an infinite loop)
11894   if (StoreBB == DestBB || OtherBB == DestBB)
11895     return false;
11896
11897   // Verify that the other block ends in a branch and is not otherwise empty.
11898   BasicBlock::iterator BBI = OtherBB->getTerminator();
11899   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11900   if (!OtherBr || BBI == OtherBB->begin())
11901     return false;
11902   
11903   // If the other block ends in an unconditional branch, check for the 'if then
11904   // else' case.  there is an instruction before the branch.
11905   StoreInst *OtherStore = 0;
11906   if (OtherBr->isUnconditional()) {
11907     --BBI;
11908     // Skip over debugging info.
11909     while (isa<DbgInfoIntrinsic>(BBI) ||
11910            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11911       if (BBI==OtherBB->begin())
11912         return false;
11913       --BBI;
11914     }
11915     // If this isn't a store, or isn't a store to the same location, bail out.
11916     OtherStore = dyn_cast<StoreInst>(BBI);
11917     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11918       return false;
11919   } else {
11920     // Otherwise, the other block ended with a conditional branch. If one of the
11921     // destinations is StoreBB, then we have the if/then case.
11922     if (OtherBr->getSuccessor(0) != StoreBB && 
11923         OtherBr->getSuccessor(1) != StoreBB)
11924       return false;
11925     
11926     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11927     // if/then triangle.  See if there is a store to the same ptr as SI that
11928     // lives in OtherBB.
11929     for (;; --BBI) {
11930       // Check to see if we find the matching store.
11931       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11932         if (OtherStore->getOperand(1) != SI.getOperand(1))
11933           return false;
11934         break;
11935       }
11936       // If we find something that may be using or overwriting the stored
11937       // value, or if we run out of instructions, we can't do the xform.
11938       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11939           BBI == OtherBB->begin())
11940         return false;
11941     }
11942     
11943     // In order to eliminate the store in OtherBr, we have to
11944     // make sure nothing reads or overwrites the stored value in
11945     // StoreBB.
11946     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11947       // FIXME: This should really be AA driven.
11948       if (I->mayReadFromMemory() || I->mayWriteToMemory())
11949         return false;
11950     }
11951   }
11952   
11953   // Insert a PHI node now if we need it.
11954   Value *MergedVal = OtherStore->getOperand(0);
11955   if (MergedVal != SI.getOperand(0)) {
11956     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11957     PN->reserveOperandSpace(2);
11958     PN->addIncoming(SI.getOperand(0), SI.getParent());
11959     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11960     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11961   }
11962   
11963   // Advance to a place where it is safe to insert the new store and
11964   // insert it.
11965   BBI = DestBB->getFirstNonPHI();
11966   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11967                                     OtherStore->isVolatile()), *BBI);
11968   
11969   // Nuke the old stores.
11970   EraseInstFromFunction(SI);
11971   EraseInstFromFunction(*OtherStore);
11972   ++NumCombined;
11973   return true;
11974 }
11975
11976
11977 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11978   // Change br (not X), label True, label False to: br X, label False, True
11979   Value *X = 0;
11980   BasicBlock *TrueDest;
11981   BasicBlock *FalseDest;
11982   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11983       !isa<Constant>(X)) {
11984     // Swap Destinations and condition...
11985     BI.setCondition(X);
11986     BI.setSuccessor(0, FalseDest);
11987     BI.setSuccessor(1, TrueDest);
11988     return &BI;
11989   }
11990
11991   // Cannonicalize fcmp_one -> fcmp_oeq
11992   FCmpInst::Predicate FPred; Value *Y;
11993   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
11994                              TrueDest, FalseDest)))
11995     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11996          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11997       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
11998       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
11999       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
12000       NewSCC->takeName(I);
12001       // Swap Destinations and condition...
12002       BI.setCondition(NewSCC);
12003       BI.setSuccessor(0, FalseDest);
12004       BI.setSuccessor(1, TrueDest);
12005       RemoveFromWorkList(I);
12006       I->eraseFromParent();
12007       AddToWorkList(NewSCC);
12008       return &BI;
12009     }
12010
12011   // Cannonicalize icmp_ne -> icmp_eq
12012   ICmpInst::Predicate IPred;
12013   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12014                       TrueDest, FalseDest)))
12015     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12016          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12017          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12018       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12019       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
12020       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
12021       NewSCC->takeName(I);
12022       // Swap Destinations and condition...
12023       BI.setCondition(NewSCC);
12024       BI.setSuccessor(0, FalseDest);
12025       BI.setSuccessor(1, TrueDest);
12026       RemoveFromWorkList(I);
12027       I->eraseFromParent();;
12028       AddToWorkList(NewSCC);
12029       return &BI;
12030     }
12031
12032   return 0;
12033 }
12034
12035 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12036   Value *Cond = SI.getCondition();
12037   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12038     if (I->getOpcode() == Instruction::Add)
12039       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12040         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12041         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12042           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
12043                                                 AddRHS));
12044         SI.setOperand(0, I->getOperand(0));
12045         AddToWorkList(I);
12046         return &SI;
12047       }
12048   }
12049   return 0;
12050 }
12051
12052 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12053   Value *Agg = EV.getAggregateOperand();
12054
12055   if (!EV.hasIndices())
12056     return ReplaceInstUsesWith(EV, Agg);
12057
12058   if (Constant *C = dyn_cast<Constant>(Agg)) {
12059     if (isa<UndefValue>(C))
12060       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12061       
12062     if (isa<ConstantAggregateZero>(C))
12063       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12064
12065     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12066       // Extract the element indexed by the first index out of the constant
12067       Value *V = C->getOperand(*EV.idx_begin());
12068       if (EV.getNumIndices() > 1)
12069         // Extract the remaining indices out of the constant indexed by the
12070         // first index
12071         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12072       else
12073         return ReplaceInstUsesWith(EV, V);
12074     }
12075     return 0; // Can't handle other constants
12076   } 
12077   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12078     // We're extracting from an insertvalue instruction, compare the indices
12079     const unsigned *exti, *exte, *insi, *inse;
12080     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12081          exte = EV.idx_end(), inse = IV->idx_end();
12082          exti != exte && insi != inse;
12083          ++exti, ++insi) {
12084       if (*insi != *exti)
12085         // The insert and extract both reference distinctly different elements.
12086         // This means the extract is not influenced by the insert, and we can
12087         // replace the aggregate operand of the extract with the aggregate
12088         // operand of the insert. i.e., replace
12089         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12090         // %E = extractvalue { i32, { i32 } } %I, 0
12091         // with
12092         // %E = extractvalue { i32, { i32 } } %A, 0
12093         return ExtractValueInst::Create(IV->getAggregateOperand(),
12094                                         EV.idx_begin(), EV.idx_end());
12095     }
12096     if (exti == exte && insi == inse)
12097       // Both iterators are at the end: Index lists are identical. Replace
12098       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12099       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12100       // with "i32 42"
12101       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12102     if (exti == exte) {
12103       // The extract list is a prefix of the insert list. i.e. replace
12104       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12105       // %E = extractvalue { i32, { i32 } } %I, 1
12106       // with
12107       // %X = extractvalue { i32, { i32 } } %A, 1
12108       // %E = insertvalue { i32 } %X, i32 42, 0
12109       // by switching the order of the insert and extract (though the
12110       // insertvalue should be left in, since it may have other uses).
12111       Value *NewEV = InsertNewInstBefore(
12112         ExtractValueInst::Create(IV->getAggregateOperand(),
12113                                  EV.idx_begin(), EV.idx_end()),
12114         EV);
12115       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12116                                      insi, inse);
12117     }
12118     if (insi == inse)
12119       // The insert list is a prefix of the extract list
12120       // We can simply remove the common indices from the extract and make it
12121       // operate on the inserted value instead of the insertvalue result.
12122       // i.e., replace
12123       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12124       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12125       // with
12126       // %E extractvalue { i32 } { i32 42 }, 0
12127       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12128                                       exti, exte);
12129   }
12130   // Can't simplify extracts from other values. Note that nested extracts are
12131   // already simplified implicitely by the above (extract ( extract (insert) )
12132   // will be translated into extract ( insert ( extract ) ) first and then just
12133   // the value inserted, if appropriate).
12134   return 0;
12135 }
12136
12137 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12138 /// is to leave as a vector operation.
12139 static bool CheapToScalarize(Value *V, bool isConstant) {
12140   if (isa<ConstantAggregateZero>(V)) 
12141     return true;
12142   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12143     if (isConstant) return true;
12144     // If all elts are the same, we can extract.
12145     Constant *Op0 = C->getOperand(0);
12146     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12147       if (C->getOperand(i) != Op0)
12148         return false;
12149     return true;
12150   }
12151   Instruction *I = dyn_cast<Instruction>(V);
12152   if (!I) return false;
12153   
12154   // Insert element gets simplified to the inserted element or is deleted if
12155   // this is constant idx extract element and its a constant idx insertelt.
12156   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12157       isa<ConstantInt>(I->getOperand(2)))
12158     return true;
12159   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12160     return true;
12161   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12162     if (BO->hasOneUse() &&
12163         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12164          CheapToScalarize(BO->getOperand(1), isConstant)))
12165       return true;
12166   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12167     if (CI->hasOneUse() &&
12168         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12169          CheapToScalarize(CI->getOperand(1), isConstant)))
12170       return true;
12171   
12172   return false;
12173 }
12174
12175 /// Read and decode a shufflevector mask.
12176 ///
12177 /// It turns undef elements into values that are larger than the number of
12178 /// elements in the input.
12179 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12180   unsigned NElts = SVI->getType()->getNumElements();
12181   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12182     return std::vector<unsigned>(NElts, 0);
12183   if (isa<UndefValue>(SVI->getOperand(2)))
12184     return std::vector<unsigned>(NElts, 2*NElts);
12185
12186   std::vector<unsigned> Result;
12187   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12188   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12189     if (isa<UndefValue>(*i))
12190       Result.push_back(NElts*2);  // undef -> 8
12191     else
12192       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12193   return Result;
12194 }
12195
12196 /// FindScalarElement - Given a vector and an element number, see if the scalar
12197 /// value is already around as a register, for example if it were inserted then
12198 /// extracted from the vector.
12199 static Value *FindScalarElement(Value *V, unsigned EltNo) {
12200   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12201   const VectorType *PTy = cast<VectorType>(V->getType());
12202   unsigned Width = PTy->getNumElements();
12203   if (EltNo >= Width)  // Out of range access.
12204     return UndefValue::get(PTy->getElementType());
12205   
12206   if (isa<UndefValue>(V))
12207     return UndefValue::get(PTy->getElementType());
12208   else if (isa<ConstantAggregateZero>(V))
12209     return Constant::getNullValue(PTy->getElementType());
12210   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12211     return CP->getOperand(EltNo);
12212   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12213     // If this is an insert to a variable element, we don't know what it is.
12214     if (!isa<ConstantInt>(III->getOperand(2))) 
12215       return 0;
12216     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12217     
12218     // If this is an insert to the element we are looking for, return the
12219     // inserted value.
12220     if (EltNo == IIElt) 
12221       return III->getOperand(1);
12222     
12223     // Otherwise, the insertelement doesn't modify the value, recurse on its
12224     // vector input.
12225     return FindScalarElement(III->getOperand(0), EltNo);
12226   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12227     unsigned LHSWidth =
12228       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12229     unsigned InEl = getShuffleMask(SVI)[EltNo];
12230     if (InEl < LHSWidth)
12231       return FindScalarElement(SVI->getOperand(0), InEl);
12232     else if (InEl < LHSWidth*2)
12233       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
12234     else
12235       return UndefValue::get(PTy->getElementType());
12236   }
12237   
12238   // Otherwise, we don't know.
12239   return 0;
12240 }
12241
12242 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12243   // If vector val is undef, replace extract with scalar undef.
12244   if (isa<UndefValue>(EI.getOperand(0)))
12245     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12246
12247   // If vector val is constant 0, replace extract with scalar 0.
12248   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12249     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12250   
12251   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12252     // If vector val is constant with all elements the same, replace EI with
12253     // that element. When the elements are not identical, we cannot replace yet
12254     // (we do that below, but only when the index is constant).
12255     Constant *op0 = C->getOperand(0);
12256     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12257       if (C->getOperand(i) != op0) {
12258         op0 = 0; 
12259         break;
12260       }
12261     if (op0)
12262       return ReplaceInstUsesWith(EI, op0);
12263   }
12264   
12265   // If extracting a specified index from the vector, see if we can recursively
12266   // find a previously computed scalar that was inserted into the vector.
12267   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12268     unsigned IndexVal = IdxC->getZExtValue();
12269     unsigned VectorWidth = 
12270       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12271       
12272     // If this is extracting an invalid index, turn this into undef, to avoid
12273     // crashing the code below.
12274     if (IndexVal >= VectorWidth)
12275       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12276     
12277     // This instruction only demands the single element from the input vector.
12278     // If the input vector has a single use, simplify it based on this use
12279     // property.
12280     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12281       APInt UndefElts(VectorWidth, 0);
12282       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12283       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12284                                                 DemandedMask, UndefElts)) {
12285         EI.setOperand(0, V);
12286         return &EI;
12287       }
12288     }
12289     
12290     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
12291       return ReplaceInstUsesWith(EI, Elt);
12292     
12293     // If the this extractelement is directly using a bitcast from a vector of
12294     // the same number of elements, see if we can find the source element from
12295     // it.  In this case, we will end up needing to bitcast the scalars.
12296     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12297       if (const VectorType *VT = 
12298               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12299         if (VT->getNumElements() == VectorWidth)
12300           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
12301             return new BitCastInst(Elt, EI.getType());
12302     }
12303   }
12304   
12305   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12306     if (I->hasOneUse()) {
12307       // Push extractelement into predecessor operation if legal and
12308       // profitable to do so
12309       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12310         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12311         if (CheapToScalarize(BO, isConstantElt)) {
12312           ExtractElementInst *newEI0 = 
12313             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12314                                    EI.getName()+".lhs");
12315           ExtractElementInst *newEI1 =
12316             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12317                                    EI.getName()+".rhs");
12318           InsertNewInstBefore(newEI0, EI);
12319           InsertNewInstBefore(newEI1, EI);
12320           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12321         }
12322       } else if (isa<LoadInst>(I)) {
12323         unsigned AS = 
12324           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12325         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12326                                          PointerType::get(EI.getType(), AS),EI);
12327         GetElementPtrInst *GEP =
12328           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12329         InsertNewInstBefore(GEP, EI);
12330         return new LoadInst(GEP);
12331       }
12332     }
12333     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12334       // Extracting the inserted element?
12335       if (IE->getOperand(2) == EI.getOperand(1))
12336         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12337       // If the inserted and extracted elements are constants, they must not
12338       // be the same value, extract from the pre-inserted value instead.
12339       if (isa<Constant>(IE->getOperand(2)) &&
12340           isa<Constant>(EI.getOperand(1))) {
12341         AddUsesToWorkList(EI);
12342         EI.setOperand(0, IE->getOperand(0));
12343         return &EI;
12344       }
12345     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12346       // If this is extracting an element from a shufflevector, figure out where
12347       // it came from and extract from the appropriate input element instead.
12348       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12349         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12350         Value *Src;
12351         unsigned LHSWidth =
12352           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12353
12354         if (SrcIdx < LHSWidth)
12355           Src = SVI->getOperand(0);
12356         else if (SrcIdx < LHSWidth*2) {
12357           SrcIdx -= LHSWidth;
12358           Src = SVI->getOperand(1);
12359         } else {
12360           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12361         }
12362         return new ExtractElementInst(Src, SrcIdx);
12363       }
12364     }
12365   }
12366   return 0;
12367 }
12368
12369 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12370 /// elements from either LHS or RHS, return the shuffle mask and true. 
12371 /// Otherwise, return false.
12372 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12373                                          std::vector<Constant*> &Mask) {
12374   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12375          "Invalid CollectSingleShuffleElements");
12376   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12377
12378   if (isa<UndefValue>(V)) {
12379     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12380     return true;
12381   } else if (V == LHS) {
12382     for (unsigned i = 0; i != NumElts; ++i)
12383       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12384     return true;
12385   } else if (V == RHS) {
12386     for (unsigned i = 0; i != NumElts; ++i)
12387       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
12388     return true;
12389   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12390     // If this is an insert of an extract from some other vector, include it.
12391     Value *VecOp    = IEI->getOperand(0);
12392     Value *ScalarOp = IEI->getOperand(1);
12393     Value *IdxOp    = IEI->getOperand(2);
12394     
12395     if (!isa<ConstantInt>(IdxOp))
12396       return false;
12397     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12398     
12399     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12400       // Okay, we can handle this if the vector we are insertinting into is
12401       // transitively ok.
12402       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12403         // If so, update the mask to reflect the inserted undef.
12404         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
12405         return true;
12406       }      
12407     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12408       if (isa<ConstantInt>(EI->getOperand(1)) &&
12409           EI->getOperand(0)->getType() == V->getType()) {
12410         unsigned ExtractedIdx =
12411           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12412         
12413         // This must be extracting from either LHS or RHS.
12414         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12415           // Okay, we can handle this if the vector we are insertinting into is
12416           // transitively ok.
12417           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12418             // If so, update the mask to reflect the inserted value.
12419             if (EI->getOperand(0) == LHS) {
12420               Mask[InsertedIdx % NumElts] = 
12421                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12422             } else {
12423               assert(EI->getOperand(0) == RHS);
12424               Mask[InsertedIdx % NumElts] = 
12425                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
12426               
12427             }
12428             return true;
12429           }
12430         }
12431       }
12432     }
12433   }
12434   // TODO: Handle shufflevector here!
12435   
12436   return false;
12437 }
12438
12439 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12440 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12441 /// that computes V and the LHS value of the shuffle.
12442 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12443                                      Value *&RHS) {
12444   assert(isa<VectorType>(V->getType()) && 
12445          (RHS == 0 || V->getType() == RHS->getType()) &&
12446          "Invalid shuffle!");
12447   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12448
12449   if (isa<UndefValue>(V)) {
12450     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12451     return V;
12452   } else if (isa<ConstantAggregateZero>(V)) {
12453     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
12454     return V;
12455   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12456     // If this is an insert of an extract from some other vector, include it.
12457     Value *VecOp    = IEI->getOperand(0);
12458     Value *ScalarOp = IEI->getOperand(1);
12459     Value *IdxOp    = IEI->getOperand(2);
12460     
12461     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12462       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12463           EI->getOperand(0)->getType() == V->getType()) {
12464         unsigned ExtractedIdx =
12465           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12466         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12467         
12468         // Either the extracted from or inserted into vector must be RHSVec,
12469         // otherwise we'd end up with a shuffle of three inputs.
12470         if (EI->getOperand(0) == RHS || RHS == 0) {
12471           RHS = EI->getOperand(0);
12472           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
12473           Mask[InsertedIdx % NumElts] = 
12474             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
12475           return V;
12476         }
12477         
12478         if (VecOp == RHS) {
12479           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
12480           // Everything but the extracted element is replaced with the RHS.
12481           for (unsigned i = 0; i != NumElts; ++i) {
12482             if (i != InsertedIdx)
12483               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
12484           }
12485           return V;
12486         }
12487         
12488         // If this insertelement is a chain that comes from exactly these two
12489         // vectors, return the vector and the effective shuffle.
12490         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
12491           return EI->getOperand(0);
12492         
12493       }
12494     }
12495   }
12496   // TODO: Handle shufflevector here!
12497   
12498   // Otherwise, can't do anything fancy.  Return an identity vector.
12499   for (unsigned i = 0; i != NumElts; ++i)
12500     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12501   return V;
12502 }
12503
12504 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12505   Value *VecOp    = IE.getOperand(0);
12506   Value *ScalarOp = IE.getOperand(1);
12507   Value *IdxOp    = IE.getOperand(2);
12508   
12509   // Inserting an undef or into an undefined place, remove this.
12510   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12511     ReplaceInstUsesWith(IE, VecOp);
12512   
12513   // If the inserted element was extracted from some other vector, and if the 
12514   // indexes are constant, try to turn this into a shufflevector operation.
12515   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12516     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12517         EI->getOperand(0)->getType() == IE.getType()) {
12518       unsigned NumVectorElts = IE.getType()->getNumElements();
12519       unsigned ExtractedIdx =
12520         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12521       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12522       
12523       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12524         return ReplaceInstUsesWith(IE, VecOp);
12525       
12526       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12527         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12528       
12529       // If we are extracting a value from a vector, then inserting it right
12530       // back into the same place, just use the input vector.
12531       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12532         return ReplaceInstUsesWith(IE, VecOp);      
12533       
12534       // We could theoretically do this for ANY input.  However, doing so could
12535       // turn chains of insertelement instructions into a chain of shufflevector
12536       // instructions, and right now we do not merge shufflevectors.  As such,
12537       // only do this in a situation where it is clear that there is benefit.
12538       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12539         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12540         // the values of VecOp, except then one read from EIOp0.
12541         // Build a new shuffle mask.
12542         std::vector<Constant*> Mask;
12543         if (isa<UndefValue>(VecOp))
12544           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
12545         else {
12546           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12547           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
12548                                                        NumVectorElts));
12549         } 
12550         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12551         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12552                                      ConstantVector::get(Mask));
12553       }
12554       
12555       // If this insertelement isn't used by some other insertelement, turn it
12556       // (and any insertelements it points to), into one big shuffle.
12557       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12558         std::vector<Constant*> Mask;
12559         Value *RHS = 0;
12560         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12561         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12562         // We now have a shuffle of LHS, RHS, Mask.
12563         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
12564       }
12565     }
12566   }
12567
12568   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12569   APInt UndefElts(VWidth, 0);
12570   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12571   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12572     return &IE;
12573
12574   return 0;
12575 }
12576
12577
12578 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12579   Value *LHS = SVI.getOperand(0);
12580   Value *RHS = SVI.getOperand(1);
12581   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12582
12583   bool MadeChange = false;
12584
12585   // Undefined shuffle mask -> undefined value.
12586   if (isa<UndefValue>(SVI.getOperand(2)))
12587     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12588
12589   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12590
12591   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12592     return 0;
12593
12594   APInt UndefElts(VWidth, 0);
12595   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12596   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12597     LHS = SVI.getOperand(0);
12598     RHS = SVI.getOperand(1);
12599     MadeChange = true;
12600   }
12601   
12602   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12603   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12604   if (LHS == RHS || isa<UndefValue>(LHS)) {
12605     if (isa<UndefValue>(LHS) && LHS == RHS) {
12606       // shuffle(undef,undef,mask) -> undef.
12607       return ReplaceInstUsesWith(SVI, LHS);
12608     }
12609     
12610     // Remap any references to RHS to use LHS.
12611     std::vector<Constant*> Elts;
12612     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12613       if (Mask[i] >= 2*e)
12614         Elts.push_back(UndefValue::get(Type::Int32Ty));
12615       else {
12616         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12617             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12618           Mask[i] = 2*e;     // Turn into undef.
12619           Elts.push_back(UndefValue::get(Type::Int32Ty));
12620         } else {
12621           Mask[i] = Mask[i] % e;  // Force to LHS.
12622           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12623         }
12624       }
12625     }
12626     SVI.setOperand(0, SVI.getOperand(1));
12627     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12628     SVI.setOperand(2, ConstantVector::get(Elts));
12629     LHS = SVI.getOperand(0);
12630     RHS = SVI.getOperand(1);
12631     MadeChange = true;
12632   }
12633   
12634   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12635   bool isLHSID = true, isRHSID = true;
12636     
12637   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12638     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12639     // Is this an identity shuffle of the LHS value?
12640     isLHSID &= (Mask[i] == i);
12641       
12642     // Is this an identity shuffle of the RHS value?
12643     isRHSID &= (Mask[i]-e == i);
12644   }
12645
12646   // Eliminate identity shuffles.
12647   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12648   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12649   
12650   // If the LHS is a shufflevector itself, see if we can combine it with this
12651   // one without producing an unusual shuffle.  Here we are really conservative:
12652   // we are absolutely afraid of producing a shuffle mask not in the input
12653   // program, because the code gen may not be smart enough to turn a merged
12654   // shuffle into two specific shuffles: it may produce worse code.  As such,
12655   // we only merge two shuffles if the result is one of the two input shuffle
12656   // masks.  In this case, merging the shuffles just removes one instruction,
12657   // which we know is safe.  This is good for things like turning:
12658   // (splat(splat)) -> splat.
12659   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12660     if (isa<UndefValue>(RHS)) {
12661       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12662
12663       std::vector<unsigned> NewMask;
12664       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12665         if (Mask[i] >= 2*e)
12666           NewMask.push_back(2*e);
12667         else
12668           NewMask.push_back(LHSMask[Mask[i]]);
12669       
12670       // If the result mask is equal to the src shuffle or this shuffle mask, do
12671       // the replacement.
12672       if (NewMask == LHSMask || NewMask == Mask) {
12673         unsigned LHSInNElts =
12674           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12675         std::vector<Constant*> Elts;
12676         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12677           if (NewMask[i] >= LHSInNElts*2) {
12678             Elts.push_back(UndefValue::get(Type::Int32Ty));
12679           } else {
12680             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
12681           }
12682         }
12683         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12684                                      LHSSVI->getOperand(1),
12685                                      ConstantVector::get(Elts));
12686       }
12687     }
12688   }
12689
12690   return MadeChange ? &SVI : 0;
12691 }
12692
12693
12694
12695
12696 /// TryToSinkInstruction - Try to move the specified instruction from its
12697 /// current block into the beginning of DestBlock, which can only happen if it's
12698 /// safe to move the instruction past all of the instructions between it and the
12699 /// end of its block.
12700 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12701   assert(I->hasOneUse() && "Invariants didn't hold!");
12702
12703   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12704   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12705     return false;
12706
12707   // Do not sink alloca instructions out of the entry block.
12708   if (isa<AllocaInst>(I) && I->getParent() ==
12709         &DestBlock->getParent()->getEntryBlock())
12710     return false;
12711
12712   // We can only sink load instructions if there is nothing between the load and
12713   // the end of block that could change the value.
12714   if (I->mayReadFromMemory()) {
12715     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12716          Scan != E; ++Scan)
12717       if (Scan->mayWriteToMemory())
12718         return false;
12719   }
12720
12721   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12722
12723   CopyPrecedingStopPoint(I, InsertPos);
12724   I->moveBefore(InsertPos);
12725   ++NumSunkInst;
12726   return true;
12727 }
12728
12729
12730 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12731 /// all reachable code to the worklist.
12732 ///
12733 /// This has a couple of tricks to make the code faster and more powerful.  In
12734 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12735 /// them to the worklist (this significantly speeds up instcombine on code where
12736 /// many instructions are dead or constant).  Additionally, if we find a branch
12737 /// whose condition is a known constant, we only visit the reachable successors.
12738 ///
12739 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12740                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12741                                        InstCombiner &IC,
12742                                        const TargetData *TD) {
12743   SmallVector<BasicBlock*, 256> Worklist;
12744   Worklist.push_back(BB);
12745
12746   while (!Worklist.empty()) {
12747     BB = Worklist.back();
12748     Worklist.pop_back();
12749     
12750     // We have now visited this block!  If we've already been here, ignore it.
12751     if (!Visited.insert(BB)) continue;
12752
12753     DbgInfoIntrinsic *DBI_Prev = NULL;
12754     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12755       Instruction *Inst = BBI++;
12756       
12757       // DCE instruction if trivially dead.
12758       if (isInstructionTriviallyDead(Inst)) {
12759         ++NumDeadInst;
12760         DOUT << "IC: DCE: " << *Inst;
12761         Inst->eraseFromParent();
12762         continue;
12763       }
12764       
12765       // ConstantProp instruction if trivially constant.
12766       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12767         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12768         Inst->replaceAllUsesWith(C);
12769         ++NumConstProp;
12770         Inst->eraseFromParent();
12771         continue;
12772       }
12773      
12774       // If there are two consecutive llvm.dbg.stoppoint calls then
12775       // it is likely that the optimizer deleted code in between these
12776       // two intrinsics. 
12777       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12778       if (DBI_Next) {
12779         if (DBI_Prev
12780             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12781             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12782           IC.RemoveFromWorkList(DBI_Prev);
12783           DBI_Prev->eraseFromParent();
12784         }
12785         DBI_Prev = DBI_Next;
12786       } else {
12787         DBI_Prev = 0;
12788       }
12789
12790       IC.AddToWorkList(Inst);
12791     }
12792
12793     // Recursively visit successors.  If this is a branch or switch on a
12794     // constant, only visit the reachable successor.
12795     TerminatorInst *TI = BB->getTerminator();
12796     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12797       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12798         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12799         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12800         Worklist.push_back(ReachableBB);
12801         continue;
12802       }
12803     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12804       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12805         // See if this is an explicit destination.
12806         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12807           if (SI->getCaseValue(i) == Cond) {
12808             BasicBlock *ReachableBB = SI->getSuccessor(i);
12809             Worklist.push_back(ReachableBB);
12810             continue;
12811           }
12812         
12813         // Otherwise it is the default destination.
12814         Worklist.push_back(SI->getSuccessor(0));
12815         continue;
12816       }
12817     }
12818     
12819     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12820       Worklist.push_back(TI->getSuccessor(i));
12821   }
12822 }
12823
12824 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12825   bool Changed = false;
12826   TD = &getAnalysis<TargetData>();
12827   
12828   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12829              << F.getNameStr() << "\n");
12830
12831   {
12832     // Do a depth-first traversal of the function, populate the worklist with
12833     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12834     // track of which blocks we visit.
12835     SmallPtrSet<BasicBlock*, 64> Visited;
12836     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12837
12838     // Do a quick scan over the function.  If we find any blocks that are
12839     // unreachable, remove any instructions inside of them.  This prevents
12840     // the instcombine code from having to deal with some bad special cases.
12841     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12842       if (!Visited.count(BB)) {
12843         Instruction *Term = BB->getTerminator();
12844         while (Term != BB->begin()) {   // Remove instrs bottom-up
12845           BasicBlock::iterator I = Term; --I;
12846
12847           DOUT << "IC: DCE: " << *I;
12848           // A debug intrinsic shouldn't force another iteration if we weren't
12849           // going to do one without it.
12850           if (!isa<DbgInfoIntrinsic>(I)) {
12851             ++NumDeadInst;
12852             Changed = true;
12853           }
12854           if (!I->use_empty())
12855             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12856           I->eraseFromParent();
12857         }
12858       }
12859   }
12860
12861   while (!Worklist.empty()) {
12862     Instruction *I = RemoveOneFromWorkList();
12863     if (I == 0) continue;  // skip null values.
12864
12865     // Check to see if we can DCE the instruction.
12866     if (isInstructionTriviallyDead(I)) {
12867       // Add operands to the worklist.
12868       if (I->getNumOperands() < 4)
12869         AddUsesToWorkList(*I);
12870       ++NumDeadInst;
12871
12872       DOUT << "IC: DCE: " << *I;
12873
12874       I->eraseFromParent();
12875       RemoveFromWorkList(I);
12876       Changed = true;
12877       continue;
12878     }
12879
12880     // Instruction isn't dead, see if we can constant propagate it.
12881     if (Constant *C = ConstantFoldInstruction(I, TD)) {
12882       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12883
12884       // Add operands to the worklist.
12885       AddUsesToWorkList(*I);
12886       ReplaceInstUsesWith(*I, C);
12887
12888       ++NumConstProp;
12889       I->eraseFromParent();
12890       RemoveFromWorkList(I);
12891       Changed = true;
12892       continue;
12893     }
12894
12895     if (TD &&
12896         (I->getType()->getTypeID() == Type::VoidTyID ||
12897          I->isTrapping())) {
12898       // See if we can constant fold its operands.
12899       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12900         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
12901           if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
12902             if (NewC != CE) {
12903               i->set(NewC);
12904               Changed = true;
12905             }
12906     }
12907
12908     // See if we can trivially sink this instruction to a successor basic block.
12909     if (I->hasOneUse()) {
12910       BasicBlock *BB = I->getParent();
12911       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12912       if (UserParent != BB) {
12913         bool UserIsSuccessor = false;
12914         // See if the user is one of our successors.
12915         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12916           if (*SI == UserParent) {
12917             UserIsSuccessor = true;
12918             break;
12919           }
12920
12921         // If the user is one of our immediate successors, and if that successor
12922         // only has us as a predecessors (we'd have to split the critical edge
12923         // otherwise), we can keep going.
12924         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12925             next(pred_begin(UserParent)) == pred_end(UserParent))
12926           // Okay, the CFG is simple enough, try to sink this instruction.
12927           Changed |= TryToSinkInstruction(I, UserParent);
12928       }
12929     }
12930
12931     // Now that we have an instruction, try combining it to simplify it...
12932 #ifndef NDEBUG
12933     std::string OrigI;
12934 #endif
12935     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
12936     if (Instruction *Result = visit(*I)) {
12937       ++NumCombined;
12938       // Should we replace the old instruction with a new one?
12939       if (Result != I) {
12940         DOUT << "IC: Old = " << *I
12941              << "    New = " << *Result;
12942
12943         // Everything uses the new instruction now.
12944         I->replaceAllUsesWith(Result);
12945
12946         // Push the new instruction and any users onto the worklist.
12947         AddToWorkList(Result);
12948         AddUsersToWorkList(*Result);
12949
12950         // Move the name to the new instruction first.
12951         Result->takeName(I);
12952
12953         // Insert the new instruction into the basic block...
12954         BasicBlock *InstParent = I->getParent();
12955         BasicBlock::iterator InsertPos = I;
12956
12957         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
12958           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12959             ++InsertPos;
12960
12961         InstParent->getInstList().insert(InsertPos, Result);
12962
12963         // Make sure that we reprocess all operands now that we reduced their
12964         // use counts.
12965         AddUsesToWorkList(*I);
12966
12967         // Instructions can end up on the worklist more than once.  Make sure
12968         // we do not process an instruction that has been deleted.
12969         RemoveFromWorkList(I);
12970
12971         // Erase the old instruction.
12972         InstParent->getInstList().erase(I);
12973       } else {
12974 #ifndef NDEBUG
12975         DOUT << "IC: Mod = " << OrigI
12976              << "    New = " << *I;
12977 #endif
12978
12979         // If the instruction was modified, it's possible that it is now dead.
12980         // if so, remove it.
12981         if (isInstructionTriviallyDead(I)) {
12982           // Make sure we process all operands now that we are reducing their
12983           // use counts.
12984           AddUsesToWorkList(*I);
12985
12986           // Instructions may end up in the worklist more than once.  Erase all
12987           // occurrences of this instruction.
12988           RemoveFromWorkList(I);
12989           I->eraseFromParent();
12990         } else {
12991           AddToWorkList(I);
12992           AddUsersToWorkList(*I);
12993         }
12994       }
12995       Changed = true;
12996     }
12997   }
12998
12999   assert(WorklistMap.empty() && "Worklist empty, but map not?");
13000     
13001   // Do an explicit clear, this shrinks the map if needed.
13002   WorklistMap.clear();
13003   return Changed;
13004 }
13005
13006
13007 bool InstCombiner::runOnFunction(Function &F) {
13008   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13009   
13010   bool EverMadeChange = false;
13011
13012   // Iterate while there is work to do.
13013   unsigned Iteration = 0;
13014   while (DoOneIteration(F, Iteration++))
13015     EverMadeChange = true;
13016   return EverMadeChange;
13017 }
13018
13019 FunctionPass *llvm::createInstructionCombiningPass() {
13020   return new InstCombiner();
13021 }