Fix a bunch of other places that used operator[] to test whether
[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 Type *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 Constant *AddOne(Constant *C) {
658   return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
659 }
660 /// SubOne - Subtract one from a ConstantInt
661 static Constant *SubOne(ConstantInt *C) {
662   return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
663 }
664 /// MultiplyOverflows - True if the multiply can not be expressed in an int
665 /// this size.
666 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
667   uint32_t W = C1->getBitWidth();
668   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
669   if (sign) {
670     LHSExt.sext(W * 2);
671     RHSExt.sext(W * 2);
672   } else {
673     LHSExt.zext(W * 2);
674     RHSExt.zext(W * 2);
675   }
676
677   APInt MulExt = LHSExt * RHSExt;
678
679   if (sign) {
680     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
681     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
682     return MulExt.slt(Min) || MulExt.sgt(Max);
683   } else 
684     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
685 }
686
687
688 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
689 /// specified instruction is a constant integer.  If so, check to see if there
690 /// are any bits set in the constant that are not demanded.  If so, shrink the
691 /// constant and return true.
692 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
693                                    APInt Demanded) {
694   assert(I && "No instruction?");
695   assert(OpNo < I->getNumOperands() && "Operand index too large");
696
697   // If the operand is not a constant integer, nothing to do.
698   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
699   if (!OpC) return false;
700
701   // If there are no bits set that aren't demanded, nothing to do.
702   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
703   if ((~Demanded & OpC->getValue()) == 0)
704     return false;
705
706   // This instruction is producing bits that are not demanded. Shrink the RHS.
707   Demanded &= OpC->getValue();
708   I->setOperand(OpNo, ConstantInt::get(Demanded));
709   return true;
710 }
711
712 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
713 // set of known zero and one bits, compute the maximum and minimum values that
714 // could have the specified known zero and known one bits, returning them in
715 // min/max.
716 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
717                                                    const APInt& KnownOne,
718                                                    APInt& Min, APInt& Max) {
719   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
720          KnownZero.getBitWidth() == Min.getBitWidth() &&
721          KnownZero.getBitWidth() == Max.getBitWidth() &&
722          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
723   APInt UnknownBits = ~(KnownZero|KnownOne);
724
725   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
726   // bit if it is unknown.
727   Min = KnownOne;
728   Max = KnownOne|UnknownBits;
729   
730   if (UnknownBits.isNegative()) { // Sign bit is unknown
731     Min.set(Min.getBitWidth()-1);
732     Max.clear(Max.getBitWidth()-1);
733   }
734 }
735
736 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
737 // a set of known zero and one bits, compute the maximum and minimum values that
738 // could have the specified known zero and known one bits, returning them in
739 // min/max.
740 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
741                                                      const APInt &KnownOne,
742                                                      APInt &Min, APInt &Max) {
743   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
744          KnownZero.getBitWidth() == Min.getBitWidth() &&
745          KnownZero.getBitWidth() == Max.getBitWidth() &&
746          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
747   APInt UnknownBits = ~(KnownZero|KnownOne);
748   
749   // The minimum value is when the unknown bits are all zeros.
750   Min = KnownOne;
751   // The maximum value is when the unknown bits are all ones.
752   Max = KnownOne|UnknownBits;
753 }
754
755 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
756 /// SimplifyDemandedBits knows about.  See if the instruction has any
757 /// properties that allow us to simplify its operands.
758 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
759   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
760   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
761   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
762   
763   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
764                                      KnownZero, KnownOne, 0);
765   if (V == 0) return false;
766   if (V == &Inst) return true;
767   ReplaceInstUsesWith(Inst, V);
768   return true;
769 }
770
771 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
772 /// specified instruction operand if possible, updating it in place.  It returns
773 /// true if it made any change and false otherwise.
774 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
775                                         APInt &KnownZero, APInt &KnownOne,
776                                         unsigned Depth) {
777   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
778                                           KnownZero, KnownOne, Depth);
779   if (NewVal == 0) return false;
780   U.set(NewVal);
781   return true;
782 }
783
784
785 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
786 /// value based on the demanded bits.  When this function is called, it is known
787 /// that only the bits set in DemandedMask of the result of V are ever used
788 /// downstream. Consequently, depending on the mask and V, it may be possible
789 /// to replace V with a constant or one of its operands. In such cases, this
790 /// function does the replacement and returns true. In all other cases, it
791 /// returns false after analyzing the expression and setting KnownOne and known
792 /// to be one in the expression.  KnownZero contains all the bits that are known
793 /// to be zero in the expression. These are provided to potentially allow the
794 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
795 /// the expression. KnownOne and KnownZero always follow the invariant that 
796 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
797 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
798 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
799 /// and KnownOne must all be the same.
800 ///
801 /// This returns null if it did not change anything and it permits no
802 /// simplification.  This returns V itself if it did some simplification of V's
803 /// operands based on the information about what bits are demanded. This returns
804 /// some other non-null value if it found out that V is equal to another value
805 /// in the context where the specified bits are demanded, but not for all users.
806 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
807                                              APInt &KnownZero, APInt &KnownOne,
808                                              unsigned Depth) {
809   assert(V != 0 && "Null pointer of Value???");
810   assert(Depth <= 6 && "Limit Search Depth");
811   uint32_t BitWidth = DemandedMask.getBitWidth();
812   const Type *VTy = V->getType();
813   assert((TD || !isa<PointerType>(VTy)) &&
814          "SimplifyDemandedBits needs to know bit widths!");
815   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
816          (!VTy->isIntOrIntVector() ||
817           VTy->getScalarSizeInBits() == BitWidth) &&
818          KnownZero.getBitWidth() == BitWidth &&
819          KnownOne.getBitWidth() == BitWidth &&
820          "Value *V, DemandedMask, KnownZero and KnownOne "
821          "must have same BitWidth");
822   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
823     // We know all of the bits for a constant!
824     KnownOne = CI->getValue() & DemandedMask;
825     KnownZero = ~KnownOne & DemandedMask;
826     return 0;
827   }
828   if (isa<ConstantPointerNull>(V)) {
829     // We know all of the bits for a constant!
830     KnownOne.clear();
831     KnownZero = DemandedMask;
832     return 0;
833   }
834
835   KnownZero.clear();
836   KnownOne.clear();
837   if (DemandedMask == 0) {   // Not demanding any bits from V.
838     if (isa<UndefValue>(V))
839       return 0;
840     return UndefValue::get(VTy);
841   }
842   
843   if (Depth == 6)        // Limit search depth.
844     return 0;
845   
846   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
847   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
848
849   Instruction *I = dyn_cast<Instruction>(V);
850   if (!I) {
851     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
852     return 0;        // Only analyze instructions.
853   }
854
855   // If there are multiple uses of this value and we aren't at the root, then
856   // we can't do any simplifications of the operands, because DemandedMask
857   // only reflects the bits demanded by *one* of the users.
858   if (Depth != 0 && !I->hasOneUse()) {
859     // Despite the fact that we can't simplify this instruction in all User's
860     // context, we can at least compute the knownzero/knownone bits, and we can
861     // do simplifications that apply to *just* the one user if we know that
862     // this instruction has a simpler value in that context.
863     if (I->getOpcode() == Instruction::And) {
864       // If either the LHS or the RHS are Zero, the result is zero.
865       ComputeMaskedBits(I->getOperand(1), DemandedMask,
866                         RHSKnownZero, RHSKnownOne, Depth+1);
867       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
868                         LHSKnownZero, LHSKnownOne, Depth+1);
869       
870       // If all of the demanded bits are known 1 on one side, return the other.
871       // These bits cannot contribute to the result of the 'and' in this
872       // context.
873       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
874           (DemandedMask & ~LHSKnownZero))
875         return I->getOperand(0);
876       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
877           (DemandedMask & ~RHSKnownZero))
878         return I->getOperand(1);
879       
880       // If all of the demanded bits in the inputs are known zeros, return zero.
881       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
882         return Constant::getNullValue(VTy);
883       
884     } else if (I->getOpcode() == Instruction::Or) {
885       // We can simplify (X|Y) -> X or Y in the user's context if we know that
886       // only bits from X or Y are demanded.
887       
888       // If either the LHS or the RHS are One, the result is One.
889       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
890                         RHSKnownZero, RHSKnownOne, Depth+1);
891       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
892                         LHSKnownZero, LHSKnownOne, Depth+1);
893       
894       // If all of the demanded bits are known zero on one side, return the
895       // other.  These bits cannot contribute to the result of the 'or' in this
896       // context.
897       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
898           (DemandedMask & ~LHSKnownOne))
899         return I->getOperand(0);
900       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
901           (DemandedMask & ~RHSKnownOne))
902         return I->getOperand(1);
903       
904       // If all of the potentially set bits on one side are known to be set on
905       // the other side, just use the 'other' side.
906       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
907           (DemandedMask & (~RHSKnownZero)))
908         return I->getOperand(0);
909       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
910           (DemandedMask & (~LHSKnownZero)))
911         return I->getOperand(1);
912     }
913     
914     // Compute the KnownZero/KnownOne bits to simplify things downstream.
915     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
916     return 0;
917   }
918   
919   // If this is the root being simplified, allow it to have multiple uses,
920   // just set the DemandedMask to all bits so that we can try to simplify the
921   // operands.  This allows visitTruncInst (for example) to simplify the
922   // operand of a trunc without duplicating all the logic below.
923   if (Depth == 0 && !V->hasOneUse())
924     DemandedMask = APInt::getAllOnesValue(BitWidth);
925   
926   switch (I->getOpcode()) {
927   default:
928     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
929     break;
930   case Instruction::And:
931     // If either the LHS or the RHS are Zero, the result is zero.
932     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
933                              RHSKnownZero, RHSKnownOne, Depth+1) ||
934         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
935                              LHSKnownZero, LHSKnownOne, Depth+1))
936       return I;
937     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
938     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
939
940     // If all of the demanded bits are known 1 on one side, return the other.
941     // These bits cannot contribute to the result of the 'and'.
942     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
943         (DemandedMask & ~LHSKnownZero))
944       return I->getOperand(0);
945     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
946         (DemandedMask & ~RHSKnownZero))
947       return I->getOperand(1);
948     
949     // If all of the demanded bits in the inputs are known zeros, return zero.
950     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
951       return Constant::getNullValue(VTy);
952       
953     // If the RHS is a constant, see if we can simplify it.
954     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
955       return I;
956       
957     // Output known-1 bits are only known if set in both the LHS & RHS.
958     RHSKnownOne &= LHSKnownOne;
959     // Output known-0 are known to be clear if zero in either the LHS | RHS.
960     RHSKnownZero |= LHSKnownZero;
961     break;
962   case Instruction::Or:
963     // If either the LHS or the RHS are One, the result is One.
964     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
965                              RHSKnownZero, RHSKnownOne, Depth+1) ||
966         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
967                              LHSKnownZero, LHSKnownOne, Depth+1))
968       return I;
969     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
970     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
971     
972     // If all of the demanded bits are known zero on one side, return the other.
973     // These bits cannot contribute to the result of the 'or'.
974     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
975         (DemandedMask & ~LHSKnownOne))
976       return I->getOperand(0);
977     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
978         (DemandedMask & ~RHSKnownOne))
979       return I->getOperand(1);
980
981     // If all of the potentially set bits on one side are known to be set on
982     // the other side, just use the 'other' side.
983     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
984         (DemandedMask & (~RHSKnownZero)))
985       return I->getOperand(0);
986     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
987         (DemandedMask & (~LHSKnownZero)))
988       return I->getOperand(1);
989         
990     // If the RHS is a constant, see if we can simplify it.
991     if (ShrinkDemandedConstant(I, 1, DemandedMask))
992       return I;
993           
994     // Output known-0 bits are only known if clear in both the LHS & RHS.
995     RHSKnownZero &= LHSKnownZero;
996     // Output known-1 are known to be set if set in either the LHS | RHS.
997     RHSKnownOne |= LHSKnownOne;
998     break;
999   case Instruction::Xor: {
1000     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1001                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1002         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1003                              LHSKnownZero, LHSKnownOne, Depth+1))
1004       return I;
1005     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1006     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1007     
1008     // If all of the demanded bits are known zero on one side, return the other.
1009     // These bits cannot contribute to the result of the 'xor'.
1010     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1011       return I->getOperand(0);
1012     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1013       return I->getOperand(1);
1014     
1015     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1016     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1017                          (RHSKnownOne & LHSKnownOne);
1018     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1019     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1020                         (RHSKnownOne & LHSKnownZero);
1021     
1022     // If all of the demanded bits are known to be zero on one side or the
1023     // other, turn this into an *inclusive* or.
1024     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1025     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1026       Instruction *Or =
1027         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1028                                  I->getName());
1029       return InsertNewInstBefore(Or, *I);
1030     }
1031     
1032     // If all of the demanded bits on one side are known, and all of the set
1033     // bits on that side are also known to be set on the other side, turn this
1034     // into an AND, as we know the bits will be cleared.
1035     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1036     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1037       // all known
1038       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1039         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1040         Instruction *And = 
1041           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1042         return InsertNewInstBefore(And, *I);
1043       }
1044     }
1045     
1046     // If the RHS is a constant, see if we can simplify it.
1047     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1048     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1049       return I;
1050     
1051     RHSKnownZero = KnownZeroOut;
1052     RHSKnownOne  = KnownOneOut;
1053     break;
1054   }
1055   case Instruction::Select:
1056     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1057                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1058         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1059                              LHSKnownZero, LHSKnownOne, Depth+1))
1060       return I;
1061     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1062     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1063     
1064     // If the operands are constants, see if we can simplify them.
1065     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1066         ShrinkDemandedConstant(I, 2, DemandedMask))
1067       return I;
1068     
1069     // Only known if known in both the LHS and RHS.
1070     RHSKnownOne &= LHSKnownOne;
1071     RHSKnownZero &= LHSKnownZero;
1072     break;
1073   case Instruction::Trunc: {
1074     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1075     DemandedMask.zext(truncBf);
1076     RHSKnownZero.zext(truncBf);
1077     RHSKnownOne.zext(truncBf);
1078     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1079                              RHSKnownZero, RHSKnownOne, Depth+1))
1080       return I;
1081     DemandedMask.trunc(BitWidth);
1082     RHSKnownZero.trunc(BitWidth);
1083     RHSKnownOne.trunc(BitWidth);
1084     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1085     break;
1086   }
1087   case Instruction::BitCast:
1088     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1089       return false;  // vector->int or fp->int?
1090
1091     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1092       if (const VectorType *SrcVTy =
1093             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1094         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1095           // Don't touch a bitcast between vectors of different element counts.
1096           return false;
1097       } else
1098         // Don't touch a scalar-to-vector bitcast.
1099         return false;
1100     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1101       // Don't touch a vector-to-scalar bitcast.
1102       return false;
1103
1104     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1105                              RHSKnownZero, RHSKnownOne, Depth+1))
1106       return I;
1107     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1108     break;
1109   case Instruction::ZExt: {
1110     // Compute the bits in the result that are not present in the input.
1111     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1112     
1113     DemandedMask.trunc(SrcBitWidth);
1114     RHSKnownZero.trunc(SrcBitWidth);
1115     RHSKnownOne.trunc(SrcBitWidth);
1116     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1117                              RHSKnownZero, RHSKnownOne, Depth+1))
1118       return I;
1119     DemandedMask.zext(BitWidth);
1120     RHSKnownZero.zext(BitWidth);
1121     RHSKnownOne.zext(BitWidth);
1122     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1123     // The top bits are known to be zero.
1124     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1125     break;
1126   }
1127   case Instruction::SExt: {
1128     // Compute the bits in the result that are not present in the input.
1129     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1130     
1131     APInt InputDemandedBits = DemandedMask & 
1132                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1133
1134     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1135     // If any of the sign extended bits are demanded, we know that the sign
1136     // bit is demanded.
1137     if ((NewBits & DemandedMask) != 0)
1138       InputDemandedBits.set(SrcBitWidth-1);
1139       
1140     InputDemandedBits.trunc(SrcBitWidth);
1141     RHSKnownZero.trunc(SrcBitWidth);
1142     RHSKnownOne.trunc(SrcBitWidth);
1143     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1144                              RHSKnownZero, RHSKnownOne, Depth+1))
1145       return I;
1146     InputDemandedBits.zext(BitWidth);
1147     RHSKnownZero.zext(BitWidth);
1148     RHSKnownOne.zext(BitWidth);
1149     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1150       
1151     // If the sign bit of the input is known set or clear, then we know the
1152     // top bits of the result.
1153
1154     // If the input sign bit is known zero, or if the NewBits are not demanded
1155     // convert this into a zero extension.
1156     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1157       // Convert to ZExt cast
1158       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1159       return InsertNewInstBefore(NewCast, *I);
1160     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1161       RHSKnownOne |= NewBits;
1162     }
1163     break;
1164   }
1165   case Instruction::Add: {
1166     // Figure out what the input bits are.  If the top bits of the and result
1167     // are not demanded, then the add doesn't demand them from its input
1168     // either.
1169     unsigned NLZ = DemandedMask.countLeadingZeros();
1170       
1171     // If there is a constant on the RHS, there are a variety of xformations
1172     // we can do.
1173     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1174       // If null, this should be simplified elsewhere.  Some of the xforms here
1175       // won't work if the RHS is zero.
1176       if (RHS->isZero())
1177         break;
1178       
1179       // If the top bit of the output is demanded, demand everything from the
1180       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1181       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1182
1183       // Find information about known zero/one bits in the input.
1184       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1185                                LHSKnownZero, LHSKnownOne, Depth+1))
1186         return I;
1187
1188       // If the RHS of the add has bits set that can't affect the input, reduce
1189       // the constant.
1190       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1191         return I;
1192       
1193       // Avoid excess work.
1194       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1195         break;
1196       
1197       // Turn it into OR if input bits are zero.
1198       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1199         Instruction *Or =
1200           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1201                                    I->getName());
1202         return InsertNewInstBefore(Or, *I);
1203       }
1204       
1205       // We can say something about the output known-zero and known-one bits,
1206       // depending on potential carries from the input constant and the
1207       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1208       // bits set and the RHS constant is 0x01001, then we know we have a known
1209       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1210       
1211       // To compute this, we first compute the potential carry bits.  These are
1212       // the bits which may be modified.  I'm not aware of a better way to do
1213       // this scan.
1214       const APInt &RHSVal = RHS->getValue();
1215       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1216       
1217       // Now that we know which bits have carries, compute the known-1/0 sets.
1218       
1219       // Bits are known one if they are known zero in one operand and one in the
1220       // other, and there is no input carry.
1221       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1222                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1223       
1224       // Bits are known zero if they are known zero in both operands and there
1225       // is no input carry.
1226       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1227     } else {
1228       // If the high-bits of this ADD are not demanded, then it does not demand
1229       // the high bits of its LHS or RHS.
1230       if (DemandedMask[BitWidth-1] == 0) {
1231         // Right fill the mask of bits for this ADD to demand the most
1232         // significant bit and all those below it.
1233         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1234         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1235                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1236             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1237                                  LHSKnownZero, LHSKnownOne, Depth+1))
1238           return I;
1239       }
1240     }
1241     break;
1242   }
1243   case Instruction::Sub:
1244     // If the high-bits of this SUB are not demanded, then it does not demand
1245     // the high bits of its LHS or RHS.
1246     if (DemandedMask[BitWidth-1] == 0) {
1247       // Right fill the mask of bits for this SUB to demand the most
1248       // significant bit and all those below it.
1249       uint32_t NLZ = DemandedMask.countLeadingZeros();
1250       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1251       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1252                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1253           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1254                                LHSKnownZero, LHSKnownOne, Depth+1))
1255         return I;
1256     }
1257     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1258     // the known zeros and ones.
1259     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1260     break;
1261   case Instruction::Shl:
1262     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1263       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1264       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1265       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1266                                RHSKnownZero, RHSKnownOne, Depth+1))
1267         return I;
1268       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1269       RHSKnownZero <<= ShiftAmt;
1270       RHSKnownOne  <<= ShiftAmt;
1271       // low bits known zero.
1272       if (ShiftAmt)
1273         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1274     }
1275     break;
1276   case Instruction::LShr:
1277     // For a logical shift right
1278     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1279       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1280       
1281       // Unsigned shift right.
1282       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1283       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1284                                RHSKnownZero, RHSKnownOne, Depth+1))
1285         return I;
1286       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1287       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1288       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1289       if (ShiftAmt) {
1290         // Compute the new bits that are at the top now.
1291         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1292         RHSKnownZero |= HighBits;  // high bits known zero.
1293       }
1294     }
1295     break;
1296   case Instruction::AShr:
1297     // If this is an arithmetic shift right and only the low-bit is set, we can
1298     // always convert this into a logical shr, even if the shift amount is
1299     // variable.  The low bit of the shift cannot be an input sign bit unless
1300     // the shift amount is >= the size of the datatype, which is undefined.
1301     if (DemandedMask == 1) {
1302       // Perform the logical shift right.
1303       Instruction *NewVal = BinaryOperator::CreateLShr(
1304                         I->getOperand(0), I->getOperand(1), I->getName());
1305       return InsertNewInstBefore(NewVal, *I);
1306     }    
1307
1308     // If the sign bit is the only bit demanded by this ashr, then there is no
1309     // need to do it, the shift doesn't change the high bit.
1310     if (DemandedMask.isSignBit())
1311       return I->getOperand(0);
1312     
1313     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1314       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1315       
1316       // Signed shift right.
1317       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1318       // If any of the "high bits" are demanded, we should set the sign bit as
1319       // demanded.
1320       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1321         DemandedMaskIn.set(BitWidth-1);
1322       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1323                                RHSKnownZero, RHSKnownOne, Depth+1))
1324         return I;
1325       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1326       // Compute the new bits that are at the top now.
1327       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1328       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1329       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1330         
1331       // Handle the sign bits.
1332       APInt SignBit(APInt::getSignBit(BitWidth));
1333       // Adjust to where it is now in the mask.
1334       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1335         
1336       // If the input sign bit is known to be zero, or if none of the top bits
1337       // are demanded, turn this into an unsigned shift right.
1338       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1339           (HighBits & ~DemandedMask) == HighBits) {
1340         // Perform the logical shift right.
1341         Instruction *NewVal = BinaryOperator::CreateLShr(
1342                           I->getOperand(0), SA, I->getName());
1343         return InsertNewInstBefore(NewVal, *I);
1344       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1345         RHSKnownOne |= HighBits;
1346       }
1347     }
1348     break;
1349   case Instruction::SRem:
1350     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1351       APInt RA = Rem->getValue().abs();
1352       if (RA.isPowerOf2()) {
1353         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1354           return I->getOperand(0);
1355
1356         APInt LowBits = RA - 1;
1357         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1358         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1359                                  LHSKnownZero, LHSKnownOne, Depth+1))
1360           return I;
1361
1362         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1363           LHSKnownZero |= ~LowBits;
1364
1365         KnownZero |= LHSKnownZero & DemandedMask;
1366
1367         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1368       }
1369     }
1370     break;
1371   case Instruction::URem: {
1372     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1373     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1374     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1375                              KnownZero2, KnownOne2, Depth+1) ||
1376         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1377                              KnownZero2, KnownOne2, Depth+1))
1378       return I;
1379
1380     unsigned Leaders = KnownZero2.countLeadingOnes();
1381     Leaders = std::max(Leaders,
1382                        KnownZero2.countLeadingOnes());
1383     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1384     break;
1385   }
1386   case Instruction::Call:
1387     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1388       switch (II->getIntrinsicID()) {
1389       default: break;
1390       case Intrinsic::bswap: {
1391         // If the only bits demanded come from one byte of the bswap result,
1392         // just shift the input byte into position to eliminate the bswap.
1393         unsigned NLZ = DemandedMask.countLeadingZeros();
1394         unsigned NTZ = DemandedMask.countTrailingZeros();
1395           
1396         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1397         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1398         // have 14 leading zeros, round to 8.
1399         NLZ &= ~7;
1400         NTZ &= ~7;
1401         // If we need exactly one byte, we can do this transformation.
1402         if (BitWidth-NLZ-NTZ == 8) {
1403           unsigned ResultBit = NTZ;
1404           unsigned InputBit = BitWidth-NTZ-8;
1405           
1406           // Replace this with either a left or right shift to get the byte into
1407           // the right place.
1408           Instruction *NewVal;
1409           if (InputBit > ResultBit)
1410             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1411                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1412           else
1413             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1414                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1415           NewVal->takeName(I);
1416           return InsertNewInstBefore(NewVal, *I);
1417         }
1418           
1419         // TODO: Could compute known zero/one bits based on the input.
1420         break;
1421       }
1422       }
1423     }
1424     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1425     break;
1426   }
1427   
1428   // If the client is only demanding bits that we know, return the known
1429   // constant.
1430   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1431     Constant *C = ConstantInt::get(RHSKnownOne);
1432     if (isa<PointerType>(V->getType()))
1433       C = ConstantExpr::getIntToPtr(C, V->getType());
1434     return C;
1435   }
1436   return false;
1437 }
1438
1439
1440 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1441 /// any number of elements. DemandedElts contains the set of elements that are
1442 /// actually used by the caller.  This method analyzes which elements of the
1443 /// operand are undef and returns that information in UndefElts.
1444 ///
1445 /// If the information about demanded elements can be used to simplify the
1446 /// operation, the operation is simplified, then the resultant value is
1447 /// returned.  This returns null if no change was made.
1448 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1449                                                 APInt& UndefElts,
1450                                                 unsigned Depth) {
1451   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1452   APInt EltMask(APInt::getAllOnesValue(VWidth));
1453   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1454
1455   if (isa<UndefValue>(V)) {
1456     // If the entire vector is undefined, just return this info.
1457     UndefElts = EltMask;
1458     return 0;
1459   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1460     UndefElts = EltMask;
1461     return UndefValue::get(V->getType());
1462   }
1463
1464   UndefElts = 0;
1465   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1466     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1467     Constant *Undef = UndefValue::get(EltTy);
1468
1469     std::vector<Constant*> Elts;
1470     for (unsigned i = 0; i != VWidth; ++i)
1471       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1472         Elts.push_back(Undef);
1473         UndefElts.set(i);
1474       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1475         Elts.push_back(Undef);
1476         UndefElts.set(i);
1477       } else {                               // Otherwise, defined.
1478         Elts.push_back(CP->getOperand(i));
1479       }
1480
1481     // If we changed the constant, return it.
1482     Constant *NewCP = ConstantVector::get(Elts);
1483     return NewCP != CP ? NewCP : 0;
1484   } else if (isa<ConstantAggregateZero>(V)) {
1485     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1486     // set to undef.
1487     
1488     // Check if this is identity. If so, return 0 since we are not simplifying
1489     // anything.
1490     if (DemandedElts == ((1ULL << VWidth) -1))
1491       return 0;
1492     
1493     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1494     Constant *Zero = Constant::getNullValue(EltTy);
1495     Constant *Undef = UndefValue::get(EltTy);
1496     std::vector<Constant*> Elts;
1497     for (unsigned i = 0; i != VWidth; ++i) {
1498       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1499       Elts.push_back(Elt);
1500     }
1501     UndefElts = DemandedElts ^ EltMask;
1502     return ConstantVector::get(Elts);
1503   }
1504   
1505   // Limit search depth.
1506   if (Depth == 10)
1507     return 0;
1508
1509   // If multiple users are using the root value, procede with
1510   // simplification conservatively assuming that all elements
1511   // are needed.
1512   if (!V->hasOneUse()) {
1513     // Quit if we find multiple users of a non-root value though.
1514     // They'll be handled when it's their turn to be visited by
1515     // the main instcombine process.
1516     if (Depth != 0)
1517       // TODO: Just compute the UndefElts information recursively.
1518       return 0;
1519
1520     // Conservatively assume that all elements are needed.
1521     DemandedElts = EltMask;
1522   }
1523   
1524   Instruction *I = dyn_cast<Instruction>(V);
1525   if (!I) return 0;        // Only analyze instructions.
1526   
1527   bool MadeChange = false;
1528   APInt UndefElts2(VWidth, 0);
1529   Value *TmpV;
1530   switch (I->getOpcode()) {
1531   default: break;
1532     
1533   case Instruction::InsertElement: {
1534     // If this is a variable index, we don't know which element it overwrites.
1535     // demand exactly the same input as we produce.
1536     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1537     if (Idx == 0) {
1538       // Note that we can't propagate undef elt info, because we don't know
1539       // which elt is getting updated.
1540       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1541                                         UndefElts2, Depth+1);
1542       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1543       break;
1544     }
1545     
1546     // If this is inserting an element that isn't demanded, remove this
1547     // insertelement.
1548     unsigned IdxNo = Idx->getZExtValue();
1549     if (IdxNo >= VWidth || !DemandedElts[IdxNo])
1550       return AddSoonDeadInstToWorklist(*I, 0);
1551     
1552     // Otherwise, the element inserted overwrites whatever was there, so the
1553     // input demanded set is simpler than the output set.
1554     APInt DemandedElts2 = DemandedElts;
1555     DemandedElts2.clear(IdxNo);
1556     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1557                                       UndefElts, Depth+1);
1558     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1559
1560     // The inserted element is defined.
1561     UndefElts.clear(IdxNo);
1562     break;
1563   }
1564   case Instruction::ShuffleVector: {
1565     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1566     uint64_t LHSVWidth =
1567       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1568     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1569     for (unsigned i = 0; i < VWidth; i++) {
1570       if (DemandedElts[i]) {
1571         unsigned MaskVal = Shuffle->getMaskValue(i);
1572         if (MaskVal != -1u) {
1573           assert(MaskVal < LHSVWidth * 2 &&
1574                  "shufflevector mask index out of range!");
1575           if (MaskVal < LHSVWidth)
1576             LeftDemanded.set(MaskVal);
1577           else
1578             RightDemanded.set(MaskVal - LHSVWidth);
1579         }
1580       }
1581     }
1582
1583     APInt UndefElts4(LHSVWidth, 0);
1584     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1585                                       UndefElts4, Depth+1);
1586     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1587
1588     APInt UndefElts3(LHSVWidth, 0);
1589     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1590                                       UndefElts3, Depth+1);
1591     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1592
1593     bool NewUndefElts = false;
1594     for (unsigned i = 0; i < VWidth; i++) {
1595       unsigned MaskVal = Shuffle->getMaskValue(i);
1596       if (MaskVal == -1u) {
1597         UndefElts.set(i);
1598       } else if (MaskVal < LHSVWidth) {
1599         if (UndefElts4[MaskVal]) {
1600           NewUndefElts = true;
1601           UndefElts.set(i);
1602         }
1603       } else {
1604         if (UndefElts3[MaskVal - LHSVWidth]) {
1605           NewUndefElts = true;
1606           UndefElts.set(i);
1607         }
1608       }
1609     }
1610
1611     if (NewUndefElts) {
1612       // Add additional discovered undefs.
1613       std::vector<Constant*> Elts;
1614       for (unsigned i = 0; i < VWidth; ++i) {
1615         if (UndefElts[i])
1616           Elts.push_back(UndefValue::get(Type::Int32Ty));
1617         else
1618           Elts.push_back(ConstantInt::get(Type::Int32Ty,
1619                                           Shuffle->getMaskValue(i)));
1620       }
1621       I->setOperand(2, ConstantVector::get(Elts));
1622       MadeChange = true;
1623     }
1624     break;
1625   }
1626   case Instruction::BitCast: {
1627     // Vector->vector casts only.
1628     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1629     if (!VTy) break;
1630     unsigned InVWidth = VTy->getNumElements();
1631     APInt InputDemandedElts(InVWidth, 0);
1632     unsigned Ratio;
1633
1634     if (VWidth == InVWidth) {
1635       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1636       // elements as are demanded of us.
1637       Ratio = 1;
1638       InputDemandedElts = DemandedElts;
1639     } else if (VWidth > InVWidth) {
1640       // Untested so far.
1641       break;
1642       
1643       // If there are more elements in the result than there are in the source,
1644       // then an input element is live if any of the corresponding output
1645       // elements are live.
1646       Ratio = VWidth/InVWidth;
1647       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1648         if (DemandedElts[OutIdx])
1649           InputDemandedElts.set(OutIdx/Ratio);
1650       }
1651     } else {
1652       // Untested so far.
1653       break;
1654       
1655       // If there are more elements in the source than there are in the result,
1656       // then an input element is live if the corresponding output element is
1657       // live.
1658       Ratio = InVWidth/VWidth;
1659       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1660         if (DemandedElts[InIdx/Ratio])
1661           InputDemandedElts.set(InIdx);
1662     }
1663     
1664     // div/rem demand all inputs, because they don't want divide by zero.
1665     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1666                                       UndefElts2, Depth+1);
1667     if (TmpV) {
1668       I->setOperand(0, TmpV);
1669       MadeChange = true;
1670     }
1671     
1672     UndefElts = UndefElts2;
1673     if (VWidth > InVWidth) {
1674       assert(0 && "Unimp");
1675       // If there are more elements in the result than there are in the source,
1676       // then an output element is undef if the corresponding input element is
1677       // undef.
1678       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1679         if (UndefElts2[OutIdx/Ratio])
1680           UndefElts.set(OutIdx);
1681     } else if (VWidth < InVWidth) {
1682       assert(0 && "Unimp");
1683       // If there are more elements in the source than there are in the result,
1684       // then a result element is undef if all of the corresponding input
1685       // elements are undef.
1686       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1687       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1688         if (!UndefElts2[InIdx])            // Not undef?
1689           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1690     }
1691     break;
1692   }
1693   case Instruction::And:
1694   case Instruction::Or:
1695   case Instruction::Xor:
1696   case Instruction::Add:
1697   case Instruction::Sub:
1698   case Instruction::Mul:
1699     // div/rem demand all inputs, because they don't want divide by zero.
1700     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1701                                       UndefElts, Depth+1);
1702     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1703     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1704                                       UndefElts2, Depth+1);
1705     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1706       
1707     // Output elements are undefined if both are undefined.  Consider things
1708     // like undef&0.  The result is known zero, not undef.
1709     UndefElts &= UndefElts2;
1710     break;
1711     
1712   case Instruction::Call: {
1713     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1714     if (!II) break;
1715     switch (II->getIntrinsicID()) {
1716     default: break;
1717       
1718     // Binary vector operations that work column-wise.  A dest element is a
1719     // function of the corresponding input elements from the two inputs.
1720     case Intrinsic::x86_sse_sub_ss:
1721     case Intrinsic::x86_sse_mul_ss:
1722     case Intrinsic::x86_sse_min_ss:
1723     case Intrinsic::x86_sse_max_ss:
1724     case Intrinsic::x86_sse2_sub_sd:
1725     case Intrinsic::x86_sse2_mul_sd:
1726     case Intrinsic::x86_sse2_min_sd:
1727     case Intrinsic::x86_sse2_max_sd:
1728       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1729                                         UndefElts, Depth+1);
1730       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1731       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1732                                         UndefElts2, Depth+1);
1733       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1734
1735       // If only the low elt is demanded and this is a scalarizable intrinsic,
1736       // scalarize it now.
1737       if (DemandedElts == 1) {
1738         switch (II->getIntrinsicID()) {
1739         default: break;
1740         case Intrinsic::x86_sse_sub_ss:
1741         case Intrinsic::x86_sse_mul_ss:
1742         case Intrinsic::x86_sse2_sub_sd:
1743         case Intrinsic::x86_sse2_mul_sd:
1744           // TODO: Lower MIN/MAX/ABS/etc
1745           Value *LHS = II->getOperand(1);
1746           Value *RHS = II->getOperand(2);
1747           // Extract the element as scalars.
1748           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1749           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1750           
1751           switch (II->getIntrinsicID()) {
1752           default: assert(0 && "Case stmts out of sync!");
1753           case Intrinsic::x86_sse_sub_ss:
1754           case Intrinsic::x86_sse2_sub_sd:
1755             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1756                                                         II->getName()), *II);
1757             break;
1758           case Intrinsic::x86_sse_mul_ss:
1759           case Intrinsic::x86_sse2_mul_sd:
1760             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1761                                                          II->getName()), *II);
1762             break;
1763           }
1764           
1765           Instruction *New =
1766             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1767                                       II->getName());
1768           InsertNewInstBefore(New, *II);
1769           AddSoonDeadInstToWorklist(*II, 0);
1770           return New;
1771         }            
1772       }
1773         
1774       // Output elements are undefined if both are undefined.  Consider things
1775       // like undef&0.  The result is known zero, not undef.
1776       UndefElts &= UndefElts2;
1777       break;
1778     }
1779     break;
1780   }
1781   }
1782   return MadeChange ? I : 0;
1783 }
1784
1785
1786 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1787 /// function is designed to check a chain of associative operators for a
1788 /// potential to apply a certain optimization.  Since the optimization may be
1789 /// applicable if the expression was reassociated, this checks the chain, then
1790 /// reassociates the expression as necessary to expose the optimization
1791 /// opportunity.  This makes use of a special Functor, which must define
1792 /// 'shouldApply' and 'apply' methods.
1793 ///
1794 template<typename Functor>
1795 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1796   unsigned Opcode = Root.getOpcode();
1797   Value *LHS = Root.getOperand(0);
1798
1799   // Quick check, see if the immediate LHS matches...
1800   if (F.shouldApply(LHS))
1801     return F.apply(Root);
1802
1803   // Otherwise, if the LHS is not of the same opcode as the root, return.
1804   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1805   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1806     // Should we apply this transform to the RHS?
1807     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1808
1809     // If not to the RHS, check to see if we should apply to the LHS...
1810     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1811       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1812       ShouldApply = true;
1813     }
1814
1815     // If the functor wants to apply the optimization to the RHS of LHSI,
1816     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1817     if (ShouldApply) {
1818       // Now all of the instructions are in the current basic block, go ahead
1819       // and perform the reassociation.
1820       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1821
1822       // First move the selected RHS to the LHS of the root...
1823       Root.setOperand(0, LHSI->getOperand(1));
1824
1825       // Make what used to be the LHS of the root be the user of the root...
1826       Value *ExtraOperand = TmpLHSI->getOperand(1);
1827       if (&Root == TmpLHSI) {
1828         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1829         return 0;
1830       }
1831       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1832       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1833       BasicBlock::iterator ARI = &Root; ++ARI;
1834       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1835       ARI = Root;
1836
1837       // Now propagate the ExtraOperand down the chain of instructions until we
1838       // get to LHSI.
1839       while (TmpLHSI != LHSI) {
1840         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1841         // Move the instruction to immediately before the chain we are
1842         // constructing to avoid breaking dominance properties.
1843         NextLHSI->moveBefore(ARI);
1844         ARI = NextLHSI;
1845
1846         Value *NextOp = NextLHSI->getOperand(1);
1847         NextLHSI->setOperand(1, ExtraOperand);
1848         TmpLHSI = NextLHSI;
1849         ExtraOperand = NextOp;
1850       }
1851
1852       // Now that the instructions are reassociated, have the functor perform
1853       // the transformation...
1854       return F.apply(Root);
1855     }
1856
1857     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1858   }
1859   return 0;
1860 }
1861
1862 namespace {
1863
1864 // AddRHS - Implements: X + X --> X << 1
1865 struct AddRHS {
1866   Value *RHS;
1867   AddRHS(Value *rhs) : RHS(rhs) {}
1868   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1869   Instruction *apply(BinaryOperator &Add) const {
1870     return BinaryOperator::CreateShl(Add.getOperand(0),
1871                                      ConstantInt::get(Add.getType(), 1));
1872   }
1873 };
1874
1875 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1876 //                 iff C1&C2 == 0
1877 struct AddMaskingAnd {
1878   Constant *C2;
1879   AddMaskingAnd(Constant *c) : C2(c) {}
1880   bool shouldApply(Value *LHS) const {
1881     ConstantInt *C1;
1882     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1883            ConstantExpr::getAnd(C1, C2)->isNullValue();
1884   }
1885   Instruction *apply(BinaryOperator &Add) const {
1886     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1887   }
1888 };
1889
1890 }
1891
1892 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1893                                              InstCombiner *IC) {
1894   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1895     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1896   }
1897
1898   // Figure out if the constant is the left or the right argument.
1899   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1900   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1901
1902   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1903     if (ConstIsRHS)
1904       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1905     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1906   }
1907
1908   Value *Op0 = SO, *Op1 = ConstOperand;
1909   if (!ConstIsRHS)
1910     std::swap(Op0, Op1);
1911   Instruction *New;
1912   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1913     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1914   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1915     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1916                           SO->getName()+".cmp");
1917   else {
1918     assert(0 && "Unknown binary instruction type!");
1919     abort();
1920   }
1921   return IC->InsertNewInstBefore(New, I);
1922 }
1923
1924 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1925 // constant as the other operand, try to fold the binary operator into the
1926 // select arguments.  This also works for Cast instructions, which obviously do
1927 // not have a second operand.
1928 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1929                                      InstCombiner *IC) {
1930   // Don't modify shared select instructions
1931   if (!SI->hasOneUse()) return 0;
1932   Value *TV = SI->getOperand(1);
1933   Value *FV = SI->getOperand(2);
1934
1935   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1936     // Bool selects with constant operands can be folded to logical ops.
1937     if (SI->getType() == Type::Int1Ty) return 0;
1938
1939     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1940     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1941
1942     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1943                               SelectFalseVal);
1944   }
1945   return 0;
1946 }
1947
1948
1949 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1950 /// node as operand #0, see if we can fold the instruction into the PHI (which
1951 /// is only possible if all operands to the PHI are constants).
1952 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1953   PHINode *PN = cast<PHINode>(I.getOperand(0));
1954   unsigned NumPHIValues = PN->getNumIncomingValues();
1955   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1956
1957   // Check to see if all of the operands of the PHI are constants.  If there is
1958   // one non-constant value, remember the BB it is.  If there is more than one
1959   // or if *it* is a PHI, bail out.
1960   BasicBlock *NonConstBB = 0;
1961   for (unsigned i = 0; i != NumPHIValues; ++i)
1962     if (!isa<Constant>(PN->getIncomingValue(i))) {
1963       if (NonConstBB) return 0;  // More than one non-const value.
1964       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1965       NonConstBB = PN->getIncomingBlock(i);
1966       
1967       // If the incoming non-constant value is in I's block, we have an infinite
1968       // loop.
1969       if (NonConstBB == I.getParent())
1970         return 0;
1971     }
1972   
1973   // If there is exactly one non-constant value, we can insert a copy of the
1974   // operation in that block.  However, if this is a critical edge, we would be
1975   // inserting the computation one some other paths (e.g. inside a loop).  Only
1976   // do this if the pred block is unconditionally branching into the phi block.
1977   if (NonConstBB) {
1978     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1979     if (!BI || !BI->isUnconditional()) return 0;
1980   }
1981
1982   // Okay, we can do the transformation: create the new PHI node.
1983   PHINode *NewPN = PHINode::Create(I.getType(), "");
1984   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1985   InsertNewInstBefore(NewPN, *PN);
1986   NewPN->takeName(PN);
1987
1988   // Next, add all of the operands to the PHI.
1989   if (I.getNumOperands() == 2) {
1990     Constant *C = cast<Constant>(I.getOperand(1));
1991     for (unsigned i = 0; i != NumPHIValues; ++i) {
1992       Value *InV = 0;
1993       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1994         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1995           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1996         else
1997           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1998       } else {
1999         assert(PN->getIncomingBlock(i) == NonConstBB);
2000         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
2001           InV = BinaryOperator::Create(BO->getOpcode(),
2002                                        PN->getIncomingValue(i), C, "phitmp",
2003                                        NonConstBB->getTerminator());
2004         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2005           InV = CmpInst::Create(CI->getOpcode(), 
2006                                 CI->getPredicate(),
2007                                 PN->getIncomingValue(i), C, "phitmp",
2008                                 NonConstBB->getTerminator());
2009         else
2010           assert(0 && "Unknown binop!");
2011         
2012         AddToWorkList(cast<Instruction>(InV));
2013       }
2014       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2015     }
2016   } else { 
2017     CastInst *CI = cast<CastInst>(&I);
2018     const Type *RetTy = CI->getType();
2019     for (unsigned i = 0; i != NumPHIValues; ++i) {
2020       Value *InV;
2021       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2022         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2023       } else {
2024         assert(PN->getIncomingBlock(i) == NonConstBB);
2025         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2026                                I.getType(), "phitmp", 
2027                                NonConstBB->getTerminator());
2028         AddToWorkList(cast<Instruction>(InV));
2029       }
2030       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2031     }
2032   }
2033   return ReplaceInstUsesWith(I, NewPN);
2034 }
2035
2036
2037 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2038 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2039 /// This basically requires proving that the add in the original type would not
2040 /// overflow to change the sign bit or have a carry out.
2041 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2042   // There are different heuristics we can use for this.  Here are some simple
2043   // ones.
2044   
2045   // Add has the property that adding any two 2's complement numbers can only 
2046   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2047   // have at least two sign bits, we know that the addition of the two values will
2048   // sign extend fine.
2049   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2050     return true;
2051   
2052   
2053   // If one of the operands only has one non-zero bit, and if the other operand
2054   // has a known-zero bit in a more significant place than it (not including the
2055   // sign bit) the ripple may go up to and fill the zero, but won't change the
2056   // sign.  For example, (X & ~4) + 1.
2057   
2058   // TODO: Implement.
2059   
2060   return false;
2061 }
2062
2063
2064 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2065   bool Changed = SimplifyCommutative(I);
2066   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2067
2068   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2069     // X + undef -> undef
2070     if (isa<UndefValue>(RHS))
2071       return ReplaceInstUsesWith(I, RHS);
2072
2073     // X + 0 --> X
2074     if (RHSC->isNullValue())
2075       return ReplaceInstUsesWith(I, LHS);
2076
2077     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2078       // X + (signbit) --> X ^ signbit
2079       const APInt& Val = CI->getValue();
2080       uint32_t BitWidth = Val.getBitWidth();
2081       if (Val == APInt::getSignBit(BitWidth))
2082         return BinaryOperator::CreateXor(LHS, RHS);
2083       
2084       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2085       // (X & 254)+1 -> (X&254)|1
2086       if (SimplifyDemandedInstructionBits(I))
2087         return &I;
2088
2089       // zext(i1) - 1  ->  select i1, 0, -1
2090       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2091         if (CI->isAllOnesValue() &&
2092             ZI->getOperand(0)->getType() == Type::Int1Ty)
2093           return SelectInst::Create(ZI->getOperand(0),
2094                                     Constant::getNullValue(I.getType()),
2095                                     ConstantInt::getAllOnesValue(I.getType()));
2096     }
2097
2098     if (isa<PHINode>(LHS))
2099       if (Instruction *NV = FoldOpIntoPhi(I))
2100         return NV;
2101     
2102     ConstantInt *XorRHS = 0;
2103     Value *XorLHS = 0;
2104     if (isa<ConstantInt>(RHSC) &&
2105         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2106       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2107       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2108       
2109       uint32_t Size = TySizeBits / 2;
2110       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2111       APInt CFF80Val(-C0080Val);
2112       do {
2113         if (TySizeBits > Size) {
2114           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2115           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2116           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2117               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2118             // This is a sign extend if the top bits are known zero.
2119             if (!MaskedValueIsZero(XorLHS, 
2120                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2121               Size = 0;  // Not a sign ext, but can't be any others either.
2122             break;
2123           }
2124         }
2125         Size >>= 1;
2126         C0080Val = APIntOps::lshr(C0080Val, Size);
2127         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2128       } while (Size >= 1);
2129       
2130       // FIXME: This shouldn't be necessary. When the backends can handle types
2131       // with funny bit widths then this switch statement should be removed. It
2132       // is just here to get the size of the "middle" type back up to something
2133       // that the back ends can handle.
2134       const Type *MiddleType = 0;
2135       switch (Size) {
2136         default: break;
2137         case 32: MiddleType = Type::Int32Ty; break;
2138         case 16: MiddleType = Type::Int16Ty; break;
2139         case  8: MiddleType = Type::Int8Ty; break;
2140       }
2141       if (MiddleType) {
2142         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2143         InsertNewInstBefore(NewTrunc, I);
2144         return new SExtInst(NewTrunc, I.getType(), I.getName());
2145       }
2146     }
2147   }
2148
2149   if (I.getType() == Type::Int1Ty)
2150     return BinaryOperator::CreateXor(LHS, RHS);
2151
2152   // X + X --> X << 1
2153   if (I.getType()->isInteger()) {
2154     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2155
2156     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2157       if (RHSI->getOpcode() == Instruction::Sub)
2158         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2159           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2160     }
2161     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2162       if (LHSI->getOpcode() == Instruction::Sub)
2163         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2164           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2165     }
2166   }
2167
2168   // -A + B  -->  B - A
2169   // -A + -B  -->  -(A + B)
2170   if (Value *LHSV = dyn_castNegVal(LHS)) {
2171     if (LHS->getType()->isIntOrIntVector()) {
2172       if (Value *RHSV = dyn_castNegVal(RHS)) {
2173         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2174         InsertNewInstBefore(NewAdd, I);
2175         return BinaryOperator::CreateNeg(NewAdd);
2176       }
2177     }
2178     
2179     return BinaryOperator::CreateSub(RHS, LHSV);
2180   }
2181
2182   // A + -B  -->  A - B
2183   if (!isa<Constant>(RHS))
2184     if (Value *V = dyn_castNegVal(RHS))
2185       return BinaryOperator::CreateSub(LHS, V);
2186
2187
2188   ConstantInt *C2;
2189   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2190     if (X == RHS)   // X*C + X --> X * (C+1)
2191       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2192
2193     // X*C1 + X*C2 --> X * (C1+C2)
2194     ConstantInt *C1;
2195     if (X == dyn_castFoldableMul(RHS, C1))
2196       return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2197   }
2198
2199   // X + X*C --> X * (C+1)
2200   if (dyn_castFoldableMul(RHS, C2) == LHS)
2201     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2202
2203   // X + ~X --> -1   since   ~X = -X-1
2204   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2205     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2206   
2207
2208   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2209   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2210     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2211       return R;
2212   
2213   // A+B --> A|B iff A and B have no bits set in common.
2214   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2215     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2216     APInt LHSKnownOne(IT->getBitWidth(), 0);
2217     APInt LHSKnownZero(IT->getBitWidth(), 0);
2218     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2219     if (LHSKnownZero != 0) {
2220       APInt RHSKnownOne(IT->getBitWidth(), 0);
2221       APInt RHSKnownZero(IT->getBitWidth(), 0);
2222       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2223       
2224       // No bits in common -> bitwise or.
2225       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2226         return BinaryOperator::CreateOr(LHS, RHS);
2227     }
2228   }
2229
2230   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2231   if (I.getType()->isIntOrIntVector()) {
2232     Value *W, *X, *Y, *Z;
2233     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2234         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2235       if (W != Y) {
2236         if (W == Z) {
2237           std::swap(Y, Z);
2238         } else if (Y == X) {
2239           std::swap(W, X);
2240         } else if (X == Z) {
2241           std::swap(Y, Z);
2242           std::swap(W, X);
2243         }
2244       }
2245
2246       if (W == Y) {
2247         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2248                                                             LHS->getName()), I);
2249         return BinaryOperator::CreateMul(W, NewAdd);
2250       }
2251     }
2252   }
2253
2254   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2255     Value *X = 0;
2256     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2257       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2258
2259     // (X & FF00) + xx00  -> (X+xx00) & FF00
2260     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2261       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2262       if (Anded == CRHS) {
2263         // See if all bits from the first bit set in the Add RHS up are included
2264         // in the mask.  First, get the rightmost bit.
2265         const APInt& AddRHSV = CRHS->getValue();
2266
2267         // Form a mask of all bits from the lowest bit added through the top.
2268         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2269
2270         // See if the and mask includes all of these bits.
2271         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2272
2273         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2274           // Okay, the xform is safe.  Insert the new add pronto.
2275           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2276                                                             LHS->getName()), I);
2277           return BinaryOperator::CreateAnd(NewAdd, C2);
2278         }
2279       }
2280     }
2281
2282     // Try to fold constant add into select arguments.
2283     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2284       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2285         return R;
2286   }
2287
2288   // add (cast *A to intptrtype) B -> 
2289   //   cast (GEP (cast *A to i8*) B)  -->  intptrtype
2290   {
2291     CastInst *CI = dyn_cast<CastInst>(LHS);
2292     Value *Other = RHS;
2293     if (!CI) {
2294       CI = dyn_cast<CastInst>(RHS);
2295       Other = LHS;
2296     }
2297     if (CI && CI->getType()->isSized() && 
2298         (CI->getType()->getScalarSizeInBits() ==
2299          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2300         && isa<PointerType>(CI->getOperand(0)->getType())) {
2301       unsigned AS =
2302         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2303       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2304                                       PointerType::get(Type::Int8Ty, AS), I);
2305       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2306       return new PtrToIntInst(I2, CI->getType());
2307     }
2308   }
2309   
2310   // add (select X 0 (sub n A)) A  -->  select X A n
2311   {
2312     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2313     Value *A = RHS;
2314     if (!SI) {
2315       SI = dyn_cast<SelectInst>(RHS);
2316       A = LHS;
2317     }
2318     if (SI && SI->hasOneUse()) {
2319       Value *TV = SI->getTrueValue();
2320       Value *FV = SI->getFalseValue();
2321       Value *N;
2322
2323       // Can we fold the add into the argument of the select?
2324       // We check both true and false select arguments for a matching subtract.
2325       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2326         // Fold the add into the true select value.
2327         return SelectInst::Create(SI->getCondition(), N, A);
2328       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2329         // Fold the add into the false select value.
2330         return SelectInst::Create(SI->getCondition(), A, N);
2331     }
2332   }
2333
2334   // Check for (add (sext x), y), see if we can merge this into an
2335   // integer add followed by a sext.
2336   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2337     // (add (sext x), cst) --> (sext (add x, cst'))
2338     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2339       Constant *CI = 
2340         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2341       if (LHSConv->hasOneUse() &&
2342           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2343           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2344         // Insert the new, smaller add.
2345         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2346                                                         CI, "addconv");
2347         InsertNewInstBefore(NewAdd, I);
2348         return new SExtInst(NewAdd, I.getType());
2349       }
2350     }
2351     
2352     // (add (sext x), (sext y)) --> (sext (add int x, y))
2353     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2354       // Only do this if x/y have the same type, if at last one of them has a
2355       // single use (so we don't increase the number of sexts), and if the
2356       // integer add will not overflow.
2357       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2358           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2359           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2360                                    RHSConv->getOperand(0))) {
2361         // Insert the new integer add.
2362         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2363                                                         RHSConv->getOperand(0),
2364                                                         "addconv");
2365         InsertNewInstBefore(NewAdd, I);
2366         return new SExtInst(NewAdd, I.getType());
2367       }
2368     }
2369   }
2370
2371   return Changed ? &I : 0;
2372 }
2373
2374 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2375   bool Changed = SimplifyCommutative(I);
2376   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2377
2378   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2379     // X + 0 --> X
2380     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2381       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2382                               (I.getType())->getValueAPF()))
2383         return ReplaceInstUsesWith(I, LHS);
2384     }
2385
2386     if (isa<PHINode>(LHS))
2387       if (Instruction *NV = FoldOpIntoPhi(I))
2388         return NV;
2389   }
2390
2391   // -A + B  -->  B - A
2392   // -A + -B  -->  -(A + B)
2393   if (Value *LHSV = dyn_castFNegVal(LHS))
2394     return BinaryOperator::CreateFSub(RHS, LHSV);
2395
2396   // A + -B  -->  A - B
2397   if (!isa<Constant>(RHS))
2398     if (Value *V = dyn_castFNegVal(RHS))
2399       return BinaryOperator::CreateFSub(LHS, V);
2400
2401   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2402   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2403     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2404       return ReplaceInstUsesWith(I, LHS);
2405
2406   // Check for (add double (sitofp x), y), see if we can merge this into an
2407   // integer add followed by a promotion.
2408   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2409     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2410     // ... if the constant fits in the integer value.  This is useful for things
2411     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2412     // requires a constant pool load, and generally allows the add to be better
2413     // instcombined.
2414     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2415       Constant *CI = 
2416       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2417       if (LHSConv->hasOneUse() &&
2418           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2419           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2420         // Insert the new integer add.
2421         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2422                                                         CI, "addconv");
2423         InsertNewInstBefore(NewAdd, I);
2424         return new SIToFPInst(NewAdd, I.getType());
2425       }
2426     }
2427     
2428     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2429     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2430       // Only do this if x/y have the same type, if at last one of them has a
2431       // single use (so we don't increase the number of int->fp conversions),
2432       // and if the integer add will not overflow.
2433       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2434           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2435           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2436                                    RHSConv->getOperand(0))) {
2437         // Insert the new integer add.
2438         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2439                                                         RHSConv->getOperand(0),
2440                                                         "addconv");
2441         InsertNewInstBefore(NewAdd, I);
2442         return new SIToFPInst(NewAdd, I.getType());
2443       }
2444     }
2445   }
2446   
2447   return Changed ? &I : 0;
2448 }
2449
2450 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2451   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2452
2453   if (Op0 == Op1)                        // sub X, X  -> 0
2454     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2455
2456   // If this is a 'B = x-(-A)', change to B = x+A...
2457   if (Value *V = dyn_castNegVal(Op1))
2458     return BinaryOperator::CreateAdd(Op0, V);
2459
2460   if (isa<UndefValue>(Op0))
2461     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2462   if (isa<UndefValue>(Op1))
2463     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2464
2465   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2466     // Replace (-1 - A) with (~A)...
2467     if (C->isAllOnesValue())
2468       return BinaryOperator::CreateNot(Op1);
2469
2470     // C - ~X == X + (1+C)
2471     Value *X = 0;
2472     if (match(Op1, m_Not(m_Value(X))))
2473       return BinaryOperator::CreateAdd(X, AddOne(C));
2474
2475     // -(X >>u 31) -> (X >>s 31)
2476     // -(X >>s 31) -> (X >>u 31)
2477     if (C->isZero()) {
2478       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2479         if (SI->getOpcode() == Instruction::LShr) {
2480           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2481             // Check to see if we are shifting out everything but the sign bit.
2482             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2483                 SI->getType()->getPrimitiveSizeInBits()-1) {
2484               // Ok, the transformation is safe.  Insert AShr.
2485               return BinaryOperator::Create(Instruction::AShr, 
2486                                           SI->getOperand(0), CU, SI->getName());
2487             }
2488           }
2489         }
2490         else if (SI->getOpcode() == Instruction::AShr) {
2491           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2492             // Check to see if we are shifting out everything but the sign bit.
2493             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2494                 SI->getType()->getPrimitiveSizeInBits()-1) {
2495               // Ok, the transformation is safe.  Insert LShr. 
2496               return BinaryOperator::CreateLShr(
2497                                           SI->getOperand(0), CU, SI->getName());
2498             }
2499           }
2500         }
2501       }
2502     }
2503
2504     // Try to fold constant sub into select arguments.
2505     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2506       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2507         return R;
2508   }
2509
2510   if (I.getType() == Type::Int1Ty)
2511     return BinaryOperator::CreateXor(Op0, Op1);
2512
2513   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2514     if (Op1I->getOpcode() == Instruction::Add) {
2515       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2516         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2517       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2518         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2519       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2520         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2521           // C1-(X+C2) --> (C1-C2)-X
2522           return BinaryOperator::CreateSub(ConstantExpr::getSub(CI1, CI2),
2523                                            Op1I->getOperand(0));
2524       }
2525     }
2526
2527     if (Op1I->hasOneUse()) {
2528       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2529       // is not used by anyone else...
2530       //
2531       if (Op1I->getOpcode() == Instruction::Sub) {
2532         // Swap the two operands of the subexpr...
2533         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2534         Op1I->setOperand(0, IIOp1);
2535         Op1I->setOperand(1, IIOp0);
2536
2537         // Create the new top level add instruction...
2538         return BinaryOperator::CreateAdd(Op0, Op1);
2539       }
2540
2541       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2542       //
2543       if (Op1I->getOpcode() == Instruction::And &&
2544           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2545         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2546
2547         Value *NewNot =
2548           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2549         return BinaryOperator::CreateAnd(Op0, NewNot);
2550       }
2551
2552       // 0 - (X sdiv C)  -> (X sdiv -C)
2553       if (Op1I->getOpcode() == Instruction::SDiv)
2554         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2555           if (CSI->isZero())
2556             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2557               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2558                                                ConstantExpr::getNeg(DivRHS));
2559
2560       // X - X*C --> X * (1-C)
2561       ConstantInt *C2 = 0;
2562       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2563         Constant *CP1 = ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2564                                              C2);
2565         return BinaryOperator::CreateMul(Op0, CP1);
2566       }
2567     }
2568   }
2569
2570   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2571     if (Op0I->getOpcode() == Instruction::Add) {
2572       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2573         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2574       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2575         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2576     } else if (Op0I->getOpcode() == Instruction::Sub) {
2577       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2578         return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2579     }
2580   }
2581
2582   ConstantInt *C1;
2583   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2584     if (X == Op1)  // X*C - X --> X * (C-1)
2585       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2586
2587     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2588     if (X == dyn_castFoldableMul(Op1, C2))
2589       return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2590   }
2591   return 0;
2592 }
2593
2594 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2595   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2596
2597   // If this is a 'B = x-(-A)', change to B = x+A...
2598   if (Value *V = dyn_castFNegVal(Op1))
2599     return BinaryOperator::CreateFAdd(Op0, V);
2600
2601   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2602     if (Op1I->getOpcode() == Instruction::FAdd) {
2603       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2604         return BinaryOperator::CreateFNeg(Op1I->getOperand(1), I.getName());
2605       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2606         return BinaryOperator::CreateFNeg(Op1I->getOperand(0), I.getName());
2607     }
2608   }
2609
2610   return 0;
2611 }
2612
2613 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2614 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2615 /// TrueIfSigned if the result of the comparison is true when the input value is
2616 /// signed.
2617 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2618                            bool &TrueIfSigned) {
2619   switch (pred) {
2620   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2621     TrueIfSigned = true;
2622     return RHS->isZero();
2623   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2624     TrueIfSigned = true;
2625     return RHS->isAllOnesValue();
2626   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2627     TrueIfSigned = false;
2628     return RHS->isAllOnesValue();
2629   case ICmpInst::ICMP_UGT:
2630     // True if LHS u> RHS and RHS == high-bit-mask - 1
2631     TrueIfSigned = true;
2632     return RHS->getValue() ==
2633       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2634   case ICmpInst::ICMP_UGE: 
2635     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2636     TrueIfSigned = true;
2637     return RHS->getValue().isSignBit();
2638   default:
2639     return false;
2640   }
2641 }
2642
2643 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2644   bool Changed = SimplifyCommutative(I);
2645   Value *Op0 = I.getOperand(0);
2646
2647   // TODO: If Op1 is undef and Op0 is finite, return zero.
2648   if (!I.getType()->isFPOrFPVector() &&
2649       isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2650     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2651
2652   // Simplify mul instructions with a constant RHS...
2653   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2654     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2655
2656       // ((X << C1)*C2) == (X * (C2 << C1))
2657       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2658         if (SI->getOpcode() == Instruction::Shl)
2659           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2660             return BinaryOperator::CreateMul(SI->getOperand(0),
2661                                              ConstantExpr::getShl(CI, ShOp));
2662
2663       if (CI->isZero())
2664         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2665       if (CI->equalsInt(1))                  // X * 1  == X
2666         return ReplaceInstUsesWith(I, Op0);
2667       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2668         return BinaryOperator::CreateNeg(Op0, I.getName());
2669
2670       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2671       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2672         return BinaryOperator::CreateShl(Op0,
2673                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2674       }
2675     } else if (isa<VectorType>(Op1->getType())) {
2676       // TODO: If Op1 is all zeros and Op0 is all finite, return all zeros.
2677
2678       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2679         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2680           return BinaryOperator::CreateNeg(Op0, I.getName());
2681
2682         // As above, vector X*splat(1.0) -> X in all defined cases.
2683         if (Constant *Splat = Op1V->getSplatValue()) {
2684           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2685             if (CI->equalsInt(1))
2686               return ReplaceInstUsesWith(I, Op0);
2687         }
2688       }
2689     }
2690     
2691     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2692       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2693           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2694         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2695         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2696                                                      Op1, "tmp");
2697         InsertNewInstBefore(Add, I);
2698         Value *C1C2 = ConstantExpr::getMul(Op1, 
2699                                            cast<Constant>(Op0I->getOperand(1)));
2700         return BinaryOperator::CreateAdd(Add, C1C2);
2701         
2702       }
2703
2704     // Try to fold constant mul into select arguments.
2705     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2706       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2707         return R;
2708
2709     if (isa<PHINode>(Op0))
2710       if (Instruction *NV = FoldOpIntoPhi(I))
2711         return NV;
2712   }
2713
2714   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2715     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2716       return BinaryOperator::CreateMul(Op0v, Op1v);
2717
2718   // (X / Y) *  Y = X - (X % Y)
2719   // (X / Y) * -Y = (X % Y) - X
2720   {
2721     Value *Op1 = I.getOperand(1);
2722     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2723     if (!BO ||
2724         (BO->getOpcode() != Instruction::UDiv && 
2725          BO->getOpcode() != Instruction::SDiv)) {
2726       Op1 = Op0;
2727       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2728     }
2729     Value *Neg = dyn_castNegVal(Op1);
2730     if (BO && BO->hasOneUse() &&
2731         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2732         (BO->getOpcode() == Instruction::UDiv ||
2733          BO->getOpcode() == Instruction::SDiv)) {
2734       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2735
2736       Instruction *Rem;
2737       if (BO->getOpcode() == Instruction::UDiv)
2738         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2739       else
2740         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2741
2742       InsertNewInstBefore(Rem, I);
2743       Rem->takeName(BO);
2744
2745       if (Op1BO == Op1)
2746         return BinaryOperator::CreateSub(Op0BO, Rem);
2747       else
2748         return BinaryOperator::CreateSub(Rem, Op0BO);
2749     }
2750   }
2751
2752   if (I.getType() == Type::Int1Ty)
2753     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2754
2755   // If one of the operands of the multiply is a cast from a boolean value, then
2756   // we know the bool is either zero or one, so this is a 'masking' multiply.
2757   // See if we can simplify things based on how the boolean was originally
2758   // formed.
2759   CastInst *BoolCast = 0;
2760   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2761     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2762       BoolCast = CI;
2763   if (!BoolCast)
2764     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2765       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2766         BoolCast = CI;
2767   if (BoolCast) {
2768     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2769       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2770       const Type *SCOpTy = SCIOp0->getType();
2771       bool TIS = false;
2772       
2773       // If the icmp is true iff the sign bit of X is set, then convert this
2774       // multiply into a shift/and combination.
2775       if (isa<ConstantInt>(SCIOp1) &&
2776           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2777           TIS) {
2778         // Shift the X value right to turn it into "all signbits".
2779         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2780                                           SCOpTy->getPrimitiveSizeInBits()-1);
2781         Value *V =
2782           InsertNewInstBefore(
2783             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2784                                             BoolCast->getOperand(0)->getName()+
2785                                             ".mask"), I);
2786
2787         // If the multiply type is not the same as the source type, sign extend
2788         // or truncate to the multiply type.
2789         if (I.getType() != V->getType()) {
2790           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2791           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2792           Instruction::CastOps opcode = 
2793             (SrcBits == DstBits ? Instruction::BitCast : 
2794              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2795           V = InsertCastBefore(opcode, V, I.getType(), I);
2796         }
2797
2798         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2799         return BinaryOperator::CreateAnd(V, OtherOp);
2800       }
2801     }
2802   }
2803
2804   return Changed ? &I : 0;
2805 }
2806
2807 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2808   bool Changed = SimplifyCommutative(I);
2809   Value *Op0 = I.getOperand(0);
2810
2811   // Simplify mul instructions with a constant RHS...
2812   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2813     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2814       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2815       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2816       if (Op1F->isExactlyValue(1.0))
2817         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2818     } else if (isa<VectorType>(Op1->getType())) {
2819       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2820         // As above, vector X*splat(1.0) -> X in all defined cases.
2821         if (Constant *Splat = Op1V->getSplatValue()) {
2822           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2823             if (F->isExactlyValue(1.0))
2824               return ReplaceInstUsesWith(I, Op0);
2825         }
2826       }
2827     }
2828
2829     // Try to fold constant mul into select arguments.
2830     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2831       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2832         return R;
2833
2834     if (isa<PHINode>(Op0))
2835       if (Instruction *NV = FoldOpIntoPhi(I))
2836         return NV;
2837   }
2838
2839   if (Value *Op0v = dyn_castFNegVal(Op0))     // -X * -Y = X*Y
2840     if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
2841       return BinaryOperator::CreateFMul(Op0v, Op1v);
2842
2843   return Changed ? &I : 0;
2844 }
2845
2846 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2847 /// instruction.
2848 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2849   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2850   
2851   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2852   int NonNullOperand = -1;
2853   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2854     if (ST->isNullValue())
2855       NonNullOperand = 2;
2856   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2857   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2858     if (ST->isNullValue())
2859       NonNullOperand = 1;
2860   
2861   if (NonNullOperand == -1)
2862     return false;
2863   
2864   Value *SelectCond = SI->getOperand(0);
2865   
2866   // Change the div/rem to use 'Y' instead of the select.
2867   I.setOperand(1, SI->getOperand(NonNullOperand));
2868   
2869   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2870   // problem.  However, the select, or the condition of the select may have
2871   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2872   // propagate the known value for the select into other uses of it, and
2873   // propagate a known value of the condition into its other users.
2874   
2875   // If the select and condition only have a single use, don't bother with this,
2876   // early exit.
2877   if (SI->use_empty() && SelectCond->hasOneUse())
2878     return true;
2879   
2880   // Scan the current block backward, looking for other uses of SI.
2881   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2882   
2883   while (BBI != BBFront) {
2884     --BBI;
2885     // If we found a call to a function, we can't assume it will return, so
2886     // information from below it cannot be propagated above it.
2887     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2888       break;
2889     
2890     // Replace uses of the select or its condition with the known values.
2891     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2892          I != E; ++I) {
2893       if (*I == SI) {
2894         *I = SI->getOperand(NonNullOperand);
2895         AddToWorkList(BBI);
2896       } else if (*I == SelectCond) {
2897         *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2898                                    ConstantInt::getFalse();
2899         AddToWorkList(BBI);
2900       }
2901     }
2902     
2903     // If we past the instruction, quit looking for it.
2904     if (&*BBI == SI)
2905       SI = 0;
2906     if (&*BBI == SelectCond)
2907       SelectCond = 0;
2908     
2909     // If we ran out of things to eliminate, break out of the loop.
2910     if (SelectCond == 0 && SI == 0)
2911       break;
2912     
2913   }
2914   return true;
2915 }
2916
2917
2918 /// This function implements the transforms on div instructions that work
2919 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2920 /// used by the visitors to those instructions.
2921 /// @brief Transforms common to all three div instructions
2922 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2923   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2924
2925   // undef / X -> 0        for integer.
2926   // undef / X -> undef    for FP (the undef could be a snan).
2927   if (isa<UndefValue>(Op0)) {
2928     if (Op0->getType()->isFPOrFPVector())
2929       return ReplaceInstUsesWith(I, Op0);
2930     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2931   }
2932
2933   // X / undef -> undef
2934   if (isa<UndefValue>(Op1))
2935     return ReplaceInstUsesWith(I, Op1);
2936
2937   return 0;
2938 }
2939
2940 /// This function implements the transforms common to both integer division
2941 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2942 /// division instructions.
2943 /// @brief Common integer divide transforms
2944 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2945   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2946
2947   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2948   if (Op0 == Op1) {
2949     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2950       Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
2951       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2952       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2953     }
2954
2955     Constant *CI = ConstantInt::get(I.getType(), 1);
2956     return ReplaceInstUsesWith(I, CI);
2957   }
2958   
2959   if (Instruction *Common = commonDivTransforms(I))
2960     return Common;
2961   
2962   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2963   // This does not apply for fdiv.
2964   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2965     return &I;
2966
2967   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2968     // div X, 1 == X
2969     if (RHS->equalsInt(1))
2970       return ReplaceInstUsesWith(I, Op0);
2971
2972     // (X / C1) / C2  -> X / (C1*C2)
2973     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2974       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2975         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2976           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2977             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2978           else 
2979             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2980                                           ConstantExpr::getMul(RHS, LHSRHS));
2981         }
2982
2983     if (!RHS->isZero()) { // avoid X udiv 0
2984       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2985         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2986           return R;
2987       if (isa<PHINode>(Op0))
2988         if (Instruction *NV = FoldOpIntoPhi(I))
2989           return NV;
2990     }
2991   }
2992
2993   // 0 / X == 0, we don't need to preserve faults!
2994   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2995     if (LHS->equalsInt(0))
2996       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2997
2998   // It can't be division by zero, hence it must be division by one.
2999   if (I.getType() == Type::Int1Ty)
3000     return ReplaceInstUsesWith(I, Op0);
3001
3002   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3003     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3004       // div X, 1 == X
3005       if (X->isOne())
3006         return ReplaceInstUsesWith(I, Op0);
3007   }
3008
3009   return 0;
3010 }
3011
3012 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3013   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3014
3015   // Handle the integer div common cases
3016   if (Instruction *Common = commonIDivTransforms(I))
3017     return Common;
3018
3019   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3020     // X udiv C^2 -> X >> C
3021     // Check to see if this is an unsigned division with an exact power of 2,
3022     // if so, convert to a right shift.
3023     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3024       return BinaryOperator::CreateLShr(Op0, 
3025                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3026
3027     // X udiv C, where C >= signbit
3028     if (C->getValue().isNegative()) {
3029       Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
3030                                       I);
3031       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3032                                 ConstantInt::get(I.getType(), 1));
3033     }
3034   }
3035
3036   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3037   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3038     if (RHSI->getOpcode() == Instruction::Shl &&
3039         isa<ConstantInt>(RHSI->getOperand(0))) {
3040       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3041       if (C1.isPowerOf2()) {
3042         Value *N = RHSI->getOperand(1);
3043         const Type *NTy = N->getType();
3044         if (uint32_t C2 = C1.logBase2()) {
3045           Constant *C2V = ConstantInt::get(NTy, C2);
3046           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3047         }
3048         return BinaryOperator::CreateLShr(Op0, N);
3049       }
3050     }
3051   }
3052   
3053   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3054   // where C1&C2 are powers of two.
3055   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3056     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3057       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3058         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3059         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3060           // Compute the shift amounts
3061           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3062           // Construct the "on true" case of the select
3063           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3064           Instruction *TSI = BinaryOperator::CreateLShr(
3065                                                  Op0, TC, SI->getName()+".t");
3066           TSI = InsertNewInstBefore(TSI, I);
3067   
3068           // Construct the "on false" case of the select
3069           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3070           Instruction *FSI = BinaryOperator::CreateLShr(
3071                                                  Op0, FC, SI->getName()+".f");
3072           FSI = InsertNewInstBefore(FSI, I);
3073
3074           // construct the select instruction and return it.
3075           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3076         }
3077       }
3078   return 0;
3079 }
3080
3081 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3082   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3083
3084   // Handle the integer div common cases
3085   if (Instruction *Common = commonIDivTransforms(I))
3086     return Common;
3087
3088   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3089     // sdiv X, -1 == -X
3090     if (RHS->isAllOnesValue())
3091       return BinaryOperator::CreateNeg(Op0);
3092   }
3093
3094   // If the sign bits of both operands are zero (i.e. we can prove they are
3095   // unsigned inputs), turn this into a udiv.
3096   if (I.getType()->isInteger()) {
3097     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3098     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3099       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3100       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3101     }
3102   }      
3103   
3104   return 0;
3105 }
3106
3107 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3108   return commonDivTransforms(I);
3109 }
3110
3111 /// This function implements the transforms on rem instructions that work
3112 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3113 /// is used by the visitors to those instructions.
3114 /// @brief Transforms common to all three rem instructions
3115 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3116   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3117
3118   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3119     if (I.getType()->isFPOrFPVector())
3120       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3121     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3122   }
3123   if (isa<UndefValue>(Op1))
3124     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3125
3126   // Handle cases involving: rem X, (select Cond, Y, Z)
3127   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3128     return &I;
3129
3130   return 0;
3131 }
3132
3133 /// This function implements the transforms common to both integer remainder
3134 /// instructions (urem and srem). It is called by the visitors to those integer
3135 /// remainder instructions.
3136 /// @brief Common integer remainder transforms
3137 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3138   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3139
3140   if (Instruction *common = commonRemTransforms(I))
3141     return common;
3142
3143   // 0 % X == 0 for integer, we don't need to preserve faults!
3144   if (Constant *LHS = dyn_cast<Constant>(Op0))
3145     if (LHS->isNullValue())
3146       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3147
3148   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3149     // X % 0 == undef, we don't need to preserve faults!
3150     if (RHS->equalsInt(0))
3151       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3152     
3153     if (RHS->equalsInt(1))  // X % 1 == 0
3154       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3155
3156     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3157       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3158         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3159           return R;
3160       } else if (isa<PHINode>(Op0I)) {
3161         if (Instruction *NV = FoldOpIntoPhi(I))
3162           return NV;
3163       }
3164
3165       // See if we can fold away this rem instruction.
3166       if (SimplifyDemandedInstructionBits(I))
3167         return &I;
3168     }
3169   }
3170
3171   return 0;
3172 }
3173
3174 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3175   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3176
3177   if (Instruction *common = commonIRemTransforms(I))
3178     return common;
3179   
3180   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3181     // X urem C^2 -> X and C
3182     // Check to see if this is an unsigned remainder with an exact power of 2,
3183     // if so, convert to a bitwise and.
3184     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3185       if (C->getValue().isPowerOf2())
3186         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3187   }
3188
3189   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3190     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3191     if (RHSI->getOpcode() == Instruction::Shl &&
3192         isa<ConstantInt>(RHSI->getOperand(0))) {
3193       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3194         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3195         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3196                                                                    "tmp"), I);
3197         return BinaryOperator::CreateAnd(Op0, Add);
3198       }
3199     }
3200   }
3201
3202   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3203   // where C1&C2 are powers of two.
3204   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3205     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3206       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3207         // STO == 0 and SFO == 0 handled above.
3208         if ((STO->getValue().isPowerOf2()) && 
3209             (SFO->getValue().isPowerOf2())) {
3210           Value *TrueAnd = InsertNewInstBefore(
3211             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3212           Value *FalseAnd = InsertNewInstBefore(
3213             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3214           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3215         }
3216       }
3217   }
3218   
3219   return 0;
3220 }
3221
3222 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3223   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3224
3225   // Handle the integer rem common cases
3226   if (Instruction *common = commonIRemTransforms(I))
3227     return common;
3228   
3229   if (Value *RHSNeg = dyn_castNegVal(Op1))
3230     if (!isa<Constant>(RHSNeg) ||
3231         (isa<ConstantInt>(RHSNeg) &&
3232          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3233       // X % -Y -> X % Y
3234       AddUsesToWorkList(I);
3235       I.setOperand(1, RHSNeg);
3236       return &I;
3237     }
3238
3239   // If the sign bits of both operands are zero (i.e. we can prove they are
3240   // unsigned inputs), turn this into a urem.
3241   if (I.getType()->isInteger()) {
3242     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3243     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3244       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3245       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3246     }
3247   }
3248
3249   // If it's a constant vector, flip any negative values positive.
3250   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3251     unsigned VWidth = RHSV->getNumOperands();
3252
3253     bool hasNegative = false;
3254     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3255       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3256         if (RHS->getValue().isNegative())
3257           hasNegative = true;
3258
3259     if (hasNegative) {
3260       std::vector<Constant *> Elts(VWidth);
3261       for (unsigned i = 0; i != VWidth; ++i) {
3262         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3263           if (RHS->getValue().isNegative())
3264             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3265           else
3266             Elts[i] = RHS;
3267         }
3268       }
3269
3270       Constant *NewRHSV = ConstantVector::get(Elts);
3271       if (NewRHSV != RHSV) {
3272         AddUsesToWorkList(I);
3273         I.setOperand(1, NewRHSV);
3274         return &I;
3275       }
3276     }
3277   }
3278
3279   return 0;
3280 }
3281
3282 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3283   return commonRemTransforms(I);
3284 }
3285
3286 // isOneBitSet - Return true if there is exactly one bit set in the specified
3287 // constant.
3288 static bool isOneBitSet(const ConstantInt *CI) {
3289   return CI->getValue().isPowerOf2();
3290 }
3291
3292 // isHighOnes - Return true if the constant is of the form 1+0+.
3293 // This is the same as lowones(~X).
3294 static bool isHighOnes(const ConstantInt *CI) {
3295   return (~CI->getValue() + 1).isPowerOf2();
3296 }
3297
3298 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3299 /// are carefully arranged to allow folding of expressions such as:
3300 ///
3301 ///      (A < B) | (A > B) --> (A != B)
3302 ///
3303 /// Note that this is only valid if the first and second predicates have the
3304 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3305 ///
3306 /// Three bits are used to represent the condition, as follows:
3307 ///   0  A > B
3308 ///   1  A == B
3309 ///   2  A < B
3310 ///
3311 /// <=>  Value  Definition
3312 /// 000     0   Always false
3313 /// 001     1   A >  B
3314 /// 010     2   A == B
3315 /// 011     3   A >= B
3316 /// 100     4   A <  B
3317 /// 101     5   A != B
3318 /// 110     6   A <= B
3319 /// 111     7   Always true
3320 ///  
3321 static unsigned getICmpCode(const ICmpInst *ICI) {
3322   switch (ICI->getPredicate()) {
3323     // False -> 0
3324   case ICmpInst::ICMP_UGT: return 1;  // 001
3325   case ICmpInst::ICMP_SGT: return 1;  // 001
3326   case ICmpInst::ICMP_EQ:  return 2;  // 010
3327   case ICmpInst::ICMP_UGE: return 3;  // 011
3328   case ICmpInst::ICMP_SGE: return 3;  // 011
3329   case ICmpInst::ICMP_ULT: return 4;  // 100
3330   case ICmpInst::ICMP_SLT: return 4;  // 100
3331   case ICmpInst::ICMP_NE:  return 5;  // 101
3332   case ICmpInst::ICMP_ULE: return 6;  // 110
3333   case ICmpInst::ICMP_SLE: return 6;  // 110
3334     // True -> 7
3335   default:
3336     assert(0 && "Invalid ICmp predicate!");
3337     return 0;
3338   }
3339 }
3340
3341 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3342 /// predicate into a three bit mask. It also returns whether it is an ordered
3343 /// predicate by reference.
3344 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3345   isOrdered = false;
3346   switch (CC) {
3347   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3348   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3349   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3350   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3351   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3352   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3353   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3354   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3355   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3356   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3357   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3358   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3359   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3360   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3361     // True -> 7
3362   default:
3363     // Not expecting FCMP_FALSE and FCMP_TRUE;
3364     assert(0 && "Unexpected FCmp predicate!");
3365     return 0;
3366   }
3367 }
3368
3369 /// getICmpValue - This is the complement of getICmpCode, which turns an
3370 /// opcode and two operands into either a constant true or false, or a brand 
3371 /// new ICmp instruction. The sign is passed in to determine which kind
3372 /// of predicate to use in the new icmp instruction.
3373 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3374   switch (code) {
3375   default: assert(0 && "Illegal ICmp code!");
3376   case  0: return ConstantInt::getFalse();
3377   case  1: 
3378     if (sign)
3379       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3380     else
3381       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3382   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3383   case  3: 
3384     if (sign)
3385       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3386     else
3387       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3388   case  4: 
3389     if (sign)
3390       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3391     else
3392       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3393   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3394   case  6: 
3395     if (sign)
3396       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3397     else
3398       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3399   case  7: return ConstantInt::getTrue();
3400   }
3401 }
3402
3403 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3404 /// opcode and two operands into either a FCmp instruction. isordered is passed
3405 /// in to determine which kind of predicate to use in the new fcmp instruction.
3406 static Value *getFCmpValue(bool isordered, unsigned code,
3407                            Value *LHS, Value *RHS) {
3408   switch (code) {
3409   default: assert(0 && "Illegal FCmp code!");
3410   case  0:
3411     if (isordered)
3412       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3413     else
3414       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3415   case  1: 
3416     if (isordered)
3417       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3418     else
3419       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3420   case  2: 
3421     if (isordered)
3422       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3423     else
3424       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3425   case  3: 
3426     if (isordered)
3427       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3428     else
3429       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3430   case  4: 
3431     if (isordered)
3432       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3433     else
3434       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3435   case  5: 
3436     if (isordered)
3437       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3438     else
3439       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3440   case  6: 
3441     if (isordered)
3442       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3443     else
3444       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3445   case  7: return ConstantInt::getTrue();
3446   }
3447 }
3448
3449 /// PredicatesFoldable - Return true if both predicates match sign or if at
3450 /// least one of them is an equality comparison (which is signless).
3451 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3452   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3453          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3454          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3455 }
3456
3457 namespace { 
3458 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3459 struct FoldICmpLogical {
3460   InstCombiner &IC;
3461   Value *LHS, *RHS;
3462   ICmpInst::Predicate pred;
3463   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3464     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3465       pred(ICI->getPredicate()) {}
3466   bool shouldApply(Value *V) const {
3467     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3468       if (PredicatesFoldable(pred, ICI->getPredicate()))
3469         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3470                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3471     return false;
3472   }
3473   Instruction *apply(Instruction &Log) const {
3474     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3475     if (ICI->getOperand(0) != LHS) {
3476       assert(ICI->getOperand(1) == LHS);
3477       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3478     }
3479
3480     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3481     unsigned LHSCode = getICmpCode(ICI);
3482     unsigned RHSCode = getICmpCode(RHSICI);
3483     unsigned Code;
3484     switch (Log.getOpcode()) {
3485     case Instruction::And: Code = LHSCode & RHSCode; break;
3486     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3487     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3488     default: assert(0 && "Illegal logical opcode!"); return 0;
3489     }
3490
3491     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3492                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3493       
3494     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3495     if (Instruction *I = dyn_cast<Instruction>(RV))
3496       return I;
3497     // Otherwise, it's a constant boolean value...
3498     return IC.ReplaceInstUsesWith(Log, RV);
3499   }
3500 };
3501 } // end anonymous namespace
3502
3503 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3504 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3505 // guaranteed to be a binary operator.
3506 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3507                                     ConstantInt *OpRHS,
3508                                     ConstantInt *AndRHS,
3509                                     BinaryOperator &TheAnd) {
3510   Value *X = Op->getOperand(0);
3511   Constant *Together = 0;
3512   if (!Op->isShift())
3513     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3514
3515   switch (Op->getOpcode()) {
3516   case Instruction::Xor:
3517     if (Op->hasOneUse()) {
3518       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3519       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3520       InsertNewInstBefore(And, TheAnd);
3521       And->takeName(Op);
3522       return BinaryOperator::CreateXor(And, Together);
3523     }
3524     break;
3525   case Instruction::Or:
3526     if (Together == AndRHS) // (X | C) & C --> C
3527       return ReplaceInstUsesWith(TheAnd, AndRHS);
3528
3529     if (Op->hasOneUse() && Together != OpRHS) {
3530       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3531       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3532       InsertNewInstBefore(Or, TheAnd);
3533       Or->takeName(Op);
3534       return BinaryOperator::CreateAnd(Or, AndRHS);
3535     }
3536     break;
3537   case Instruction::Add:
3538     if (Op->hasOneUse()) {
3539       // Adding a one to a single bit bit-field should be turned into an XOR
3540       // of the bit.  First thing to check is to see if this AND is with a
3541       // single bit constant.
3542       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3543
3544       // If there is only one bit set...
3545       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3546         // Ok, at this point, we know that we are masking the result of the
3547         // ADD down to exactly one bit.  If the constant we are adding has
3548         // no bits set below this bit, then we can eliminate the ADD.
3549         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3550
3551         // Check to see if any bits below the one bit set in AndRHSV are set.
3552         if ((AddRHS & (AndRHSV-1)) == 0) {
3553           // If not, the only thing that can effect the output of the AND is
3554           // the bit specified by AndRHSV.  If that bit is set, the effect of
3555           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3556           // no effect.
3557           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3558             TheAnd.setOperand(0, X);
3559             return &TheAnd;
3560           } else {
3561             // Pull the XOR out of the AND.
3562             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3563             InsertNewInstBefore(NewAnd, TheAnd);
3564             NewAnd->takeName(Op);
3565             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3566           }
3567         }
3568       }
3569     }
3570     break;
3571
3572   case Instruction::Shl: {
3573     // We know that the AND will not produce any of the bits shifted in, so if
3574     // the anded constant includes them, clear them now!
3575     //
3576     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3577     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3578     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3579     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3580
3581     if (CI->getValue() == ShlMask) { 
3582     // Masking out bits that the shift already masks
3583       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3584     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3585       TheAnd.setOperand(1, CI);
3586       return &TheAnd;
3587     }
3588     break;
3589   }
3590   case Instruction::LShr:
3591   {
3592     // We know that the AND will not produce any of the bits shifted in, so if
3593     // the anded constant includes them, clear them now!  This only applies to
3594     // unsigned shifts, because a signed shr may bring in set bits!
3595     //
3596     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3597     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3598     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3599     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3600
3601     if (CI->getValue() == ShrMask) {   
3602     // Masking out bits that the shift already masks.
3603       return ReplaceInstUsesWith(TheAnd, Op);
3604     } else if (CI != AndRHS) {
3605       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3606       return &TheAnd;
3607     }
3608     break;
3609   }
3610   case Instruction::AShr:
3611     // Signed shr.
3612     // See if this is shifting in some sign extension, then masking it out
3613     // with an and.
3614     if (Op->hasOneUse()) {
3615       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3616       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3617       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3618       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3619       if (C == AndRHS) {          // Masking out bits shifted in.
3620         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3621         // Make the argument unsigned.
3622         Value *ShVal = Op->getOperand(0);
3623         ShVal = InsertNewInstBefore(
3624             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3625                                    Op->getName()), TheAnd);
3626         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3627       }
3628     }
3629     break;
3630   }
3631   return 0;
3632 }
3633
3634
3635 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3636 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3637 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3638 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3639 /// insert new instructions.
3640 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3641                                            bool isSigned, bool Inside, 
3642                                            Instruction &IB) {
3643   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3644             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3645          "Lo is not <= Hi in range emission code!");
3646     
3647   if (Inside) {
3648     if (Lo == Hi)  // Trivially false.
3649       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3650
3651     // V >= Min && V < Hi --> V < Hi
3652     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3653       ICmpInst::Predicate pred = (isSigned ? 
3654         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3655       return new ICmpInst(pred, V, Hi);
3656     }
3657
3658     // Emit V-Lo <u Hi-Lo
3659     Constant *NegLo = ConstantExpr::getNeg(Lo);
3660     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3661     InsertNewInstBefore(Add, IB);
3662     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3663     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3664   }
3665
3666   if (Lo == Hi)  // Trivially true.
3667     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3668
3669   // V < Min || V >= Hi -> V > Hi-1
3670   Hi = SubOne(cast<ConstantInt>(Hi));
3671   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3672     ICmpInst::Predicate pred = (isSigned ? 
3673         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3674     return new ICmpInst(pred, V, Hi);
3675   }
3676
3677   // Emit V-Lo >u Hi-1-Lo
3678   // Note that Hi has already had one subtracted from it, above.
3679   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3680   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3681   InsertNewInstBefore(Add, IB);
3682   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3683   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3684 }
3685
3686 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3687 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3688 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3689 // not, since all 1s are not contiguous.
3690 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3691   const APInt& V = Val->getValue();
3692   uint32_t BitWidth = Val->getType()->getBitWidth();
3693   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3694
3695   // look for the first zero bit after the run of ones
3696   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3697   // look for the first non-zero bit
3698   ME = V.getActiveBits(); 
3699   return true;
3700 }
3701
3702 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3703 /// where isSub determines whether the operator is a sub.  If we can fold one of
3704 /// the following xforms:
3705 /// 
3706 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3707 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3708 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3709 ///
3710 /// return (A +/- B).
3711 ///
3712 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3713                                         ConstantInt *Mask, bool isSub,
3714                                         Instruction &I) {
3715   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3716   if (!LHSI || LHSI->getNumOperands() != 2 ||
3717       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3718
3719   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3720
3721   switch (LHSI->getOpcode()) {
3722   default: return 0;
3723   case Instruction::And:
3724     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3725       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3726       if ((Mask->getValue().countLeadingZeros() + 
3727            Mask->getValue().countPopulation()) == 
3728           Mask->getValue().getBitWidth())
3729         break;
3730
3731       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3732       // part, we don't need any explicit masks to take them out of A.  If that
3733       // is all N is, ignore it.
3734       uint32_t MB = 0, ME = 0;
3735       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3736         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3737         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3738         if (MaskedValueIsZero(RHS, Mask))
3739           break;
3740       }
3741     }
3742     return 0;
3743   case Instruction::Or:
3744   case Instruction::Xor:
3745     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3746     if ((Mask->getValue().countLeadingZeros() + 
3747          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3748         && ConstantExpr::getAnd(N, Mask)->isNullValue())
3749       break;
3750     return 0;
3751   }
3752   
3753   Instruction *New;
3754   if (isSub)
3755     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3756   else
3757     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3758   return InsertNewInstBefore(New, I);
3759 }
3760
3761 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3762 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3763                                           ICmpInst *LHS, ICmpInst *RHS) {
3764   Value *Val, *Val2;
3765   ConstantInt *LHSCst, *RHSCst;
3766   ICmpInst::Predicate LHSCC, RHSCC;
3767   
3768   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3769   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
3770       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
3771     return 0;
3772   
3773   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3774   // where C is a power of 2
3775   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3776       LHSCst->getValue().isPowerOf2()) {
3777     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3778     InsertNewInstBefore(NewOr, I);
3779     return new ICmpInst(LHSCC, NewOr, LHSCst);
3780   }
3781   
3782   // From here on, we only handle:
3783   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3784   if (Val != Val2) return 0;
3785   
3786   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3787   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3788       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3789       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3790       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3791     return 0;
3792   
3793   // We can't fold (ugt x, C) & (sgt x, C2).
3794   if (!PredicatesFoldable(LHSCC, RHSCC))
3795     return 0;
3796     
3797   // Ensure that the larger constant is on the RHS.
3798   bool ShouldSwap;
3799   if (ICmpInst::isSignedPredicate(LHSCC) ||
3800       (ICmpInst::isEquality(LHSCC) && 
3801        ICmpInst::isSignedPredicate(RHSCC)))
3802     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3803   else
3804     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3805     
3806   if (ShouldSwap) {
3807     std::swap(LHS, RHS);
3808     std::swap(LHSCst, RHSCst);
3809     std::swap(LHSCC, RHSCC);
3810   }
3811
3812   // At this point, we know we have have two icmp instructions
3813   // comparing a value against two constants and and'ing the result
3814   // together.  Because of the above check, we know that we only have
3815   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3816   // (from the FoldICmpLogical check above), that the two constants 
3817   // are not equal and that the larger constant is on the RHS
3818   assert(LHSCst != RHSCst && "Compares not folded above?");
3819
3820   switch (LHSCC) {
3821   default: assert(0 && "Unknown integer condition code!");
3822   case ICmpInst::ICMP_EQ:
3823     switch (RHSCC) {
3824     default: assert(0 && "Unknown integer condition code!");
3825     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3826     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3827     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3828       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3829     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3830     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3831     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3832       return ReplaceInstUsesWith(I, LHS);
3833     }
3834   case ICmpInst::ICMP_NE:
3835     switch (RHSCC) {
3836     default: assert(0 && "Unknown integer condition code!");
3837     case ICmpInst::ICMP_ULT:
3838       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3839         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3840       break;                        // (X != 13 & X u< 15) -> no change
3841     case ICmpInst::ICMP_SLT:
3842       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3843         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3844       break;                        // (X != 13 & X s< 15) -> no change
3845     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3846     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3847     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3848       return ReplaceInstUsesWith(I, RHS);
3849     case ICmpInst::ICMP_NE:
3850       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3851         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3852         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3853                                                      Val->getName()+".off");
3854         InsertNewInstBefore(Add, I);
3855         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3856                             ConstantInt::get(Add->getType(), 1));
3857       }
3858       break;                        // (X != 13 & X != 15) -> no change
3859     }
3860     break;
3861   case ICmpInst::ICMP_ULT:
3862     switch (RHSCC) {
3863     default: assert(0 && "Unknown integer condition code!");
3864     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3865     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3866       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3867     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3868       break;
3869     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3870     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3871       return ReplaceInstUsesWith(I, LHS);
3872     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3873       break;
3874     }
3875     break;
3876   case ICmpInst::ICMP_SLT:
3877     switch (RHSCC) {
3878     default: assert(0 && "Unknown integer condition code!");
3879     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3880     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3881       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3882     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3883       break;
3884     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3885     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3886       return ReplaceInstUsesWith(I, LHS);
3887     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3888       break;
3889     }
3890     break;
3891   case ICmpInst::ICMP_UGT:
3892     switch (RHSCC) {
3893     default: assert(0 && "Unknown integer condition code!");
3894     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3895     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3896       return ReplaceInstUsesWith(I, RHS);
3897     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3898       break;
3899     case ICmpInst::ICMP_NE:
3900       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3901         return new ICmpInst(LHSCC, Val, RHSCst);
3902       break;                        // (X u> 13 & X != 15) -> no change
3903     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3904       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3905     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3906       break;
3907     }
3908     break;
3909   case ICmpInst::ICMP_SGT:
3910     switch (RHSCC) {
3911     default: assert(0 && "Unknown integer condition code!");
3912     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3913     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3914       return ReplaceInstUsesWith(I, RHS);
3915     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3916       break;
3917     case ICmpInst::ICMP_NE:
3918       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3919         return new ICmpInst(LHSCC, Val, RHSCst);
3920       break;                        // (X s> 13 & X != 15) -> no change
3921     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3922       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3923     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3924       break;
3925     }
3926     break;
3927   }
3928  
3929   return 0;
3930 }
3931
3932
3933 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3934   bool Changed = SimplifyCommutative(I);
3935   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3936
3937   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3938     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3939
3940   // and X, X = X
3941   if (Op0 == Op1)
3942     return ReplaceInstUsesWith(I, Op1);
3943
3944   // See if we can simplify any instructions used by the instruction whose sole 
3945   // purpose is to compute bits we don't care about.
3946   if (SimplifyDemandedInstructionBits(I))
3947     return &I;
3948   if (isa<VectorType>(I.getType())) {
3949     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3950       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3951         return ReplaceInstUsesWith(I, I.getOperand(0));
3952     } else if (isa<ConstantAggregateZero>(Op1)) {
3953       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3954     }
3955   }
3956
3957   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3958     const APInt& AndRHSMask = AndRHS->getValue();
3959     APInt NotAndRHS(~AndRHSMask);
3960
3961     // Optimize a variety of ((val OP C1) & C2) combinations...
3962     if (isa<BinaryOperator>(Op0)) {
3963       Instruction *Op0I = cast<Instruction>(Op0);
3964       Value *Op0LHS = Op0I->getOperand(0);
3965       Value *Op0RHS = Op0I->getOperand(1);
3966       switch (Op0I->getOpcode()) {
3967       case Instruction::Xor:
3968       case Instruction::Or:
3969         // If the mask is only needed on one incoming arm, push it up.
3970         if (Op0I->hasOneUse()) {
3971           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3972             // Not masking anything out for the LHS, move to RHS.
3973             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3974                                                    Op0RHS->getName()+".masked");
3975             InsertNewInstBefore(NewRHS, I);
3976             return BinaryOperator::Create(
3977                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3978           }
3979           if (!isa<Constant>(Op0RHS) &&
3980               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3981             // Not masking anything out for the RHS, move to LHS.
3982             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3983                                                    Op0LHS->getName()+".masked");
3984             InsertNewInstBefore(NewLHS, I);
3985             return BinaryOperator::Create(
3986                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3987           }
3988         }
3989
3990         break;
3991       case Instruction::Add:
3992         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3993         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3994         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3995         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3996           return BinaryOperator::CreateAnd(V, AndRHS);
3997         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3998           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
3999         break;
4000
4001       case Instruction::Sub:
4002         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4003         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4004         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4005         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4006           return BinaryOperator::CreateAnd(V, AndRHS);
4007
4008         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4009         // has 1's for all bits that the subtraction with A might affect.
4010         if (Op0I->hasOneUse()) {
4011           uint32_t BitWidth = AndRHSMask.getBitWidth();
4012           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4013           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4014
4015           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4016           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4017               MaskedValueIsZero(Op0LHS, Mask)) {
4018             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
4019             InsertNewInstBefore(NewNeg, I);
4020             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4021           }
4022         }
4023         break;
4024
4025       case Instruction::Shl:
4026       case Instruction::LShr:
4027         // (1 << x) & 1 --> zext(x == 0)
4028         // (1 >> x) & 1 --> zext(x == 0)
4029         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4030           Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
4031                                            Constant::getNullValue(I.getType()));
4032           InsertNewInstBefore(NewICmp, I);
4033           return new ZExtInst(NewICmp, I.getType());
4034         }
4035         break;
4036       }
4037
4038       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4039         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4040           return Res;
4041     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4042       // If this is an integer truncation or change from signed-to-unsigned, and
4043       // if the source is an and/or with immediate, transform it.  This
4044       // frequently occurs for bitfield accesses.
4045       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4046         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4047             CastOp->getNumOperands() == 2)
4048           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4049             if (CastOp->getOpcode() == Instruction::And) {
4050               // Change: and (cast (and X, C1) to T), C2
4051               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4052               // This will fold the two constants together, which may allow 
4053               // other simplifications.
4054               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4055                 CastOp->getOperand(0), I.getType(), 
4056                 CastOp->getName()+".shrunk");
4057               NewCast = InsertNewInstBefore(NewCast, I);
4058               // trunc_or_bitcast(C1)&C2
4059               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4060               C3 = ConstantExpr::getAnd(C3, AndRHS);
4061               return BinaryOperator::CreateAnd(NewCast, C3);
4062             } else if (CastOp->getOpcode() == Instruction::Or) {
4063               // Change: and (cast (or X, C1) to T), C2
4064               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4065               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4066               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
4067                 return ReplaceInstUsesWith(I, AndRHS);
4068             }
4069           }
4070       }
4071     }
4072
4073     // Try to fold constant and into select arguments.
4074     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4075       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4076         return R;
4077     if (isa<PHINode>(Op0))
4078       if (Instruction *NV = FoldOpIntoPhi(I))
4079         return NV;
4080   }
4081
4082   Value *Op0NotVal = dyn_castNotVal(Op0);
4083   Value *Op1NotVal = dyn_castNotVal(Op1);
4084
4085   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4086     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4087
4088   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4089   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4090     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4091                                                I.getName()+".demorgan");
4092     InsertNewInstBefore(Or, I);
4093     return BinaryOperator::CreateNot(Or);
4094   }
4095   
4096   {
4097     Value *A = 0, *B = 0, *C = 0, *D = 0;
4098     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4099       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4100         return ReplaceInstUsesWith(I, Op1);
4101     
4102       // (A|B) & ~(A&B) -> A^B
4103       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4104         if ((A == C && B == D) || (A == D && B == C))
4105           return BinaryOperator::CreateXor(A, B);
4106       }
4107     }
4108     
4109     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4110       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4111         return ReplaceInstUsesWith(I, Op0);
4112
4113       // ~(A&B) & (A|B) -> A^B
4114       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4115         if ((A == C && B == D) || (A == D && B == C))
4116           return BinaryOperator::CreateXor(A, B);
4117       }
4118     }
4119     
4120     if (Op0->hasOneUse() &&
4121         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4122       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4123         I.swapOperands();     // Simplify below
4124         std::swap(Op0, Op1);
4125       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4126         cast<BinaryOperator>(Op0)->swapOperands();
4127         I.swapOperands();     // Simplify below
4128         std::swap(Op0, Op1);
4129       }
4130     }
4131
4132     if (Op1->hasOneUse() &&
4133         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4134       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4135         cast<BinaryOperator>(Op1)->swapOperands();
4136         std::swap(A, B);
4137       }
4138       if (A == Op0) {                                // A&(A^B) -> A & ~B
4139         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
4140         InsertNewInstBefore(NotB, I);
4141         return BinaryOperator::CreateAnd(A, NotB);
4142       }
4143     }
4144
4145     // (A&((~A)|B)) -> A&B
4146     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4147         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4148       return BinaryOperator::CreateAnd(A, Op1);
4149     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4150         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4151       return BinaryOperator::CreateAnd(A, Op0);
4152   }
4153   
4154   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4155     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4156     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4157       return R;
4158
4159     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4160       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4161         return Res;
4162   }
4163
4164   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4165   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4166     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4167       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4168         const Type *SrcTy = Op0C->getOperand(0)->getType();
4169         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4170             // Only do this if the casts both really cause code to be generated.
4171             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4172                               I.getType(), TD) &&
4173             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4174                               I.getType(), TD)) {
4175           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4176                                                          Op1C->getOperand(0),
4177                                                          I.getName());
4178           InsertNewInstBefore(NewOp, I);
4179           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4180         }
4181       }
4182     
4183   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4184   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4185     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4186       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4187           SI0->getOperand(1) == SI1->getOperand(1) &&
4188           (SI0->hasOneUse() || SI1->hasOneUse())) {
4189         Instruction *NewOp =
4190           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4191                                                         SI1->getOperand(0),
4192                                                         SI0->getName()), I);
4193         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4194                                       SI1->getOperand(1));
4195       }
4196   }
4197
4198   // If and'ing two fcmp, try combine them into one.
4199   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4200     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4201       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4202           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4203         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4204         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4205           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4206             // If either of the constants are nans, then the whole thing returns
4207             // false.
4208             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4209               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4210             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4211                                 RHS->getOperand(0));
4212           }
4213       } else {
4214         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4215         FCmpInst::Predicate Op0CC, Op1CC;
4216         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4217             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4218           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4219             // Swap RHS operands to match LHS.
4220             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4221             std::swap(Op1LHS, Op1RHS);
4222           }
4223           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4224             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4225             if (Op0CC == Op1CC)
4226               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4227             else if (Op0CC == FCmpInst::FCMP_FALSE ||
4228                      Op1CC == FCmpInst::FCMP_FALSE)
4229               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4230             else if (Op0CC == FCmpInst::FCMP_TRUE)
4231               return ReplaceInstUsesWith(I, Op1);
4232             else if (Op1CC == FCmpInst::FCMP_TRUE)
4233               return ReplaceInstUsesWith(I, Op0);
4234             bool Op0Ordered;
4235             bool Op1Ordered;
4236             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4237             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4238             if (Op1Pred == 0) {
4239               std::swap(Op0, Op1);
4240               std::swap(Op0Pred, Op1Pred);
4241               std::swap(Op0Ordered, Op1Ordered);
4242             }
4243             if (Op0Pred == 0) {
4244               // uno && ueq -> uno && (uno || eq) -> ueq
4245               // ord && olt -> ord && (ord && lt) -> olt
4246               if (Op0Ordered == Op1Ordered)
4247                 return ReplaceInstUsesWith(I, Op1);
4248               // uno && oeq -> uno && (ord && eq) -> false
4249               // uno && ord -> false
4250               if (!Op0Ordered)
4251                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4252               // ord && ueq -> ord && (uno || eq) -> oeq
4253               return cast<Instruction>(getFCmpValue(true, Op1Pred,
4254                                                     Op0LHS, Op0RHS));
4255             }
4256           }
4257         }
4258       }
4259     }
4260   }
4261
4262   return Changed ? &I : 0;
4263 }
4264
4265 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4266 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4267 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4268 /// the expression came from the corresponding "byte swapped" byte in some other
4269 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4270 /// we know that the expression deposits the low byte of %X into the high byte
4271 /// of the bswap result and that all other bytes are zero.  This expression is
4272 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4273 /// match.
4274 ///
4275 /// This function returns true if the match was unsuccessful and false if so.
4276 /// On entry to the function the "OverallLeftShift" is a signed integer value
4277 /// indicating the number of bytes that the subexpression is later shifted.  For
4278 /// example, if the expression is later right shifted by 16 bits, the
4279 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4280 /// byte of ByteValues is actually being set.
4281 ///
4282 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4283 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4284 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4285 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4286 /// always in the local (OverallLeftShift) coordinate space.
4287 ///
4288 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4289                               SmallVector<Value*, 8> &ByteValues) {
4290   if (Instruction *I = dyn_cast<Instruction>(V)) {
4291     // If this is an or instruction, it may be an inner node of the bswap.
4292     if (I->getOpcode() == Instruction::Or) {
4293       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4294                                ByteValues) ||
4295              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4296                                ByteValues);
4297     }
4298   
4299     // If this is a logical shift by a constant multiple of 8, recurse with
4300     // OverallLeftShift and ByteMask adjusted.
4301     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4302       unsigned ShAmt = 
4303         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4304       // Ensure the shift amount is defined and of a byte value.
4305       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4306         return true;
4307
4308       unsigned ByteShift = ShAmt >> 3;
4309       if (I->getOpcode() == Instruction::Shl) {
4310         // X << 2 -> collect(X, +2)
4311         OverallLeftShift += ByteShift;
4312         ByteMask >>= ByteShift;
4313       } else {
4314         // X >>u 2 -> collect(X, -2)
4315         OverallLeftShift -= ByteShift;
4316         ByteMask <<= ByteShift;
4317         ByteMask &= (~0U >> (32-ByteValues.size()));
4318       }
4319
4320       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4321       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4322
4323       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4324                                ByteValues);
4325     }
4326
4327     // If this is a logical 'and' with a mask that clears bytes, clear the
4328     // corresponding bytes in ByteMask.
4329     if (I->getOpcode() == Instruction::And &&
4330         isa<ConstantInt>(I->getOperand(1))) {
4331       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4332       unsigned NumBytes = ByteValues.size();
4333       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4334       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4335       
4336       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4337         // If this byte is masked out by a later operation, we don't care what
4338         // the and mask is.
4339         if ((ByteMask & (1 << i)) == 0)
4340           continue;
4341         
4342         // If the AndMask is all zeros for this byte, clear the bit.
4343         APInt MaskB = AndMask & Byte;
4344         if (MaskB == 0) {
4345           ByteMask &= ~(1U << i);
4346           continue;
4347         }
4348         
4349         // If the AndMask is not all ones for this byte, it's not a bytezap.
4350         if (MaskB != Byte)
4351           return true;
4352
4353         // Otherwise, this byte is kept.
4354       }
4355
4356       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4357                                ByteValues);
4358     }
4359   }
4360   
4361   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4362   // the input value to the bswap.  Some observations: 1) if more than one byte
4363   // is demanded from this input, then it could not be successfully assembled
4364   // into a byteswap.  At least one of the two bytes would not be aligned with
4365   // their ultimate destination.
4366   if (!isPowerOf2_32(ByteMask)) return true;
4367   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4368   
4369   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4370   // is demanded, it needs to go into byte 0 of the result.  This means that the
4371   // byte needs to be shifted until it lands in the right byte bucket.  The
4372   // shift amount depends on the position: if the byte is coming from the high
4373   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4374   // low part, it must be shifted left.
4375   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4376   if (InputByteNo < ByteValues.size()/2) {
4377     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4378       return true;
4379   } else {
4380     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4381       return true;
4382   }
4383   
4384   // If the destination byte value is already defined, the values are or'd
4385   // together, which isn't a bswap (unless it's an or of the same bits).
4386   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4387     return true;
4388   ByteValues[DestByteNo] = V;
4389   return false;
4390 }
4391
4392 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4393 /// If so, insert the new bswap intrinsic and return it.
4394 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4395   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4396   if (!ITy || ITy->getBitWidth() % 16 || 
4397       // ByteMask only allows up to 32-byte values.
4398       ITy->getBitWidth() > 32*8) 
4399     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4400   
4401   /// ByteValues - For each byte of the result, we keep track of which value
4402   /// defines each byte.
4403   SmallVector<Value*, 8> ByteValues;
4404   ByteValues.resize(ITy->getBitWidth()/8);
4405     
4406   // Try to find all the pieces corresponding to the bswap.
4407   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4408   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4409     return 0;
4410   
4411   // Check to see if all of the bytes come from the same value.
4412   Value *V = ByteValues[0];
4413   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4414   
4415   // Check to make sure that all of the bytes come from the same value.
4416   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4417     if (ByteValues[i] != V)
4418       return 0;
4419   const Type *Tys[] = { ITy };
4420   Module *M = I.getParent()->getParent()->getParent();
4421   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4422   return CallInst::Create(F, V);
4423 }
4424
4425 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4426 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4427 /// we can simplify this expression to "cond ? C : D or B".
4428 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4429                                          Value *C, Value *D) {
4430   // If A is not a select of -1/0, this cannot match.
4431   Value *Cond = 0;
4432   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4433     return 0;
4434
4435   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4436   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4437     return SelectInst::Create(Cond, C, B);
4438   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4439     return SelectInst::Create(Cond, C, B);
4440   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4441   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4442     return SelectInst::Create(Cond, C, D);
4443   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4444     return SelectInst::Create(Cond, C, D);
4445   return 0;
4446 }
4447
4448 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4449 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4450                                          ICmpInst *LHS, ICmpInst *RHS) {
4451   Value *Val, *Val2;
4452   ConstantInt *LHSCst, *RHSCst;
4453   ICmpInst::Predicate LHSCC, RHSCC;
4454   
4455   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4456   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4457       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4458     return 0;
4459   
4460   // From here on, we only handle:
4461   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4462   if (Val != Val2) return 0;
4463   
4464   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4465   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4466       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4467       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4468       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4469     return 0;
4470   
4471   // We can't fold (ugt x, C) | (sgt x, C2).
4472   if (!PredicatesFoldable(LHSCC, RHSCC))
4473     return 0;
4474   
4475   // Ensure that the larger constant is on the RHS.
4476   bool ShouldSwap;
4477   if (ICmpInst::isSignedPredicate(LHSCC) ||
4478       (ICmpInst::isEquality(LHSCC) && 
4479        ICmpInst::isSignedPredicate(RHSCC)))
4480     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4481   else
4482     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4483   
4484   if (ShouldSwap) {
4485     std::swap(LHS, RHS);
4486     std::swap(LHSCst, RHSCst);
4487     std::swap(LHSCC, RHSCC);
4488   }
4489   
4490   // At this point, we know we have have two icmp instructions
4491   // comparing a value against two constants and or'ing the result
4492   // together.  Because of the above check, we know that we only have
4493   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4494   // FoldICmpLogical check above), that the two constants are not
4495   // equal.
4496   assert(LHSCst != RHSCst && "Compares not folded above?");
4497
4498   switch (LHSCC) {
4499   default: assert(0 && "Unknown integer condition code!");
4500   case ICmpInst::ICMP_EQ:
4501     switch (RHSCC) {
4502     default: assert(0 && "Unknown integer condition code!");
4503     case ICmpInst::ICMP_EQ:
4504       if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4505         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4506         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4507                                                      Val->getName()+".off");
4508         InsertNewInstBefore(Add, I);
4509         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4510         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4511       }
4512       break;                         // (X == 13 | X == 15) -> no change
4513     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4514     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4515       break;
4516     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4517     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4518     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4519       return ReplaceInstUsesWith(I, RHS);
4520     }
4521     break;
4522   case ICmpInst::ICMP_NE:
4523     switch (RHSCC) {
4524     default: assert(0 && "Unknown integer condition code!");
4525     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4526     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4527     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4528       return ReplaceInstUsesWith(I, LHS);
4529     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4530     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4531     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4532       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4533     }
4534     break;
4535   case ICmpInst::ICMP_ULT:
4536     switch (RHSCC) {
4537     default: assert(0 && "Unknown integer condition code!");
4538     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4539       break;
4540     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4541       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4542       // this can cause overflow.
4543       if (RHSCst->isMaxValue(false))
4544         return ReplaceInstUsesWith(I, LHS);
4545       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4546     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4547       break;
4548     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4549     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4550       return ReplaceInstUsesWith(I, RHS);
4551     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4552       break;
4553     }
4554     break;
4555   case ICmpInst::ICMP_SLT:
4556     switch (RHSCC) {
4557     default: assert(0 && "Unknown integer condition code!");
4558     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4559       break;
4560     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4561       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4562       // this can cause overflow.
4563       if (RHSCst->isMaxValue(true))
4564         return ReplaceInstUsesWith(I, LHS);
4565       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4566     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4567       break;
4568     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4569     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4570       return ReplaceInstUsesWith(I, RHS);
4571     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4572       break;
4573     }
4574     break;
4575   case ICmpInst::ICMP_UGT:
4576     switch (RHSCC) {
4577     default: assert(0 && "Unknown integer condition code!");
4578     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4579     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4580       return ReplaceInstUsesWith(I, LHS);
4581     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4582       break;
4583     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4584     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4585       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4586     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4587       break;
4588     }
4589     break;
4590   case ICmpInst::ICMP_SGT:
4591     switch (RHSCC) {
4592     default: assert(0 && "Unknown integer condition code!");
4593     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4594     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4595       return ReplaceInstUsesWith(I, LHS);
4596     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4597       break;
4598     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4599     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4600       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4601     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4602       break;
4603     }
4604     break;
4605   }
4606   return 0;
4607 }
4608
4609 /// FoldOrWithConstants - This helper function folds:
4610 ///
4611 ///     ((A | B) & C1) | (B & C2)
4612 ///
4613 /// into:
4614 /// 
4615 ///     (A & C1) | B
4616 ///
4617 /// when the XOR of the two constants is "all ones" (-1).
4618 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4619                                                Value *A, Value *B, Value *C) {
4620   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4621   if (!CI1) return 0;
4622
4623   Value *V1 = 0;
4624   ConstantInt *CI2 = 0;
4625   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4626
4627   APInt Xor = CI1->getValue() ^ CI2->getValue();
4628   if (!Xor.isAllOnesValue()) return 0;
4629
4630   if (V1 == A || V1 == B) {
4631     Instruction *NewOp =
4632       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4633     return BinaryOperator::CreateOr(NewOp, V1);
4634   }
4635
4636   return 0;
4637 }
4638
4639 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4640   bool Changed = SimplifyCommutative(I);
4641   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4642
4643   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4644     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4645
4646   // or X, X = X
4647   if (Op0 == Op1)
4648     return ReplaceInstUsesWith(I, Op0);
4649
4650   // See if we can simplify any instructions used by the instruction whose sole 
4651   // purpose is to compute bits we don't care about.
4652   if (SimplifyDemandedInstructionBits(I))
4653     return &I;
4654   if (isa<VectorType>(I.getType())) {
4655     if (isa<ConstantAggregateZero>(Op1)) {
4656       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4657     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4658       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4659         return ReplaceInstUsesWith(I, I.getOperand(1));
4660     }
4661   }
4662
4663   // or X, -1 == -1
4664   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4665     ConstantInt *C1 = 0; Value *X = 0;
4666     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4667     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4668       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4669       InsertNewInstBefore(Or, I);
4670       Or->takeName(Op0);
4671       return BinaryOperator::CreateAnd(Or, 
4672                ConstantInt::get(RHS->getValue() | C1->getValue()));
4673     }
4674
4675     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4676     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4677       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4678       InsertNewInstBefore(Or, I);
4679       Or->takeName(Op0);
4680       return BinaryOperator::CreateXor(Or,
4681                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4682     }
4683
4684     // Try to fold constant and into select arguments.
4685     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4686       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4687         return R;
4688     if (isa<PHINode>(Op0))
4689       if (Instruction *NV = FoldOpIntoPhi(I))
4690         return NV;
4691   }
4692
4693   Value *A = 0, *B = 0;
4694   ConstantInt *C1 = 0, *C2 = 0;
4695
4696   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4697     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4698       return ReplaceInstUsesWith(I, Op1);
4699   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4700     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4701       return ReplaceInstUsesWith(I, Op0);
4702
4703   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4704   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4705   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4706       match(Op1, m_Or(m_Value(), m_Value())) ||
4707       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4708        match(Op1, m_Shift(m_Value(), m_Value())))) {
4709     if (Instruction *BSwap = MatchBSwap(I))
4710       return BSwap;
4711   }
4712   
4713   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4714   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4715       MaskedValueIsZero(Op1, C1->getValue())) {
4716     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4717     InsertNewInstBefore(NOr, I);
4718     NOr->takeName(Op0);
4719     return BinaryOperator::CreateXor(NOr, C1);
4720   }
4721
4722   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4723   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4724       MaskedValueIsZero(Op0, C1->getValue())) {
4725     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4726     InsertNewInstBefore(NOr, I);
4727     NOr->takeName(Op0);
4728     return BinaryOperator::CreateXor(NOr, C1);
4729   }
4730
4731   // (A & C)|(B & D)
4732   Value *C = 0, *D = 0;
4733   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4734       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4735     Value *V1 = 0, *V2 = 0, *V3 = 0;
4736     C1 = dyn_cast<ConstantInt>(C);
4737     C2 = dyn_cast<ConstantInt>(D);
4738     if (C1 && C2) {  // (A & C1)|(B & C2)
4739       // If we have: ((V + N) & C1) | (V & C2)
4740       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4741       // replace with V+N.
4742       if (C1->getValue() == ~C2->getValue()) {
4743         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4744             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4745           // Add commutes, try both ways.
4746           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4747             return ReplaceInstUsesWith(I, A);
4748           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4749             return ReplaceInstUsesWith(I, A);
4750         }
4751         // Or commutes, try both ways.
4752         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4753             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4754           // Add commutes, try both ways.
4755           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4756             return ReplaceInstUsesWith(I, B);
4757           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4758             return ReplaceInstUsesWith(I, B);
4759         }
4760       }
4761       V1 = 0; V2 = 0; V3 = 0;
4762     }
4763     
4764     // Check to see if we have any common things being and'ed.  If so, find the
4765     // terms for V1 & (V2|V3).
4766     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4767       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4768         V1 = A, V2 = C, V3 = D;
4769       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4770         V1 = A, V2 = B, V3 = C;
4771       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4772         V1 = C, V2 = A, V3 = D;
4773       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4774         V1 = C, V2 = A, V3 = B;
4775       
4776       if (V1) {
4777         Value *Or =
4778           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4779         return BinaryOperator::CreateAnd(V1, Or);
4780       }
4781     }
4782
4783     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4784     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4785       return Match;
4786     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4787       return Match;
4788     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4789       return Match;
4790     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4791       return Match;
4792
4793     // ((A&~B)|(~A&B)) -> A^B
4794     if ((match(C, m_Not(m_Specific(D))) &&
4795          match(B, m_Not(m_Specific(A)))))
4796       return BinaryOperator::CreateXor(A, D);
4797     // ((~B&A)|(~A&B)) -> A^B
4798     if ((match(A, m_Not(m_Specific(D))) &&
4799          match(B, m_Not(m_Specific(C)))))
4800       return BinaryOperator::CreateXor(C, D);
4801     // ((A&~B)|(B&~A)) -> A^B
4802     if ((match(C, m_Not(m_Specific(B))) &&
4803          match(D, m_Not(m_Specific(A)))))
4804       return BinaryOperator::CreateXor(A, B);
4805     // ((~B&A)|(B&~A)) -> A^B
4806     if ((match(A, m_Not(m_Specific(B))) &&
4807          match(D, m_Not(m_Specific(C)))))
4808       return BinaryOperator::CreateXor(C, B);
4809   }
4810   
4811   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4812   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4813     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4814       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4815           SI0->getOperand(1) == SI1->getOperand(1) &&
4816           (SI0->hasOneUse() || SI1->hasOneUse())) {
4817         Instruction *NewOp =
4818         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4819                                                      SI1->getOperand(0),
4820                                                      SI0->getName()), I);
4821         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4822                                       SI1->getOperand(1));
4823       }
4824   }
4825
4826   // ((A|B)&1)|(B&-2) -> (A&1) | B
4827   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4828       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4829     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4830     if (Ret) return Ret;
4831   }
4832   // (B&-2)|((A|B)&1) -> (A&1) | B
4833   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4834       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4835     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4836     if (Ret) return Ret;
4837   }
4838
4839   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4840     if (A == Op1)   // ~A | A == -1
4841       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4842   } else {
4843     A = 0;
4844   }
4845   // Note, A is still live here!
4846   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4847     if (Op0 == B)
4848       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4849
4850     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4851     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4852       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4853                                               I.getName()+".demorgan"), I);
4854       return BinaryOperator::CreateNot(And);
4855     }
4856   }
4857
4858   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4859   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4860     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4861       return R;
4862
4863     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4864       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4865         return Res;
4866   }
4867     
4868   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4869   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4870     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4871       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4872         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4873             !isa<ICmpInst>(Op1C->getOperand(0))) {
4874           const Type *SrcTy = Op0C->getOperand(0)->getType();
4875           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4876               // Only do this if the casts both really cause code to be
4877               // generated.
4878               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4879                                 I.getType(), TD) &&
4880               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4881                                 I.getType(), TD)) {
4882             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4883                                                           Op1C->getOperand(0),
4884                                                           I.getName());
4885             InsertNewInstBefore(NewOp, I);
4886             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4887           }
4888         }
4889       }
4890   }
4891   
4892     
4893   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4894   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4895     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4896       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4897           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4898           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4899         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4900           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4901             // If either of the constants are nans, then the whole thing returns
4902             // true.
4903             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4904               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4905             
4906             // Otherwise, no need to compare the two constants, compare the
4907             // rest.
4908             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4909                                 RHS->getOperand(0));
4910           }
4911       } else {
4912         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4913         FCmpInst::Predicate Op0CC, Op1CC;
4914         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4915             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4916           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4917             // Swap RHS operands to match LHS.
4918             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4919             std::swap(Op1LHS, Op1RHS);
4920           }
4921           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4922             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4923             if (Op0CC == Op1CC)
4924               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4925             else if (Op0CC == FCmpInst::FCMP_TRUE ||
4926                      Op1CC == FCmpInst::FCMP_TRUE)
4927               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4928             else if (Op0CC == FCmpInst::FCMP_FALSE)
4929               return ReplaceInstUsesWith(I, Op1);
4930             else if (Op1CC == FCmpInst::FCMP_FALSE)
4931               return ReplaceInstUsesWith(I, Op0);
4932             bool Op0Ordered;
4933             bool Op1Ordered;
4934             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4935             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4936             if (Op0Ordered == Op1Ordered) {
4937               // If both are ordered or unordered, return a new fcmp with
4938               // or'ed predicates.
4939               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4940                                        Op0LHS, Op0RHS);
4941               if (Instruction *I = dyn_cast<Instruction>(RV))
4942                 return I;
4943               // Otherwise, it's a constant boolean value...
4944               return ReplaceInstUsesWith(I, RV);
4945             }
4946           }
4947         }
4948       }
4949     }
4950   }
4951
4952   return Changed ? &I : 0;
4953 }
4954
4955 namespace {
4956
4957 // XorSelf - Implements: X ^ X --> 0
4958 struct XorSelf {
4959   Value *RHS;
4960   XorSelf(Value *rhs) : RHS(rhs) {}
4961   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4962   Instruction *apply(BinaryOperator &Xor) const {
4963     return &Xor;
4964   }
4965 };
4966
4967 }
4968
4969 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4970   bool Changed = SimplifyCommutative(I);
4971   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4972
4973   if (isa<UndefValue>(Op1)) {
4974     if (isa<UndefValue>(Op0))
4975       // Handle undef ^ undef -> 0 special case. This is a common
4976       // idiom (misuse).
4977       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4978     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4979   }
4980
4981   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4982   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4983     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4984     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4985   }
4986   
4987   // See if we can simplify any instructions used by the instruction whose sole 
4988   // purpose is to compute bits we don't care about.
4989   if (SimplifyDemandedInstructionBits(I))
4990     return &I;
4991   if (isa<VectorType>(I.getType()))
4992     if (isa<ConstantAggregateZero>(Op1))
4993       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4994
4995   // Is this a ~ operation?
4996   if (Value *NotOp = dyn_castNotVal(&I)) {
4997     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4998     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4999     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5000       if (Op0I->getOpcode() == Instruction::And || 
5001           Op0I->getOpcode() == Instruction::Or) {
5002         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5003         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5004           Instruction *NotY =
5005             BinaryOperator::CreateNot(Op0I->getOperand(1),
5006                                       Op0I->getOperand(1)->getName()+".not");
5007           InsertNewInstBefore(NotY, I);
5008           if (Op0I->getOpcode() == Instruction::And)
5009             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5010           else
5011             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5012         }
5013       }
5014     }
5015   }
5016   
5017   
5018   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5019     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
5020       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5021       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5022         return new ICmpInst(ICI->getInversePredicate(),
5023                             ICI->getOperand(0), ICI->getOperand(1));
5024
5025       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5026         return new FCmpInst(FCI->getInversePredicate(),
5027                             FCI->getOperand(0), FCI->getOperand(1));
5028     }
5029
5030     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5031     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5032       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5033         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5034           Instruction::CastOps Opcode = Op0C->getOpcode();
5035           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5036             if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
5037                                              Op0C->getDestTy())) {
5038               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5039                                      CI->getOpcode(), CI->getInversePredicate(),
5040                                      CI->getOperand(0), CI->getOperand(1)), I);
5041               NewCI->takeName(CI);
5042               return CastInst::Create(Opcode, NewCI, Op0C->getType());
5043             }
5044           }
5045         }
5046       }
5047     }
5048
5049     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5050       // ~(c-X) == X-c-1 == X+(-c-1)
5051       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5052         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5053           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5054           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5055                                               ConstantInt::get(I.getType(), 1));
5056           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5057         }
5058           
5059       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5060         if (Op0I->getOpcode() == Instruction::Add) {
5061           // ~(X-c) --> (-c-1)-X
5062           if (RHS->isAllOnesValue()) {
5063             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5064             return BinaryOperator::CreateSub(
5065                            ConstantExpr::getSub(NegOp0CI,
5066                                              ConstantInt::get(I.getType(), 1)),
5067                                           Op0I->getOperand(0));
5068           } else if (RHS->getValue().isSignBit()) {
5069             // (X + C) ^ signbit -> (X + C + signbit)
5070             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
5071             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5072
5073           }
5074         } else if (Op0I->getOpcode() == Instruction::Or) {
5075           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5076           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5077             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5078             // Anything in both C1 and C2 is known to be zero, remove it from
5079             // NewRHS.
5080             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5081             NewRHS = ConstantExpr::getAnd(NewRHS, 
5082                                           ConstantExpr::getNot(CommonBits));
5083             AddToWorkList(Op0I);
5084             I.setOperand(0, Op0I->getOperand(0));
5085             I.setOperand(1, NewRHS);
5086             return &I;
5087           }
5088         }
5089       }
5090     }
5091
5092     // Try to fold constant and into select arguments.
5093     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5094       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5095         return R;
5096     if (isa<PHINode>(Op0))
5097       if (Instruction *NV = FoldOpIntoPhi(I))
5098         return NV;
5099   }
5100
5101   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
5102     if (X == Op1)
5103       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5104
5105   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5106     if (X == Op0)
5107       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5108
5109   
5110   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5111   if (Op1I) {
5112     Value *A, *B;
5113     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5114       if (A == Op0) {              // B^(B|A) == (A|B)^B
5115         Op1I->swapOperands();
5116         I.swapOperands();
5117         std::swap(Op0, Op1);
5118       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5119         I.swapOperands();     // Simplified below.
5120         std::swap(Op0, Op1);
5121       }
5122     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5123       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5124     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5125       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5126     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
5127       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5128         Op1I->swapOperands();
5129         std::swap(A, B);
5130       }
5131       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5132         I.swapOperands();     // Simplified below.
5133         std::swap(Op0, Op1);
5134       }
5135     }
5136   }
5137   
5138   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5139   if (Op0I) {
5140     Value *A, *B;
5141     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5142       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5143         std::swap(A, B);
5144       if (B == Op1) {                                // (A|B)^B == A & ~B
5145         Instruction *NotB =
5146           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5147         return BinaryOperator::CreateAnd(A, NotB);
5148       }
5149     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5150       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5151     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5152       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5153     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5154       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5155         std::swap(A, B);
5156       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5157           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5158         Instruction *N =
5159           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5160         return BinaryOperator::CreateAnd(N, Op1);
5161       }
5162     }
5163   }
5164   
5165   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5166   if (Op0I && Op1I && Op0I->isShift() && 
5167       Op0I->getOpcode() == Op1I->getOpcode() && 
5168       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5169       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5170     Instruction *NewOp =
5171       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5172                                                     Op1I->getOperand(0),
5173                                                     Op0I->getName()), I);
5174     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5175                                   Op1I->getOperand(1));
5176   }
5177     
5178   if (Op0I && Op1I) {
5179     Value *A, *B, *C, *D;
5180     // (A & B)^(A | B) -> A ^ B
5181     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5182         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5183       if ((A == C && B == D) || (A == D && B == C)) 
5184         return BinaryOperator::CreateXor(A, B);
5185     }
5186     // (A | B)^(A & B) -> A ^ B
5187     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5188         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5189       if ((A == C && B == D) || (A == D && B == C)) 
5190         return BinaryOperator::CreateXor(A, B);
5191     }
5192     
5193     // (A & B)^(C & D)
5194     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5195         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5196         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5197       // (X & Y)^(X & Y) -> (Y^Z) & X
5198       Value *X = 0, *Y = 0, *Z = 0;
5199       if (A == C)
5200         X = A, Y = B, Z = D;
5201       else if (A == D)
5202         X = A, Y = B, Z = C;
5203       else if (B == C)
5204         X = B, Y = A, Z = D;
5205       else if (B == D)
5206         X = B, Y = A, Z = C;
5207       
5208       if (X) {
5209         Instruction *NewOp =
5210         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5211         return BinaryOperator::CreateAnd(NewOp, X);
5212       }
5213     }
5214   }
5215     
5216   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5217   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5218     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5219       return R;
5220
5221   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5222   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5223     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5224       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5225         const Type *SrcTy = Op0C->getOperand(0)->getType();
5226         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5227             // Only do this if the casts both really cause code to be generated.
5228             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5229                               I.getType(), TD) &&
5230             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5231                               I.getType(), TD)) {
5232           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5233                                                          Op1C->getOperand(0),
5234                                                          I.getName());
5235           InsertNewInstBefore(NewOp, I);
5236           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5237         }
5238       }
5239   }
5240
5241   return Changed ? &I : 0;
5242 }
5243
5244 static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
5245   return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5246 }
5247
5248 static bool HasAddOverflow(ConstantInt *Result,
5249                            ConstantInt *In1, ConstantInt *In2,
5250                            bool IsSigned) {
5251   if (IsSigned)
5252     if (In2->getValue().isNegative())
5253       return Result->getValue().sgt(In1->getValue());
5254     else
5255       return Result->getValue().slt(In1->getValue());
5256   else
5257     return Result->getValue().ult(In1->getValue());
5258 }
5259
5260 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5261 /// overflowed for this type.
5262 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5263                             Constant *In2, bool IsSigned = false) {
5264   Result = ConstantExpr::getAdd(In1, In2);
5265
5266   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5267     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5268       Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
5269       if (HasAddOverflow(ExtractElement(Result, Idx),
5270                          ExtractElement(In1, Idx),
5271                          ExtractElement(In2, Idx),
5272                          IsSigned))
5273         return true;
5274     }
5275     return false;
5276   }
5277
5278   return HasAddOverflow(cast<ConstantInt>(Result),
5279                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5280                         IsSigned);
5281 }
5282
5283 static bool HasSubOverflow(ConstantInt *Result,
5284                            ConstantInt *In1, ConstantInt *In2,
5285                            bool IsSigned) {
5286   if (IsSigned)
5287     if (In2->getValue().isNegative())
5288       return Result->getValue().slt(In1->getValue());
5289     else
5290       return Result->getValue().sgt(In1->getValue());
5291   else
5292     return Result->getValue().ugt(In1->getValue());
5293 }
5294
5295 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5296 /// overflowed for this type.
5297 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5298                             Constant *In2, bool IsSigned = false) {
5299   Result = ConstantExpr::getSub(In1, In2);
5300
5301   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5302     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5303       Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
5304       if (HasSubOverflow(ExtractElement(Result, Idx),
5305                          ExtractElement(In1, Idx),
5306                          ExtractElement(In2, Idx),
5307                          IsSigned))
5308         return true;
5309     }
5310     return false;
5311   }
5312
5313   return HasSubOverflow(cast<ConstantInt>(Result),
5314                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5315                         IsSigned);
5316 }
5317
5318 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5319 /// code necessary to compute the offset from the base pointer (without adding
5320 /// in the base pointer).  Return the result as a signed integer of intptr size.
5321 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5322   TargetData &TD = IC.getTargetData();
5323   gep_type_iterator GTI = gep_type_begin(GEP);
5324   const Type *IntPtrTy = TD.getIntPtrType();
5325   Value *Result = Constant::getNullValue(IntPtrTy);
5326
5327   // Build a mask for high order bits.
5328   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5329   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5330
5331   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5332        ++i, ++GTI) {
5333     Value *Op = *i;
5334     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5335     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5336       if (OpC->isZero()) continue;
5337       
5338       // Handle a struct index, which adds its field offset to the pointer.
5339       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5340         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5341         
5342         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5343           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
5344         else
5345           Result = IC.InsertNewInstBefore(
5346                    BinaryOperator::CreateAdd(Result,
5347                                              ConstantInt::get(IntPtrTy, Size),
5348                                              GEP->getName()+".offs"), I);
5349         continue;
5350       }
5351       
5352       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5353       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5354       Scale = ConstantExpr::getMul(OC, Scale);
5355       if (Constant *RC = dyn_cast<Constant>(Result))
5356         Result = ConstantExpr::getAdd(RC, Scale);
5357       else {
5358         // Emit an add instruction.
5359         Result = IC.InsertNewInstBefore(
5360            BinaryOperator::CreateAdd(Result, Scale,
5361                                      GEP->getName()+".offs"), I);
5362       }
5363       continue;
5364     }
5365     // Convert to correct type.
5366     if (Op->getType() != IntPtrTy) {
5367       if (Constant *OpC = dyn_cast<Constant>(Op))
5368         Op = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true);
5369       else
5370         Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5371                                                                 true,
5372                                                       Op->getName()+".c"), I);
5373     }
5374     if (Size != 1) {
5375       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5376       if (Constant *OpC = dyn_cast<Constant>(Op))
5377         Op = ConstantExpr::getMul(OpC, Scale);
5378       else    // We'll let instcombine(mul) convert this to a shl if possible.
5379         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5380                                                   GEP->getName()+".idx"), I);
5381     }
5382
5383     // Emit an add instruction.
5384     if (isa<Constant>(Op) && isa<Constant>(Result))
5385       Result = ConstantExpr::getAdd(cast<Constant>(Op),
5386                                     cast<Constant>(Result));
5387     else
5388       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5389                                                   GEP->getName()+".offs"), I);
5390   }
5391   return Result;
5392 }
5393
5394
5395 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5396 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
5397 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
5398 /// complex, and scales are involved.  The above expression would also be legal
5399 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
5400 /// later form is less amenable to optimization though, and we are allowed to
5401 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5402 ///
5403 /// If we can't emit an optimized form for this expression, this returns null.
5404 /// 
5405 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5406                                           InstCombiner &IC) {
5407   TargetData &TD = IC.getTargetData();
5408   gep_type_iterator GTI = gep_type_begin(GEP);
5409
5410   // Check to see if this gep only has a single variable index.  If so, and if
5411   // any constant indices are a multiple of its scale, then we can compute this
5412   // in terms of the scale of the variable index.  For example, if the GEP
5413   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5414   // because the expression will cross zero at the same point.
5415   unsigned i, e = GEP->getNumOperands();
5416   int64_t Offset = 0;
5417   for (i = 1; i != e; ++i, ++GTI) {
5418     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5419       // Compute the aggregate offset of constant indices.
5420       if (CI->isZero()) continue;
5421
5422       // Handle a struct index, which adds its field offset to the pointer.
5423       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5424         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5425       } else {
5426         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5427         Offset += Size*CI->getSExtValue();
5428       }
5429     } else {
5430       // Found our variable index.
5431       break;
5432     }
5433   }
5434   
5435   // If there are no variable indices, we must have a constant offset, just
5436   // evaluate it the general way.
5437   if (i == e) return 0;
5438   
5439   Value *VariableIdx = GEP->getOperand(i);
5440   // Determine the scale factor of the variable element.  For example, this is
5441   // 4 if the variable index is into an array of i32.
5442   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5443   
5444   // Verify that there are no other variable indices.  If so, emit the hard way.
5445   for (++i, ++GTI; i != e; ++i, ++GTI) {
5446     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5447     if (!CI) return 0;
5448    
5449     // Compute the aggregate offset of constant indices.
5450     if (CI->isZero()) continue;
5451     
5452     // Handle a struct index, which adds its field offset to the pointer.
5453     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5454       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5455     } else {
5456       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5457       Offset += Size*CI->getSExtValue();
5458     }
5459   }
5460   
5461   // Okay, we know we have a single variable index, which must be a
5462   // pointer/array/vector index.  If there is no offset, life is simple, return
5463   // the index.
5464   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5465   if (Offset == 0) {
5466     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5467     // we don't need to bother extending: the extension won't affect where the
5468     // computation crosses zero.
5469     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5470       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5471                                   VariableIdx->getNameStart(), &I);
5472     return VariableIdx;
5473   }
5474   
5475   // Otherwise, there is an index.  The computation we will do will be modulo
5476   // the pointer size, so get it.
5477   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5478   
5479   Offset &= PtrSizeMask;
5480   VariableScale &= PtrSizeMask;
5481
5482   // To do this transformation, any constant index must be a multiple of the
5483   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5484   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5485   // multiple of the variable scale.
5486   int64_t NewOffs = Offset / (int64_t)VariableScale;
5487   if (Offset != NewOffs*(int64_t)VariableScale)
5488     return 0;
5489
5490   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5491   const Type *IntPtrTy = TD.getIntPtrType();
5492   if (VariableIdx->getType() != IntPtrTy)
5493     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5494                                               true /*SExt*/, 
5495                                               VariableIdx->getNameStart(), &I);
5496   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5497   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5498 }
5499
5500
5501 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5502 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5503 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5504                                        ICmpInst::Predicate Cond,
5505                                        Instruction &I) {
5506   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5507
5508   // Look through bitcasts.
5509   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5510     RHS = BCI->getOperand(0);
5511
5512   Value *PtrBase = GEPLHS->getOperand(0);
5513   if (PtrBase == RHS) {
5514     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5515     // This transformation (ignoring the base and scales) is valid because we
5516     // know pointers can't overflow.  See if we can output an optimized form.
5517     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5518     
5519     // If not, synthesize the offset the hard way.
5520     if (Offset == 0)
5521       Offset = EmitGEPOffset(GEPLHS, I, *this);
5522     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5523                         Constant::getNullValue(Offset->getType()));
5524   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5525     // If the base pointers are different, but the indices are the same, just
5526     // compare the base pointer.
5527     if (PtrBase != GEPRHS->getOperand(0)) {
5528       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5529       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5530                         GEPRHS->getOperand(0)->getType();
5531       if (IndicesTheSame)
5532         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5533           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5534             IndicesTheSame = false;
5535             break;
5536           }
5537
5538       // If all indices are the same, just compare the base pointers.
5539       if (IndicesTheSame)
5540         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
5541                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5542
5543       // Otherwise, the base pointers are different and the indices are
5544       // different, bail out.
5545       return 0;
5546     }
5547
5548     // If one of the GEPs has all zero indices, recurse.
5549     bool AllZeros = true;
5550     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5551       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5552           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5553         AllZeros = false;
5554         break;
5555       }
5556     if (AllZeros)
5557       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5558                           ICmpInst::getSwappedPredicate(Cond), I);
5559
5560     // If the other GEP has all zero indices, recurse.
5561     AllZeros = true;
5562     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5563       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5564           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5565         AllZeros = false;
5566         break;
5567       }
5568     if (AllZeros)
5569       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5570
5571     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5572       // If the GEPs only differ by one index, compare it.
5573       unsigned NumDifferences = 0;  // Keep track of # differences.
5574       unsigned DiffOperand = 0;     // The operand that differs.
5575       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5576         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5577           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5578                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5579             // Irreconcilable differences.
5580             NumDifferences = 2;
5581             break;
5582           } else {
5583             if (NumDifferences++) break;
5584             DiffOperand = i;
5585           }
5586         }
5587
5588       if (NumDifferences == 0)   // SAME GEP?
5589         return ReplaceInstUsesWith(I, // No comparison is needed here.
5590                                    ConstantInt::get(Type::Int1Ty,
5591                                              ICmpInst::isTrueWhenEqual(Cond)));
5592
5593       else if (NumDifferences == 1) {
5594         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5595         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5596         // Make sure we do a signed comparison here.
5597         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5598       }
5599     }
5600
5601     // Only lower this if the icmp is the only user of the GEP or if we expect
5602     // the result to fold to a constant!
5603     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5604         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5605       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5606       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5607       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5608       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5609     }
5610   }
5611   return 0;
5612 }
5613
5614 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5615 ///
5616 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5617                                                 Instruction *LHSI,
5618                                                 Constant *RHSC) {
5619   if (!isa<ConstantFP>(RHSC)) return 0;
5620   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5621   
5622   // Get the width of the mantissa.  We don't want to hack on conversions that
5623   // might lose information from the integer, e.g. "i64 -> float"
5624   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5625   if (MantissaWidth == -1) return 0;  // Unknown.
5626   
5627   // Check to see that the input is converted from an integer type that is small
5628   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5629   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5630   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5631   
5632   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5633   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5634   if (LHSUnsigned)
5635     ++InputSize;
5636   
5637   // If the conversion would lose info, don't hack on this.
5638   if ((int)InputSize > MantissaWidth)
5639     return 0;
5640   
5641   // Otherwise, we can potentially simplify the comparison.  We know that it
5642   // will always come through as an integer value and we know the constant is
5643   // not a NAN (it would have been previously simplified).
5644   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5645   
5646   ICmpInst::Predicate Pred;
5647   switch (I.getPredicate()) {
5648   default: assert(0 && "Unexpected predicate!");
5649   case FCmpInst::FCMP_UEQ:
5650   case FCmpInst::FCMP_OEQ:
5651     Pred = ICmpInst::ICMP_EQ;
5652     break;
5653   case FCmpInst::FCMP_UGT:
5654   case FCmpInst::FCMP_OGT:
5655     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5656     break;
5657   case FCmpInst::FCMP_UGE:
5658   case FCmpInst::FCMP_OGE:
5659     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5660     break;
5661   case FCmpInst::FCMP_ULT:
5662   case FCmpInst::FCMP_OLT:
5663     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5664     break;
5665   case FCmpInst::FCMP_ULE:
5666   case FCmpInst::FCMP_OLE:
5667     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5668     break;
5669   case FCmpInst::FCMP_UNE:
5670   case FCmpInst::FCMP_ONE:
5671     Pred = ICmpInst::ICMP_NE;
5672     break;
5673   case FCmpInst::FCMP_ORD:
5674     return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5675   case FCmpInst::FCMP_UNO:
5676     return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5677   }
5678   
5679   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5680   
5681   // Now we know that the APFloat is a normal number, zero or inf.
5682   
5683   // See if the FP constant is too large for the integer.  For example,
5684   // comparing an i8 to 300.0.
5685   unsigned IntWidth = IntTy->getScalarSizeInBits();
5686   
5687   if (!LHSUnsigned) {
5688     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5689     // and large values.
5690     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5691     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5692                           APFloat::rmNearestTiesToEven);
5693     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5694       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5695           Pred == ICmpInst::ICMP_SLE)
5696         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5697       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5698     }
5699   } else {
5700     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5701     // +INF and large values.
5702     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5703     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5704                           APFloat::rmNearestTiesToEven);
5705     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5706       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5707           Pred == ICmpInst::ICMP_ULE)
5708         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5709       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5710     }
5711   }
5712   
5713   if (!LHSUnsigned) {
5714     // See if the RHS value is < SignedMin.
5715     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5716     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5717                           APFloat::rmNearestTiesToEven);
5718     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5719       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5720           Pred == ICmpInst::ICMP_SGE)
5721         return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5722       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5723     }
5724   }
5725
5726   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5727   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5728   // casting the FP value to the integer value and back, checking for equality.
5729   // Don't do this for zero, because -0.0 is not fractional.
5730   Constant *RHSInt = LHSUnsigned
5731     ? ConstantExpr::getFPToUI(RHSC, IntTy)
5732     : ConstantExpr::getFPToSI(RHSC, IntTy);
5733   if (!RHS.isZero()) {
5734     bool Equal = LHSUnsigned
5735       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5736       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5737     if (!Equal) {
5738       // If we had a comparison against a fractional value, we have to adjust
5739       // the compare predicate and sometimes the value.  RHSC is rounded towards
5740       // zero at this point.
5741       switch (Pred) {
5742       default: assert(0 && "Unexpected integer comparison!");
5743       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5744         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5745       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5746         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5747       case ICmpInst::ICMP_ULE:
5748         // (float)int <= 4.4   --> int <= 4
5749         // (float)int <= -4.4  --> false
5750         if (RHS.isNegative())
5751           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5752         break;
5753       case ICmpInst::ICMP_SLE:
5754         // (float)int <= 4.4   --> int <= 4
5755         // (float)int <= -4.4  --> int < -4
5756         if (RHS.isNegative())
5757           Pred = ICmpInst::ICMP_SLT;
5758         break;
5759       case ICmpInst::ICMP_ULT:
5760         // (float)int < -4.4   --> false
5761         // (float)int < 4.4    --> int <= 4
5762         if (RHS.isNegative())
5763           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5764         Pred = ICmpInst::ICMP_ULE;
5765         break;
5766       case ICmpInst::ICMP_SLT:
5767         // (float)int < -4.4   --> int < -4
5768         // (float)int < 4.4    --> int <= 4
5769         if (!RHS.isNegative())
5770           Pred = ICmpInst::ICMP_SLE;
5771         break;
5772       case ICmpInst::ICMP_UGT:
5773         // (float)int > 4.4    --> int > 4
5774         // (float)int > -4.4   --> true
5775         if (RHS.isNegative())
5776           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5777         break;
5778       case ICmpInst::ICMP_SGT:
5779         // (float)int > 4.4    --> int > 4
5780         // (float)int > -4.4   --> int >= -4
5781         if (RHS.isNegative())
5782           Pred = ICmpInst::ICMP_SGE;
5783         break;
5784       case ICmpInst::ICMP_UGE:
5785         // (float)int >= -4.4   --> true
5786         // (float)int >= 4.4    --> int > 4
5787         if (!RHS.isNegative())
5788           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5789         Pred = ICmpInst::ICMP_UGT;
5790         break;
5791       case ICmpInst::ICMP_SGE:
5792         // (float)int >= -4.4   --> int >= -4
5793         // (float)int >= 4.4    --> int > 4
5794         if (!RHS.isNegative())
5795           Pred = ICmpInst::ICMP_SGT;
5796         break;
5797       }
5798     }
5799   }
5800
5801   // Lower this FP comparison into an appropriate integer version of the
5802   // comparison.
5803   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5804 }
5805
5806 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5807   bool Changed = SimplifyCompare(I);
5808   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5809
5810   // Fold trivial predicates.
5811   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5812     return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5813   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5814     return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5815   
5816   // Simplify 'fcmp pred X, X'
5817   if (Op0 == Op1) {
5818     switch (I.getPredicate()) {
5819     default: assert(0 && "Unknown predicate!");
5820     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5821     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5822     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5823       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5824     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5825     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5826     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5827       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5828       
5829     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5830     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5831     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5832     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5833       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5834       I.setPredicate(FCmpInst::FCMP_UNO);
5835       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5836       return &I;
5837       
5838     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5839     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5840     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5841     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5842       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5843       I.setPredicate(FCmpInst::FCMP_ORD);
5844       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5845       return &I;
5846     }
5847   }
5848     
5849   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5850     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5851
5852   // Handle fcmp with constant RHS
5853   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5854     // If the constant is a nan, see if we can fold the comparison based on it.
5855     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5856       if (CFP->getValueAPF().isNaN()) {
5857         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5858           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5859         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5860                "Comparison must be either ordered or unordered!");
5861         // True if unordered.
5862         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5863       }
5864     }
5865     
5866     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5867       switch (LHSI->getOpcode()) {
5868       case Instruction::PHI:
5869         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5870         // block.  If in the same block, we're encouraging jump threading.  If
5871         // not, we are just pessimizing the code by making an i1 phi.
5872         if (LHSI->getParent() == I.getParent())
5873           if (Instruction *NV = FoldOpIntoPhi(I))
5874             return NV;
5875         break;
5876       case Instruction::SIToFP:
5877       case Instruction::UIToFP:
5878         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5879           return NV;
5880         break;
5881       case Instruction::Select:
5882         // If either operand of the select is a constant, we can fold the
5883         // comparison into the select arms, which will cause one to be
5884         // constant folded and the select turned into a bitwise or.
5885         Value *Op1 = 0, *Op2 = 0;
5886         if (LHSI->hasOneUse()) {
5887           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5888             // Fold the known value into the constant operand.
5889             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5890             // Insert a new FCmp of the other select operand.
5891             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5892                                                       LHSI->getOperand(2), RHSC,
5893                                                       I.getName()), I);
5894           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5895             // Fold the known value into the constant operand.
5896             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5897             // Insert a new FCmp of the other select operand.
5898             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5899                                                       LHSI->getOperand(1), RHSC,
5900                                                       I.getName()), I);
5901           }
5902         }
5903
5904         if (Op1)
5905           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5906         break;
5907       }
5908   }
5909
5910   return Changed ? &I : 0;
5911 }
5912
5913 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5914   bool Changed = SimplifyCompare(I);
5915   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5916   const Type *Ty = Op0->getType();
5917
5918   // icmp X, X
5919   if (Op0 == Op1)
5920     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5921                                                    I.isTrueWhenEqual()));
5922
5923   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5924     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5925   
5926   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5927   // addresses never equal each other!  We already know that Op0 != Op1.
5928   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5929        isa<ConstantPointerNull>(Op0)) &&
5930       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5931        isa<ConstantPointerNull>(Op1)))
5932     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5933                                                    !I.isTrueWhenEqual()));
5934
5935   // icmp's with boolean values can always be turned into bitwise operations
5936   if (Ty == Type::Int1Ty) {
5937     switch (I.getPredicate()) {
5938     default: assert(0 && "Invalid icmp instruction!");
5939     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5940       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5941       InsertNewInstBefore(Xor, I);
5942       return BinaryOperator::CreateNot(Xor);
5943     }
5944     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5945       return BinaryOperator::CreateXor(Op0, Op1);
5946
5947     case ICmpInst::ICMP_UGT:
5948       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5949       // FALL THROUGH
5950     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5951       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5952       InsertNewInstBefore(Not, I);
5953       return BinaryOperator::CreateAnd(Not, Op1);
5954     }
5955     case ICmpInst::ICMP_SGT:
5956       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5957       // FALL THROUGH
5958     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5959       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5960       InsertNewInstBefore(Not, I);
5961       return BinaryOperator::CreateAnd(Not, Op0);
5962     }
5963     case ICmpInst::ICMP_UGE:
5964       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
5965       // FALL THROUGH
5966     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
5967       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5968       InsertNewInstBefore(Not, I);
5969       return BinaryOperator::CreateOr(Not, Op1);
5970     }
5971     case ICmpInst::ICMP_SGE:
5972       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
5973       // FALL THROUGH
5974     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
5975       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5976       InsertNewInstBefore(Not, I);
5977       return BinaryOperator::CreateOr(Not, Op0);
5978     }
5979     }
5980   }
5981
5982   unsigned BitWidth = 0;
5983   if (TD)
5984     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
5985   else if (Ty->isIntOrIntVector())
5986     BitWidth = Ty->getScalarSizeInBits();
5987
5988   bool isSignBit = false;
5989
5990   // See if we are doing a comparison with a constant.
5991   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5992     Value *A = 0, *B = 0;
5993     
5994     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5995     if (I.isEquality() && CI->isNullValue() &&
5996         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5997       // (icmp cond A B) if cond is equality
5998       return new ICmpInst(I.getPredicate(), A, B);
5999     }
6000     
6001     // If we have an icmp le or icmp ge instruction, turn it into the
6002     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6003     // them being folded in the code below.
6004     switch (I.getPredicate()) {
6005     default: break;
6006     case ICmpInst::ICMP_ULE:
6007       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
6008         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6009       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
6010     case ICmpInst::ICMP_SLE:
6011       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
6012         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6013       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
6014     case ICmpInst::ICMP_UGE:
6015       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
6016         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6017       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
6018     case ICmpInst::ICMP_SGE:
6019       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
6020         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6021       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
6022     }
6023     
6024     // If this comparison is a normal comparison, it demands all
6025     // bits, if it is a sign bit comparison, it only demands the sign bit.
6026     bool UnusedBit;
6027     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6028   }
6029
6030   // See if we can fold the comparison based on range information we can get
6031   // by checking whether bits are known to be zero or one in the input.
6032   if (BitWidth != 0) {
6033     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6034     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6035
6036     if (SimplifyDemandedBits(I.getOperandUse(0),
6037                              isSignBit ? APInt::getSignBit(BitWidth)
6038                                        : APInt::getAllOnesValue(BitWidth),
6039                              Op0KnownZero, Op0KnownOne, 0))
6040       return &I;
6041     if (SimplifyDemandedBits(I.getOperandUse(1),
6042                              APInt::getAllOnesValue(BitWidth),
6043                              Op1KnownZero, Op1KnownOne, 0))
6044       return &I;
6045
6046     // Given the known and unknown bits, compute a range that the LHS could be
6047     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6048     // EQ and NE we use unsigned values.
6049     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6050     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6051     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6052       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6053                                              Op0Min, Op0Max);
6054       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6055                                              Op1Min, Op1Max);
6056     } else {
6057       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6058                                                Op0Min, Op0Max);
6059       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6060                                                Op1Min, Op1Max);
6061     }
6062
6063     // If Min and Max are known to be the same, then SimplifyDemandedBits
6064     // figured out that the LHS is a constant.  Just constant fold this now so
6065     // that code below can assume that Min != Max.
6066     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6067       return new ICmpInst(I.getPredicate(), ConstantInt::get(Op0Min), Op1);
6068     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6069       return new ICmpInst(I.getPredicate(), Op0, ConstantInt::get(Op1Min));
6070
6071     // Based on the range information we know about the LHS, see if we can
6072     // simplify this comparison.  For example, (x&4) < 8  is always true.
6073     switch (I.getPredicate()) {
6074     default: assert(0 && "Unknown icmp opcode!");
6075     case ICmpInst::ICMP_EQ:
6076       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6077         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6078       break;
6079     case ICmpInst::ICMP_NE:
6080       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6081         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6082       break;
6083     case ICmpInst::ICMP_ULT:
6084       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6085         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6086       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6087         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6088       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6089         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6090       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6091         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6092           return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
6093
6094         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6095         if (CI->isMinValue(true))
6096           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6097                             ConstantInt::getAllOnesValue(Op0->getType()));
6098       }
6099       break;
6100     case ICmpInst::ICMP_UGT:
6101       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6102         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6103       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6104         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6105
6106       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6107         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6108       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6109         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6110           return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
6111
6112         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6113         if (CI->isMaxValue(true))
6114           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6115                               ConstantInt::getNullValue(Op0->getType()));
6116       }
6117       break;
6118     case ICmpInst::ICMP_SLT:
6119       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6120         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6121       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6122         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6123       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6124         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6125       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6126         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6127           return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
6128       }
6129       break;
6130     case ICmpInst::ICMP_SGT:
6131       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6132         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6133       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6134         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6135
6136       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6137         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6138       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6139         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6140           return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
6141       }
6142       break;
6143     case ICmpInst::ICMP_SGE:
6144       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6145       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6146         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6147       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6148         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6149       break;
6150     case ICmpInst::ICMP_SLE:
6151       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6152       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6153         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6154       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6155         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6156       break;
6157     case ICmpInst::ICMP_UGE:
6158       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6159       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6160         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6161       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6162         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6163       break;
6164     case ICmpInst::ICMP_ULE:
6165       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6166       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6167         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6168       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6169         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6170       break;
6171     }
6172
6173     // Turn a signed comparison into an unsigned one if both operands
6174     // are known to have the same sign.
6175     if (I.isSignedPredicate() &&
6176         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6177          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6178       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6179   }
6180
6181   // Test if the ICmpInst instruction is used exclusively by a select as
6182   // part of a minimum or maximum operation. If so, refrain from doing
6183   // any other folding. This helps out other analyses which understand
6184   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6185   // and CodeGen. And in this case, at least one of the comparison
6186   // operands has at least one user besides the compare (the select),
6187   // which would often largely negate the benefit of folding anyway.
6188   if (I.hasOneUse())
6189     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6190       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6191           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6192         return 0;
6193
6194   // See if we are doing a comparison between a constant and an instruction that
6195   // can be folded into the comparison.
6196   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6197     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6198     // instruction, see if that instruction also has constants so that the 
6199     // instruction can be folded into the icmp 
6200     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6201       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6202         return Res;
6203   }
6204
6205   // Handle icmp with constant (but not simple integer constant) RHS
6206   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6207     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6208       switch (LHSI->getOpcode()) {
6209       case Instruction::GetElementPtr:
6210         if (RHSC->isNullValue()) {
6211           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6212           bool isAllZeros = true;
6213           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6214             if (!isa<Constant>(LHSI->getOperand(i)) ||
6215                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6216               isAllZeros = false;
6217               break;
6218             }
6219           if (isAllZeros)
6220             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6221                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
6222         }
6223         break;
6224
6225       case Instruction::PHI:
6226         // Only fold icmp into the PHI if the phi and fcmp are in the same
6227         // block.  If in the same block, we're encouraging jump threading.  If
6228         // not, we are just pessimizing the code by making an i1 phi.
6229         if (LHSI->getParent() == I.getParent())
6230           if (Instruction *NV = FoldOpIntoPhi(I))
6231             return NV;
6232         break;
6233       case Instruction::Select: {
6234         // If either operand of the select is a constant, we can fold the
6235         // comparison into the select arms, which will cause one to be
6236         // constant folded and the select turned into a bitwise or.
6237         Value *Op1 = 0, *Op2 = 0;
6238         if (LHSI->hasOneUse()) {
6239           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6240             // Fold the known value into the constant operand.
6241             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6242             // Insert a new ICmp of the other select operand.
6243             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6244                                                    LHSI->getOperand(2), RHSC,
6245                                                    I.getName()), I);
6246           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6247             // Fold the known value into the constant operand.
6248             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6249             // Insert a new ICmp of the other select operand.
6250             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6251                                                    LHSI->getOperand(1), RHSC,
6252                                                    I.getName()), I);
6253           }
6254         }
6255
6256         if (Op1)
6257           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6258         break;
6259       }
6260       case Instruction::Malloc:
6261         // If we have (malloc != null), and if the malloc has a single use, we
6262         // can assume it is successful and remove the malloc.
6263         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6264           AddToWorkList(LHSI);
6265           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
6266                                                          !I.isTrueWhenEqual()));
6267         }
6268         break;
6269       }
6270   }
6271
6272   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6273   if (User *GEP = dyn_castGetElementPtr(Op0))
6274     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6275       return NI;
6276   if (User *GEP = dyn_castGetElementPtr(Op1))
6277     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6278                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6279       return NI;
6280
6281   // Test to see if the operands of the icmp are casted versions of other
6282   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6283   // now.
6284   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6285     if (isa<PointerType>(Op0->getType()) && 
6286         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6287       // We keep moving the cast from the left operand over to the right
6288       // operand, where it can often be eliminated completely.
6289       Op0 = CI->getOperand(0);
6290
6291       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6292       // so eliminate it as well.
6293       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6294         Op1 = CI2->getOperand(0);
6295
6296       // If Op1 is a constant, we can fold the cast into the constant.
6297       if (Op0->getType() != Op1->getType()) {
6298         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6299           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6300         } else {
6301           // Otherwise, cast the RHS right before the icmp
6302           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6303         }
6304       }
6305       return new ICmpInst(I.getPredicate(), Op0, Op1);
6306     }
6307   }
6308   
6309   if (isa<CastInst>(Op0)) {
6310     // Handle the special case of: icmp (cast bool to X), <cst>
6311     // This comes up when you have code like
6312     //   int X = A < B;
6313     //   if (X) ...
6314     // For generality, we handle any zero-extension of any operand comparison
6315     // with a constant or another cast from the same type.
6316     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6317       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6318         return R;
6319   }
6320   
6321   // See if it's the same type of instruction on the left and right.
6322   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6323     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6324       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6325           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6326         switch (Op0I->getOpcode()) {
6327         default: break;
6328         case Instruction::Add:
6329         case Instruction::Sub:
6330         case Instruction::Xor:
6331           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6332             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6333                                 Op1I->getOperand(0));
6334           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6335           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6336             if (CI->getValue().isSignBit()) {
6337               ICmpInst::Predicate Pred = I.isSignedPredicate()
6338                                              ? I.getUnsignedPredicate()
6339                                              : I.getSignedPredicate();
6340               return new ICmpInst(Pred, Op0I->getOperand(0),
6341                                   Op1I->getOperand(0));
6342             }
6343             
6344             if (CI->getValue().isMaxSignedValue()) {
6345               ICmpInst::Predicate Pred = I.isSignedPredicate()
6346                                              ? I.getUnsignedPredicate()
6347                                              : I.getSignedPredicate();
6348               Pred = I.getSwappedPredicate(Pred);
6349               return new ICmpInst(Pred, Op0I->getOperand(0),
6350                                   Op1I->getOperand(0));
6351             }
6352           }
6353           break;
6354         case Instruction::Mul:
6355           if (!I.isEquality())
6356             break;
6357
6358           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6359             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6360             // Mask = -1 >> count-trailing-zeros(Cst).
6361             if (!CI->isZero() && !CI->isOne()) {
6362               const APInt &AP = CI->getValue();
6363               ConstantInt *Mask = ConstantInt::get(
6364                                       APInt::getLowBitsSet(AP.getBitWidth(),
6365                                                            AP.getBitWidth() -
6366                                                       AP.countTrailingZeros()));
6367               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6368                                                             Mask);
6369               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6370                                                             Mask);
6371               InsertNewInstBefore(And1, I);
6372               InsertNewInstBefore(And2, I);
6373               return new ICmpInst(I.getPredicate(), And1, And2);
6374             }
6375           }
6376           break;
6377         }
6378       }
6379     }
6380   }
6381   
6382   // ~x < ~y --> y < x
6383   { Value *A, *B;
6384     if (match(Op0, m_Not(m_Value(A))) &&
6385         match(Op1, m_Not(m_Value(B))))
6386       return new ICmpInst(I.getPredicate(), B, A);
6387   }
6388   
6389   if (I.isEquality()) {
6390     Value *A, *B, *C, *D;
6391     
6392     // -x == -y --> x == y
6393     if (match(Op0, m_Neg(m_Value(A))) &&
6394         match(Op1, m_Neg(m_Value(B))))
6395       return new ICmpInst(I.getPredicate(), A, B);
6396     
6397     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6398       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6399         Value *OtherVal = A == Op1 ? B : A;
6400         return new ICmpInst(I.getPredicate(), OtherVal,
6401                             Constant::getNullValue(A->getType()));
6402       }
6403
6404       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6405         // A^c1 == C^c2 --> A == C^(c1^c2)
6406         ConstantInt *C1, *C2;
6407         if (match(B, m_ConstantInt(C1)) &&
6408             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6409           Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6410           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6411           return new ICmpInst(I.getPredicate(), A,
6412                               InsertNewInstBefore(Xor, I));
6413         }
6414         
6415         // A^B == A^D -> B == D
6416         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6417         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6418         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6419         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6420       }
6421     }
6422     
6423     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6424         (A == Op0 || B == Op0)) {
6425       // A == (A^B)  ->  B == 0
6426       Value *OtherVal = A == Op0 ? B : A;
6427       return new ICmpInst(I.getPredicate(), OtherVal,
6428                           Constant::getNullValue(A->getType()));
6429     }
6430
6431     // (A-B) == A  ->  B == 0
6432     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6433       return new ICmpInst(I.getPredicate(), B, 
6434                           Constant::getNullValue(B->getType()));
6435
6436     // A == (A-B)  ->  B == 0
6437     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6438       return new ICmpInst(I.getPredicate(), B,
6439                           Constant::getNullValue(B->getType()));
6440     
6441     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6442     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6443         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6444         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6445       Value *X = 0, *Y = 0, *Z = 0;
6446       
6447       if (A == C) {
6448         X = B; Y = D; Z = A;
6449       } else if (A == D) {
6450         X = B; Y = C; Z = A;
6451       } else if (B == C) {
6452         X = A; Y = D; Z = B;
6453       } else if (B == D) {
6454         X = A; Y = C; Z = B;
6455       }
6456       
6457       if (X) {   // Build (X^Y) & Z
6458         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6459         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6460         I.setOperand(0, Op1);
6461         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6462         return &I;
6463       }
6464     }
6465   }
6466   return Changed ? &I : 0;
6467 }
6468
6469
6470 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6471 /// and CmpRHS are both known to be integer constants.
6472 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6473                                           ConstantInt *DivRHS) {
6474   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6475   const APInt &CmpRHSV = CmpRHS->getValue();
6476   
6477   // FIXME: If the operand types don't match the type of the divide 
6478   // then don't attempt this transform. The code below doesn't have the
6479   // logic to deal with a signed divide and an unsigned compare (and
6480   // vice versa). This is because (x /s C1) <s C2  produces different 
6481   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6482   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6483   // work. :(  The if statement below tests that condition and bails 
6484   // if it finds it. 
6485   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6486   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6487     return 0;
6488   if (DivRHS->isZero())
6489     return 0; // The ProdOV computation fails on divide by zero.
6490   if (DivIsSigned && DivRHS->isAllOnesValue())
6491     return 0; // The overflow computation also screws up here
6492   if (DivRHS->isOne())
6493     return 0; // Not worth bothering, and eliminates some funny cases
6494               // with INT_MIN.
6495
6496   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6497   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6498   // C2 (CI). By solving for X we can turn this into a range check 
6499   // instead of computing a divide. 
6500   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6501
6502   // Determine if the product overflows by seeing if the product is
6503   // not equal to the divide. Make sure we do the same kind of divide
6504   // as in the LHS instruction that we're folding. 
6505   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6506                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6507
6508   // Get the ICmp opcode
6509   ICmpInst::Predicate Pred = ICI.getPredicate();
6510
6511   // Figure out the interval that is being checked.  For example, a comparison
6512   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6513   // Compute this interval based on the constants involved and the signedness of
6514   // the compare/divide.  This computes a half-open interval, keeping track of
6515   // whether either value in the interval overflows.  After analysis each
6516   // overflow variable is set to 0 if it's corresponding bound variable is valid
6517   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6518   int LoOverflow = 0, HiOverflow = 0;
6519   Constant *LoBound = 0, *HiBound = 0;
6520   
6521   if (!DivIsSigned) {  // udiv
6522     // e.g. X/5 op 3  --> [15, 20)
6523     LoBound = Prod;
6524     HiOverflow = LoOverflow = ProdOV;
6525     if (!HiOverflow)
6526       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
6527   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6528     if (CmpRHSV == 0) {       // (X / pos) op 0
6529       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6530       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6531       HiBound = DivRHS;
6532     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6533       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6534       HiOverflow = LoOverflow = ProdOV;
6535       if (!HiOverflow)
6536         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6537     } else {                       // (X / pos) op neg
6538       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6539       HiBound = AddOne(Prod);
6540       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6541       if (!LoOverflow) {
6542         ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6543         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6544                                      true) ? -1 : 0;
6545        }
6546     }
6547   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6548     if (CmpRHSV == 0) {       // (X / neg) op 0
6549       // e.g. X/-5 op 0  --> [-4, 5)
6550       LoBound = AddOne(DivRHS);
6551       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6552       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6553         HiOverflow = 1;            // [INTMIN+1, overflow)
6554         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6555       }
6556     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6557       // e.g. X/-5 op 3  --> [-19, -14)
6558       HiBound = AddOne(Prod);
6559       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6560       if (!LoOverflow)
6561         LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
6562     } else {                       // (X / neg) op neg
6563       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6564       LoOverflow = HiOverflow = ProdOV;
6565       if (!HiOverflow)
6566         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
6567     }
6568     
6569     // Dividing by a negative swaps the condition.  LT <-> GT
6570     Pred = ICmpInst::getSwappedPredicate(Pred);
6571   }
6572
6573   Value *X = DivI->getOperand(0);
6574   switch (Pred) {
6575   default: assert(0 && "Unhandled icmp opcode!");
6576   case ICmpInst::ICMP_EQ:
6577     if (LoOverflow && HiOverflow)
6578       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6579     else if (HiOverflow)
6580       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6581                           ICmpInst::ICMP_UGE, X, LoBound);
6582     else if (LoOverflow)
6583       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6584                           ICmpInst::ICMP_ULT, X, HiBound);
6585     else
6586       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6587   case ICmpInst::ICMP_NE:
6588     if (LoOverflow && HiOverflow)
6589       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6590     else if (HiOverflow)
6591       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6592                           ICmpInst::ICMP_ULT, X, LoBound);
6593     else if (LoOverflow)
6594       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6595                           ICmpInst::ICMP_UGE, X, HiBound);
6596     else
6597       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6598   case ICmpInst::ICMP_ULT:
6599   case ICmpInst::ICMP_SLT:
6600     if (LoOverflow == +1)   // Low bound is greater than input range.
6601       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6602     if (LoOverflow == -1)   // Low bound is less than input range.
6603       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6604     return new ICmpInst(Pred, X, LoBound);
6605   case ICmpInst::ICMP_UGT:
6606   case ICmpInst::ICMP_SGT:
6607     if (HiOverflow == +1)       // High bound greater than input range.
6608       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6609     else if (HiOverflow == -1)  // High bound less than input range.
6610       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6611     if (Pred == ICmpInst::ICMP_UGT)
6612       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6613     else
6614       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6615   }
6616 }
6617
6618
6619 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6620 ///
6621 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6622                                                           Instruction *LHSI,
6623                                                           ConstantInt *RHS) {
6624   const APInt &RHSV = RHS->getValue();
6625   
6626   switch (LHSI->getOpcode()) {
6627   case Instruction::Trunc:
6628     if (ICI.isEquality() && LHSI->hasOneUse()) {
6629       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6630       // of the high bits truncated out of x are known.
6631       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6632              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6633       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6634       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6635       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6636       
6637       // If all the high bits are known, we can do this xform.
6638       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6639         // Pull in the high bits from known-ones set.
6640         APInt NewRHS(RHS->getValue());
6641         NewRHS.zext(SrcBits);
6642         NewRHS |= KnownOne;
6643         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6644                             ConstantInt::get(NewRHS));
6645       }
6646     }
6647     break;
6648       
6649   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6650     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6651       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6652       // fold the xor.
6653       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6654           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6655         Value *CompareVal = LHSI->getOperand(0);
6656         
6657         // If the sign bit of the XorCST is not set, there is no change to
6658         // the operation, just stop using the Xor.
6659         if (!XorCST->getValue().isNegative()) {
6660           ICI.setOperand(0, CompareVal);
6661           AddToWorkList(LHSI);
6662           return &ICI;
6663         }
6664         
6665         // Was the old condition true if the operand is positive?
6666         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6667         
6668         // If so, the new one isn't.
6669         isTrueIfPositive ^= true;
6670         
6671         if (isTrueIfPositive)
6672           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6673         else
6674           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6675       }
6676
6677       if (LHSI->hasOneUse()) {
6678         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6679         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6680           const APInt &SignBit = XorCST->getValue();
6681           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6682                                          ? ICI.getUnsignedPredicate()
6683                                          : ICI.getSignedPredicate();
6684           return new ICmpInst(Pred, LHSI->getOperand(0),
6685                               ConstantInt::get(RHSV ^ SignBit));
6686         }
6687
6688         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6689         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6690           const APInt &NotSignBit = XorCST->getValue();
6691           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6692                                          ? ICI.getUnsignedPredicate()
6693                                          : ICI.getSignedPredicate();
6694           Pred = ICI.getSwappedPredicate(Pred);
6695           return new ICmpInst(Pred, LHSI->getOperand(0),
6696                               ConstantInt::get(RHSV ^ NotSignBit));
6697         }
6698       }
6699     }
6700     break;
6701   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6702     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6703         LHSI->getOperand(0)->hasOneUse()) {
6704       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6705       
6706       // If the LHS is an AND of a truncating cast, we can widen the
6707       // and/compare to be the input width without changing the value
6708       // produced, eliminating a cast.
6709       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6710         // We can do this transformation if either the AND constant does not
6711         // have its sign bit set or if it is an equality comparison. 
6712         // Extending a relational comparison when we're checking the sign
6713         // bit would not work.
6714         if (Cast->hasOneUse() &&
6715             (ICI.isEquality() ||
6716              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6717           uint32_t BitWidth = 
6718             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6719           APInt NewCST = AndCST->getValue();
6720           NewCST.zext(BitWidth);
6721           APInt NewCI = RHSV;
6722           NewCI.zext(BitWidth);
6723           Instruction *NewAnd = 
6724             BinaryOperator::CreateAnd(Cast->getOperand(0),
6725                                       ConstantInt::get(NewCST),LHSI->getName());
6726           InsertNewInstBefore(NewAnd, ICI);
6727           return new ICmpInst(ICI.getPredicate(), NewAnd,
6728                               ConstantInt::get(NewCI));
6729         }
6730       }
6731       
6732       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6733       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6734       // happens a LOT in code produced by the C front-end, for bitfield
6735       // access.
6736       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6737       if (Shift && !Shift->isShift())
6738         Shift = 0;
6739       
6740       ConstantInt *ShAmt;
6741       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6742       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6743       const Type *AndTy = AndCST->getType();          // Type of the and.
6744       
6745       // We can fold this as long as we can't shift unknown bits
6746       // into the mask.  This can only happen with signed shift
6747       // rights, as they sign-extend.
6748       if (ShAmt) {
6749         bool CanFold = Shift->isLogicalShift();
6750         if (!CanFold) {
6751           // To test for the bad case of the signed shr, see if any
6752           // of the bits shifted in could be tested after the mask.
6753           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6754           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6755           
6756           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6757           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6758                AndCST->getValue()) == 0)
6759             CanFold = true;
6760         }
6761         
6762         if (CanFold) {
6763           Constant *NewCst;
6764           if (Shift->getOpcode() == Instruction::Shl)
6765             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6766           else
6767             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6768           
6769           // Check to see if we are shifting out any of the bits being
6770           // compared.
6771           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6772             // If we shifted bits out, the fold is not going to work out.
6773             // As a special case, check to see if this means that the
6774             // result is always true or false now.
6775             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6776               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6777             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6778               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6779           } else {
6780             ICI.setOperand(1, NewCst);
6781             Constant *NewAndCST;
6782             if (Shift->getOpcode() == Instruction::Shl)
6783               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6784             else
6785               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6786             LHSI->setOperand(1, NewAndCST);
6787             LHSI->setOperand(0, Shift->getOperand(0));
6788             AddToWorkList(Shift); // Shift is dead.
6789             AddUsesToWorkList(ICI);
6790             return &ICI;
6791           }
6792         }
6793       }
6794       
6795       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6796       // preferable because it allows the C<<Y expression to be hoisted out
6797       // of a loop if Y is invariant and X is not.
6798       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6799           ICI.isEquality() && !Shift->isArithmeticShift() &&
6800           !isa<Constant>(Shift->getOperand(0))) {
6801         // Compute C << Y.
6802         Value *NS;
6803         if (Shift->getOpcode() == Instruction::LShr) {
6804           NS = BinaryOperator::CreateShl(AndCST, 
6805                                          Shift->getOperand(1), "tmp");
6806         } else {
6807           // Insert a logical shift.
6808           NS = BinaryOperator::CreateLShr(AndCST,
6809                                           Shift->getOperand(1), "tmp");
6810         }
6811         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6812         
6813         // Compute X & (C << Y).
6814         Instruction *NewAnd = 
6815           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6816         InsertNewInstBefore(NewAnd, ICI);
6817         
6818         ICI.setOperand(0, NewAnd);
6819         return &ICI;
6820       }
6821     }
6822     break;
6823     
6824   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6825     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6826     if (!ShAmt) break;
6827     
6828     uint32_t TypeBits = RHSV.getBitWidth();
6829     
6830     // Check that the shift amount is in range.  If not, don't perform
6831     // undefined shifts.  When the shift is visited it will be
6832     // simplified.
6833     if (ShAmt->uge(TypeBits))
6834       break;
6835     
6836     if (ICI.isEquality()) {
6837       // If we are comparing against bits always shifted out, the
6838       // comparison cannot succeed.
6839       Constant *Comp =
6840         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6841       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6842         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6843         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6844         return ReplaceInstUsesWith(ICI, Cst);
6845       }
6846       
6847       if (LHSI->hasOneUse()) {
6848         // Otherwise strength reduce the shift into an and.
6849         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6850         Constant *Mask =
6851           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6852         
6853         Instruction *AndI =
6854           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6855                                     Mask, LHSI->getName()+".mask");
6856         Value *And = InsertNewInstBefore(AndI, ICI);
6857         return new ICmpInst(ICI.getPredicate(), And,
6858                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
6859       }
6860     }
6861     
6862     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6863     bool TrueIfSigned = false;
6864     if (LHSI->hasOneUse() &&
6865         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6866       // (X << 31) <s 0  --> (X&1) != 0
6867       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6868                                            (TypeBits-ShAmt->getZExtValue()-1));
6869       Instruction *AndI =
6870         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6871                                   Mask, LHSI->getName()+".mask");
6872       Value *And = InsertNewInstBefore(AndI, ICI);
6873       
6874       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6875                           And, Constant::getNullValue(And->getType()));
6876     }
6877     break;
6878   }
6879     
6880   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6881   case Instruction::AShr: {
6882     // Only handle equality comparisons of shift-by-constant.
6883     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6884     if (!ShAmt || !ICI.isEquality()) break;
6885
6886     // Check that the shift amount is in range.  If not, don't perform
6887     // undefined shifts.  When the shift is visited it will be
6888     // simplified.
6889     uint32_t TypeBits = RHSV.getBitWidth();
6890     if (ShAmt->uge(TypeBits))
6891       break;
6892     
6893     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6894       
6895     // If we are comparing against bits always shifted out, the
6896     // comparison cannot succeed.
6897     APInt Comp = RHSV << ShAmtVal;
6898     if (LHSI->getOpcode() == Instruction::LShr)
6899       Comp = Comp.lshr(ShAmtVal);
6900     else
6901       Comp = Comp.ashr(ShAmtVal);
6902     
6903     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6904       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6905       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6906       return ReplaceInstUsesWith(ICI, Cst);
6907     }
6908     
6909     // Otherwise, check to see if the bits shifted out are known to be zero.
6910     // If so, we can compare against the unshifted value:
6911     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6912     if (LHSI->hasOneUse() &&
6913         MaskedValueIsZero(LHSI->getOperand(0), 
6914                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6915       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6916                           ConstantExpr::getShl(RHS, ShAmt));
6917     }
6918       
6919     if (LHSI->hasOneUse()) {
6920       // Otherwise strength reduce the shift into an and.
6921       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6922       Constant *Mask = ConstantInt::get(Val);
6923       
6924       Instruction *AndI =
6925         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6926                                   Mask, LHSI->getName()+".mask");
6927       Value *And = InsertNewInstBefore(AndI, ICI);
6928       return new ICmpInst(ICI.getPredicate(), And,
6929                           ConstantExpr::getShl(RHS, ShAmt));
6930     }
6931     break;
6932   }
6933     
6934   case Instruction::SDiv:
6935   case Instruction::UDiv:
6936     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6937     // Fold this div into the comparison, producing a range check. 
6938     // Determine, based on the divide type, what the range is being 
6939     // checked.  If there is an overflow on the low or high side, remember 
6940     // it, otherwise compute the range [low, hi) bounding the new value.
6941     // See: InsertRangeTest above for the kinds of replacements possible.
6942     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6943       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6944                                           DivRHS))
6945         return R;
6946     break;
6947
6948   case Instruction::Add:
6949     // Fold: icmp pred (add, X, C1), C2
6950
6951     if (!ICI.isEquality()) {
6952       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6953       if (!LHSC) break;
6954       const APInt &LHSV = LHSC->getValue();
6955
6956       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6957                             .subtract(LHSV);
6958
6959       if (ICI.isSignedPredicate()) {
6960         if (CR.getLower().isSignBit()) {
6961           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6962                               ConstantInt::get(CR.getUpper()));
6963         } else if (CR.getUpper().isSignBit()) {
6964           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6965                               ConstantInt::get(CR.getLower()));
6966         }
6967       } else {
6968         if (CR.getLower().isMinValue()) {
6969           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6970                               ConstantInt::get(CR.getUpper()));
6971         } else if (CR.getUpper().isMinValue()) {
6972           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6973                               ConstantInt::get(CR.getLower()));
6974         }
6975       }
6976     }
6977     break;
6978   }
6979   
6980   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6981   if (ICI.isEquality()) {
6982     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6983     
6984     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6985     // the second operand is a constant, simplify a bit.
6986     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6987       switch (BO->getOpcode()) {
6988       case Instruction::SRem:
6989         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6990         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6991           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6992           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6993             Instruction *NewRem =
6994               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6995                                          BO->getName());
6996             InsertNewInstBefore(NewRem, ICI);
6997             return new ICmpInst(ICI.getPredicate(), NewRem, 
6998                                 Constant::getNullValue(BO->getType()));
6999           }
7000         }
7001         break;
7002       case Instruction::Add:
7003         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7004         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7005           if (BO->hasOneUse())
7006             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7007                                 ConstantExpr::getSub(RHS, BOp1C));
7008         } else if (RHSV == 0) {
7009           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7010           // efficiently invertible, or if the add has just this one use.
7011           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7012           
7013           if (Value *NegVal = dyn_castNegVal(BOp1))
7014             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
7015           else if (Value *NegVal = dyn_castNegVal(BOp0))
7016             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
7017           else if (BO->hasOneUse()) {
7018             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
7019             InsertNewInstBefore(Neg, ICI);
7020             Neg->takeName(BO);
7021             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
7022           }
7023         }
7024         break;
7025       case Instruction::Xor:
7026         // For the xor case, we can xor two constants together, eliminating
7027         // the explicit xor.
7028         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7029           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
7030                               ConstantExpr::getXor(RHS, BOC));
7031         
7032         // FALLTHROUGH
7033       case Instruction::Sub:
7034         // Replace (([sub|xor] A, B) != 0) with (A != B)
7035         if (RHSV == 0)
7036           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7037                               BO->getOperand(1));
7038         break;
7039         
7040       case Instruction::Or:
7041         // If bits are being or'd in that are not present in the constant we
7042         // are comparing against, then the comparison could never succeed!
7043         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7044           Constant *NotCI = ConstantExpr::getNot(RHS);
7045           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7046             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
7047                                                              isICMP_NE));
7048         }
7049         break;
7050         
7051       case Instruction::And:
7052         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7053           // If bits are being compared against that are and'd out, then the
7054           // comparison can never succeed!
7055           if ((RHSV & ~BOC->getValue()) != 0)
7056             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
7057                                                              isICMP_NE));
7058           
7059           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7060           if (RHS == BOC && RHSV.isPowerOf2())
7061             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7062                                 ICmpInst::ICMP_NE, LHSI,
7063                                 Constant::getNullValue(RHS->getType()));
7064           
7065           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7066           if (BOC->getValue().isSignBit()) {
7067             Value *X = BO->getOperand(0);
7068             Constant *Zero = Constant::getNullValue(X->getType());
7069             ICmpInst::Predicate pred = isICMP_NE ? 
7070               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7071             return new ICmpInst(pred, X, Zero);
7072           }
7073           
7074           // ((X & ~7) == 0) --> X < 8
7075           if (RHSV == 0 && isHighOnes(BOC)) {
7076             Value *X = BO->getOperand(0);
7077             Constant *NegX = ConstantExpr::getNeg(BOC);
7078             ICmpInst::Predicate pred = isICMP_NE ? 
7079               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7080             return new ICmpInst(pred, X, NegX);
7081           }
7082         }
7083       default: break;
7084       }
7085     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7086       // Handle icmp {eq|ne} <intrinsic>, intcst.
7087       if (II->getIntrinsicID() == Intrinsic::bswap) {
7088         AddToWorkList(II);
7089         ICI.setOperand(0, II->getOperand(1));
7090         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
7091         return &ICI;
7092       }
7093     }
7094   }
7095   return 0;
7096 }
7097
7098 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7099 /// We only handle extending casts so far.
7100 ///
7101 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7102   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7103   Value *LHSCIOp        = LHSCI->getOperand(0);
7104   const Type *SrcTy     = LHSCIOp->getType();
7105   const Type *DestTy    = LHSCI->getType();
7106   Value *RHSCIOp;
7107
7108   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7109   // integer type is the same size as the pointer type.
7110   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7111       getTargetData().getPointerSizeInBits() == 
7112          cast<IntegerType>(DestTy)->getBitWidth()) {
7113     Value *RHSOp = 0;
7114     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7115       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7116     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7117       RHSOp = RHSC->getOperand(0);
7118       // If the pointer types don't match, insert a bitcast.
7119       if (LHSCIOp->getType() != RHSOp->getType())
7120         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
7121     }
7122
7123     if (RHSOp)
7124       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7125   }
7126   
7127   // The code below only handles extension cast instructions, so far.
7128   // Enforce this.
7129   if (LHSCI->getOpcode() != Instruction::ZExt &&
7130       LHSCI->getOpcode() != Instruction::SExt)
7131     return 0;
7132
7133   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7134   bool isSignedCmp = ICI.isSignedPredicate();
7135
7136   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7137     // Not an extension from the same type?
7138     RHSCIOp = CI->getOperand(0);
7139     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7140       return 0;
7141     
7142     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7143     // and the other is a zext), then we can't handle this.
7144     if (CI->getOpcode() != LHSCI->getOpcode())
7145       return 0;
7146
7147     // Deal with equality cases early.
7148     if (ICI.isEquality())
7149       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7150
7151     // A signed comparison of sign extended values simplifies into a
7152     // signed comparison.
7153     if (isSignedCmp && isSignedExt)
7154       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7155
7156     // The other three cases all fold into an unsigned comparison.
7157     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7158   }
7159
7160   // If we aren't dealing with a constant on the RHS, exit early
7161   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7162   if (!CI)
7163     return 0;
7164
7165   // Compute the constant that would happen if we truncated to SrcTy then
7166   // reextended to DestTy.
7167   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7168   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
7169
7170   // If the re-extended constant didn't change...
7171   if (Res2 == CI) {
7172     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7173     // For example, we might have:
7174     //    %A = sext i16 %X to i32
7175     //    %B = icmp ugt i32 %A, 1330
7176     // It is incorrect to transform this into 
7177     //    %B = icmp ugt i16 %X, 1330
7178     // because %A may have negative value. 
7179     //
7180     // However, we allow this when the compare is EQ/NE, because they are
7181     // signless.
7182     if (isSignedExt == isSignedCmp || ICI.isEquality())
7183       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7184     return 0;
7185   }
7186
7187   // The re-extended constant changed so the constant cannot be represented 
7188   // in the shorter type. Consequently, we cannot emit a simple comparison.
7189
7190   // First, handle some easy cases. We know the result cannot be equal at this
7191   // point so handle the ICI.isEquality() cases
7192   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7193     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
7194   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7195     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
7196
7197   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7198   // should have been folded away previously and not enter in here.
7199   Value *Result;
7200   if (isSignedCmp) {
7201     // We're performing a signed comparison.
7202     if (cast<ConstantInt>(CI)->getValue().isNegative())
7203       Result = ConstantInt::getFalse();          // X < (small) --> false
7204     else
7205       Result = ConstantInt::getTrue();           // X < (large) --> true
7206   } else {
7207     // We're performing an unsigned comparison.
7208     if (isSignedExt) {
7209       // We're performing an unsigned comp with a sign extended value.
7210       // This is true if the input is >= 0. [aka >s -1]
7211       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
7212       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
7213                                    NegOne, ICI.getName()), ICI);
7214     } else {
7215       // Unsigned extend & unsigned compare -> always true.
7216       Result = ConstantInt::getTrue();
7217     }
7218   }
7219
7220   // Finally, return the value computed.
7221   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7222       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7223     return ReplaceInstUsesWith(ICI, Result);
7224
7225   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7226           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7227          "ICmp should be folded!");
7228   if (Constant *CI = dyn_cast<Constant>(Result))
7229     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7230   return BinaryOperator::CreateNot(Result);
7231 }
7232
7233 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7234   return commonShiftTransforms(I);
7235 }
7236
7237 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7238   return commonShiftTransforms(I);
7239 }
7240
7241 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7242   if (Instruction *R = commonShiftTransforms(I))
7243     return R;
7244   
7245   Value *Op0 = I.getOperand(0);
7246   
7247   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7248   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7249     if (CSI->isAllOnesValue())
7250       return ReplaceInstUsesWith(I, CSI);
7251
7252   // See if we can turn a signed shr into an unsigned shr.
7253   if (MaskedValueIsZero(Op0,
7254                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7255     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7256
7257   // Arithmetic shifting an all-sign-bit value is a no-op.
7258   unsigned NumSignBits = ComputeNumSignBits(Op0);
7259   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7260     return ReplaceInstUsesWith(I, Op0);
7261
7262   return 0;
7263 }
7264
7265 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7266   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7267   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7268
7269   // shl X, 0 == X and shr X, 0 == X
7270   // shl 0, X == 0 and shr 0, X == 0
7271   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7272       Op0 == Constant::getNullValue(Op0->getType()))
7273     return ReplaceInstUsesWith(I, Op0);
7274   
7275   if (isa<UndefValue>(Op0)) {            
7276     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7277       return ReplaceInstUsesWith(I, Op0);
7278     else                                    // undef << X -> 0, undef >>u X -> 0
7279       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7280   }
7281   if (isa<UndefValue>(Op1)) {
7282     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7283       return ReplaceInstUsesWith(I, Op0);          
7284     else                                     // X << undef, X >>u undef -> 0
7285       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7286   }
7287
7288   // See if we can fold away this shift.
7289   if (SimplifyDemandedInstructionBits(I))
7290     return &I;
7291
7292   // Try to fold constant and into select arguments.
7293   if (isa<Constant>(Op0))
7294     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7295       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7296         return R;
7297
7298   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7299     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7300       return Res;
7301   return 0;
7302 }
7303
7304 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7305                                                BinaryOperator &I) {
7306   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7307
7308   // See if we can simplify any instructions used by the instruction whose sole 
7309   // purpose is to compute bits we don't care about.
7310   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7311   
7312   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7313   // a signed shift.
7314   //
7315   if (Op1->uge(TypeBits)) {
7316     if (I.getOpcode() != Instruction::AShr)
7317       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7318     else {
7319       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7320       return &I;
7321     }
7322   }
7323   
7324   // ((X*C1) << C2) == (X * (C1 << C2))
7325   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7326     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7327       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7328         return BinaryOperator::CreateMul(BO->getOperand(0),
7329                                          ConstantExpr::getShl(BOOp, Op1));
7330   
7331   // Try to fold constant and into select arguments.
7332   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7333     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7334       return R;
7335   if (isa<PHINode>(Op0))
7336     if (Instruction *NV = FoldOpIntoPhi(I))
7337       return NV;
7338   
7339   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7340   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7341     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7342     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7343     // place.  Don't try to do this transformation in this case.  Also, we
7344     // require that the input operand is a shift-by-constant so that we have
7345     // confidence that the shifts will get folded together.  We could do this
7346     // xform in more cases, but it is unlikely to be profitable.
7347     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7348         isa<ConstantInt>(TrOp->getOperand(1))) {
7349       // Okay, we'll do this xform.  Make the shift of shift.
7350       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7351       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7352                                                 I.getName());
7353       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7354
7355       // For logical shifts, the truncation has the effect of making the high
7356       // part of the register be zeros.  Emulate this by inserting an AND to
7357       // clear the top bits as needed.  This 'and' will usually be zapped by
7358       // other xforms later if dead.
7359       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7360       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7361       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7362       
7363       // The mask we constructed says what the trunc would do if occurring
7364       // between the shifts.  We want to know the effect *after* the second
7365       // shift.  We know that it is a logical shift by a constant, so adjust the
7366       // mask as appropriate.
7367       if (I.getOpcode() == Instruction::Shl)
7368         MaskV <<= Op1->getZExtValue();
7369       else {
7370         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7371         MaskV = MaskV.lshr(Op1->getZExtValue());
7372       }
7373
7374       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
7375                                                    TI->getName());
7376       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7377
7378       // Return the value truncated to the interesting size.
7379       return new TruncInst(And, I.getType());
7380     }
7381   }
7382   
7383   if (Op0->hasOneUse()) {
7384     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7385       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7386       Value *V1, *V2;
7387       ConstantInt *CC;
7388       switch (Op0BO->getOpcode()) {
7389         default: break;
7390         case Instruction::Add:
7391         case Instruction::And:
7392         case Instruction::Or:
7393         case Instruction::Xor: {
7394           // These operators commute.
7395           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7396           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7397               match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
7398             Instruction *YS = BinaryOperator::CreateShl(
7399                                             Op0BO->getOperand(0), Op1,
7400                                             Op0BO->getName());
7401             InsertNewInstBefore(YS, I); // (Y << C)
7402             Instruction *X = 
7403               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7404                                      Op0BO->getOperand(1)->getName());
7405             InsertNewInstBefore(X, I);  // (X + (Y << C))
7406             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7407             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7408                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7409           }
7410           
7411           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7412           Value *Op0BOOp1 = Op0BO->getOperand(1);
7413           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7414               match(Op0BOOp1, 
7415                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7416                           m_ConstantInt(CC))) &&
7417               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7418             Instruction *YS = BinaryOperator::CreateShl(
7419                                                      Op0BO->getOperand(0), Op1,
7420                                                      Op0BO->getName());
7421             InsertNewInstBefore(YS, I); // (Y << C)
7422             Instruction *XM =
7423               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7424                                         V1->getName()+".mask");
7425             InsertNewInstBefore(XM, I); // X & (CC << C)
7426             
7427             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7428           }
7429         }
7430           
7431         // FALL THROUGH.
7432         case Instruction::Sub: {
7433           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7434           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7435               match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
7436             Instruction *YS = BinaryOperator::CreateShl(
7437                                                      Op0BO->getOperand(1), Op1,
7438                                                      Op0BO->getName());
7439             InsertNewInstBefore(YS, I); // (Y << C)
7440             Instruction *X =
7441               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7442                                      Op0BO->getOperand(0)->getName());
7443             InsertNewInstBefore(X, I);  // (X + (Y << C))
7444             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7445             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7446                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7447           }
7448           
7449           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7450           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7451               match(Op0BO->getOperand(0),
7452                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7453                           m_ConstantInt(CC))) && V2 == Op1 &&
7454               cast<BinaryOperator>(Op0BO->getOperand(0))
7455                   ->getOperand(0)->hasOneUse()) {
7456             Instruction *YS = BinaryOperator::CreateShl(
7457                                                      Op0BO->getOperand(1), Op1,
7458                                                      Op0BO->getName());
7459             InsertNewInstBefore(YS, I); // (Y << C)
7460             Instruction *XM =
7461               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7462                                         V1->getName()+".mask");
7463             InsertNewInstBefore(XM, I); // X & (CC << C)
7464             
7465             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7466           }
7467           
7468           break;
7469         }
7470       }
7471       
7472       
7473       // If the operand is an bitwise operator with a constant RHS, and the
7474       // shift is the only use, we can pull it out of the shift.
7475       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7476         bool isValid = true;     // Valid only for And, Or, Xor
7477         bool highBitSet = false; // Transform if high bit of constant set?
7478         
7479         switch (Op0BO->getOpcode()) {
7480           default: isValid = false; break;   // Do not perform transform!
7481           case Instruction::Add:
7482             isValid = isLeftShift;
7483             break;
7484           case Instruction::Or:
7485           case Instruction::Xor:
7486             highBitSet = false;
7487             break;
7488           case Instruction::And:
7489             highBitSet = true;
7490             break;
7491         }
7492         
7493         // If this is a signed shift right, and the high bit is modified
7494         // by the logical operation, do not perform the transformation.
7495         // The highBitSet boolean indicates the value of the high bit of
7496         // the constant which would cause it to be modified for this
7497         // operation.
7498         //
7499         if (isValid && I.getOpcode() == Instruction::AShr)
7500           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7501         
7502         if (isValid) {
7503           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7504           
7505           Instruction *NewShift =
7506             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7507           InsertNewInstBefore(NewShift, I);
7508           NewShift->takeName(Op0BO);
7509           
7510           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7511                                         NewRHS);
7512         }
7513       }
7514     }
7515   }
7516   
7517   // Find out if this is a shift of a shift by a constant.
7518   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7519   if (ShiftOp && !ShiftOp->isShift())
7520     ShiftOp = 0;
7521   
7522   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7523     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7524     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7525     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7526     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7527     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7528     Value *X = ShiftOp->getOperand(0);
7529     
7530     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7531     
7532     const IntegerType *Ty = cast<IntegerType>(I.getType());
7533     
7534     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7535     if (I.getOpcode() == ShiftOp->getOpcode()) {
7536       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7537       // saturates.
7538       if (AmtSum >= TypeBits) {
7539         if (I.getOpcode() != Instruction::AShr)
7540           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7541         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7542       }
7543       
7544       return BinaryOperator::Create(I.getOpcode(), X,
7545                                     ConstantInt::get(Ty, AmtSum));
7546     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7547                I.getOpcode() == Instruction::AShr) {
7548       if (AmtSum >= TypeBits)
7549         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7550       
7551       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7552       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7553     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7554                I.getOpcode() == Instruction::LShr) {
7555       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7556       if (AmtSum >= TypeBits)
7557         AmtSum = TypeBits-1;
7558       
7559       Instruction *Shift =
7560         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7561       InsertNewInstBefore(Shift, I);
7562
7563       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7564       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7565     }
7566     
7567     // Okay, if we get here, one shift must be left, and the other shift must be
7568     // right.  See if the amounts are equal.
7569     if (ShiftAmt1 == ShiftAmt2) {
7570       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7571       if (I.getOpcode() == Instruction::Shl) {
7572         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7573         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7574       }
7575       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7576       if (I.getOpcode() == Instruction::LShr) {
7577         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7578         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7579       }
7580       // We can simplify ((X << C) >>s C) into a trunc + sext.
7581       // NOTE: we could do this for any C, but that would make 'unusual' integer
7582       // types.  For now, just stick to ones well-supported by the code
7583       // generators.
7584       const Type *SExtType = 0;
7585       switch (Ty->getBitWidth() - ShiftAmt1) {
7586       case 1  :
7587       case 8  :
7588       case 16 :
7589       case 32 :
7590       case 64 :
7591       case 128:
7592         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7593         break;
7594       default: break;
7595       }
7596       if (SExtType) {
7597         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7598         InsertNewInstBefore(NewTrunc, I);
7599         return new SExtInst(NewTrunc, Ty);
7600       }
7601       // Otherwise, we can't handle it yet.
7602     } else if (ShiftAmt1 < ShiftAmt2) {
7603       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7604       
7605       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7606       if (I.getOpcode() == Instruction::Shl) {
7607         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7608                ShiftOp->getOpcode() == Instruction::AShr);
7609         Instruction *Shift =
7610           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7611         InsertNewInstBefore(Shift, I);
7612         
7613         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7614         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7615       }
7616       
7617       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7618       if (I.getOpcode() == Instruction::LShr) {
7619         assert(ShiftOp->getOpcode() == Instruction::Shl);
7620         Instruction *Shift =
7621           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7622         InsertNewInstBefore(Shift, I);
7623         
7624         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7625         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7626       }
7627       
7628       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7629     } else {
7630       assert(ShiftAmt2 < ShiftAmt1);
7631       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7632
7633       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7634       if (I.getOpcode() == Instruction::Shl) {
7635         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7636                ShiftOp->getOpcode() == Instruction::AShr);
7637         Instruction *Shift =
7638           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7639                                  ConstantInt::get(Ty, ShiftDiff));
7640         InsertNewInstBefore(Shift, I);
7641         
7642         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7643         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7644       }
7645       
7646       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7647       if (I.getOpcode() == Instruction::LShr) {
7648         assert(ShiftOp->getOpcode() == Instruction::Shl);
7649         Instruction *Shift =
7650           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7651         InsertNewInstBefore(Shift, I);
7652         
7653         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7654         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7655       }
7656       
7657       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7658     }
7659   }
7660   return 0;
7661 }
7662
7663
7664 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7665 /// expression.  If so, decompose it, returning some value X, such that Val is
7666 /// X*Scale+Offset.
7667 ///
7668 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7669                                         int &Offset) {
7670   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7671   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7672     Offset = CI->getZExtValue();
7673     Scale  = 0;
7674     return ConstantInt::get(Type::Int32Ty, 0);
7675   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7676     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7677       if (I->getOpcode() == Instruction::Shl) {
7678         // This is a value scaled by '1 << the shift amt'.
7679         Scale = 1U << RHS->getZExtValue();
7680         Offset = 0;
7681         return I->getOperand(0);
7682       } else if (I->getOpcode() == Instruction::Mul) {
7683         // This value is scaled by 'RHS'.
7684         Scale = RHS->getZExtValue();
7685         Offset = 0;
7686         return I->getOperand(0);
7687       } else if (I->getOpcode() == Instruction::Add) {
7688         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7689         // where C1 is divisible by C2.
7690         unsigned SubScale;
7691         Value *SubVal = 
7692           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7693         Offset += RHS->getZExtValue();
7694         Scale = SubScale;
7695         return SubVal;
7696       }
7697     }
7698   }
7699
7700   // Otherwise, we can't look past this.
7701   Scale = 1;
7702   Offset = 0;
7703   return Val;
7704 }
7705
7706
7707 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7708 /// try to eliminate the cast by moving the type information into the alloc.
7709 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7710                                                    AllocationInst &AI) {
7711   const PointerType *PTy = cast<PointerType>(CI.getType());
7712   
7713   // Remove any uses of AI that are dead.
7714   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7715   
7716   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7717     Instruction *User = cast<Instruction>(*UI++);
7718     if (isInstructionTriviallyDead(User)) {
7719       while (UI != E && *UI == User)
7720         ++UI; // If this instruction uses AI more than once, don't break UI.
7721       
7722       ++NumDeadInst;
7723       DOUT << "IC: DCE: " << *User;
7724       EraseInstFromFunction(*User);
7725     }
7726   }
7727   
7728   // Get the type really allocated and the type casted to.
7729   const Type *AllocElTy = AI.getAllocatedType();
7730   const Type *CastElTy = PTy->getElementType();
7731   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7732
7733   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7734   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7735   if (CastElTyAlign < AllocElTyAlign) return 0;
7736
7737   // If the allocation has multiple uses, only promote it if we are strictly
7738   // increasing the alignment of the resultant allocation.  If we keep it the
7739   // same, we open the door to infinite loops of various kinds.  (A reference
7740   // from a dbg.declare doesn't count as a use for this purpose.)
7741   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7742       CastElTyAlign == AllocElTyAlign) return 0;
7743
7744   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7745   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7746   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7747
7748   // See if we can satisfy the modulus by pulling a scale out of the array
7749   // size argument.
7750   unsigned ArraySizeScale;
7751   int ArrayOffset;
7752   Value *NumElements = // See if the array size is a decomposable linear expr.
7753     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7754  
7755   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7756   // do the xform.
7757   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7758       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7759
7760   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7761   Value *Amt = 0;
7762   if (Scale == 1) {
7763     Amt = NumElements;
7764   } else {
7765     // If the allocation size is constant, form a constant mul expression
7766     Amt = ConstantInt::get(Type::Int32Ty, Scale);
7767     if (isa<ConstantInt>(NumElements))
7768       Amt = ConstantExpr::getMul(cast<ConstantInt>(NumElements),
7769                                  cast<ConstantInt>(Amt));
7770     // otherwise multiply the amount and the number of elements
7771     else {
7772       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7773       Amt = InsertNewInstBefore(Tmp, AI);
7774     }
7775   }
7776   
7777   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7778     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
7779     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7780     Amt = InsertNewInstBefore(Tmp, AI);
7781   }
7782   
7783   AllocationInst *New;
7784   if (isa<MallocInst>(AI))
7785     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7786   else
7787     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7788   InsertNewInstBefore(New, AI);
7789   New->takeName(&AI);
7790   
7791   // If the allocation has one real use plus a dbg.declare, just remove the
7792   // declare.
7793   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7794     EraseInstFromFunction(*DI);
7795   }
7796   // If the allocation has multiple real uses, insert a cast and change all
7797   // things that used it to use the new cast.  This will also hack on CI, but it
7798   // will die soon.
7799   else if (!AI.hasOneUse()) {
7800     AddUsesToWorkList(AI);
7801     // New is the allocation instruction, pointer typed. AI is the original
7802     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7803     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7804     InsertNewInstBefore(NewCast, AI);
7805     AI.replaceAllUsesWith(NewCast);
7806   }
7807   return ReplaceInstUsesWith(CI, New);
7808 }
7809
7810 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7811 /// and return it as type Ty without inserting any new casts and without
7812 /// changing the computed value.  This is used by code that tries to decide
7813 /// whether promoting or shrinking integer operations to wider or smaller types
7814 /// will allow us to eliminate a truncate or extend.
7815 ///
7816 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7817 /// extension operation if Ty is larger.
7818 ///
7819 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7820 /// should return true if trunc(V) can be computed by computing V in the smaller
7821 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7822 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7823 /// efficiently truncated.
7824 ///
7825 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7826 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7827 /// the final result.
7828 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7829                                               unsigned CastOpc,
7830                                               int &NumCastsRemoved){
7831   // We can always evaluate constants in another type.
7832   if (isa<Constant>(V))
7833     return true;
7834   
7835   Instruction *I = dyn_cast<Instruction>(V);
7836   if (!I) return false;
7837   
7838   const Type *OrigTy = V->getType();
7839   
7840   // If this is an extension or truncate, we can often eliminate it.
7841   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7842     // If this is a cast from the destination type, we can trivially eliminate
7843     // it, and this will remove a cast overall.
7844     if (I->getOperand(0)->getType() == Ty) {
7845       // If the first operand is itself a cast, and is eliminable, do not count
7846       // this as an eliminable cast.  We would prefer to eliminate those two
7847       // casts first.
7848       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7849         ++NumCastsRemoved;
7850       return true;
7851     }
7852   }
7853
7854   // We can't extend or shrink something that has multiple uses: doing so would
7855   // require duplicating the instruction in general, which isn't profitable.
7856   if (!I->hasOneUse()) return false;
7857
7858   unsigned Opc = I->getOpcode();
7859   switch (Opc) {
7860   case Instruction::Add:
7861   case Instruction::Sub:
7862   case Instruction::Mul:
7863   case Instruction::And:
7864   case Instruction::Or:
7865   case Instruction::Xor:
7866     // These operators can all arbitrarily be extended or truncated.
7867     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7868                                       NumCastsRemoved) &&
7869            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7870                                       NumCastsRemoved);
7871
7872   case Instruction::Shl:
7873     // If we are truncating the result of this SHL, and if it's a shift of a
7874     // constant amount, we can always perform a SHL in a smaller type.
7875     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7876       uint32_t BitWidth = Ty->getScalarSizeInBits();
7877       if (BitWidth < OrigTy->getScalarSizeInBits() &&
7878           CI->getLimitedValue(BitWidth) < BitWidth)
7879         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7880                                           NumCastsRemoved);
7881     }
7882     break;
7883   case Instruction::LShr:
7884     // If this is a truncate of a logical shr, we can truncate it to a smaller
7885     // lshr iff we know that the bits we would otherwise be shifting in are
7886     // already zeros.
7887     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7888       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7889       uint32_t BitWidth = Ty->getScalarSizeInBits();
7890       if (BitWidth < OrigBitWidth &&
7891           MaskedValueIsZero(I->getOperand(0),
7892             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7893           CI->getLimitedValue(BitWidth) < BitWidth) {
7894         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7895                                           NumCastsRemoved);
7896       }
7897     }
7898     break;
7899   case Instruction::ZExt:
7900   case Instruction::SExt:
7901   case Instruction::Trunc:
7902     // If this is the same kind of case as our original (e.g. zext+zext), we
7903     // can safely replace it.  Note that replacing it does not reduce the number
7904     // of casts in the input.
7905     if (Opc == CastOpc)
7906       return true;
7907
7908     // sext (zext ty1), ty2 -> zext ty2
7909     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7910       return true;
7911     break;
7912   case Instruction::Select: {
7913     SelectInst *SI = cast<SelectInst>(I);
7914     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7915                                       NumCastsRemoved) &&
7916            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7917                                       NumCastsRemoved);
7918   }
7919   case Instruction::PHI: {
7920     // We can change a phi if we can change all operands.
7921     PHINode *PN = cast<PHINode>(I);
7922     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7923       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7924                                       NumCastsRemoved))
7925         return false;
7926     return true;
7927   }
7928   default:
7929     // TODO: Can handle more cases here.
7930     break;
7931   }
7932   
7933   return false;
7934 }
7935
7936 /// EvaluateInDifferentType - Given an expression that 
7937 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7938 /// evaluate the expression.
7939 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7940                                              bool isSigned) {
7941   if (Constant *C = dyn_cast<Constant>(V))
7942     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7943
7944   // Otherwise, it must be an instruction.
7945   Instruction *I = cast<Instruction>(V);
7946   Instruction *Res = 0;
7947   unsigned Opc = I->getOpcode();
7948   switch (Opc) {
7949   case Instruction::Add:
7950   case Instruction::Sub:
7951   case Instruction::Mul:
7952   case Instruction::And:
7953   case Instruction::Or:
7954   case Instruction::Xor:
7955   case Instruction::AShr:
7956   case Instruction::LShr:
7957   case Instruction::Shl: {
7958     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7959     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7960     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7961     break;
7962   }    
7963   case Instruction::Trunc:
7964   case Instruction::ZExt:
7965   case Instruction::SExt:
7966     // If the source type of the cast is the type we're trying for then we can
7967     // just return the source.  There's no need to insert it because it is not
7968     // new.
7969     if (I->getOperand(0)->getType() == Ty)
7970       return I->getOperand(0);
7971     
7972     // Otherwise, must be the same type of cast, so just reinsert a new one.
7973     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7974                            Ty);
7975     break;
7976   case Instruction::Select: {
7977     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7978     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7979     Res = SelectInst::Create(I->getOperand(0), True, False);
7980     break;
7981   }
7982   case Instruction::PHI: {
7983     PHINode *OPN = cast<PHINode>(I);
7984     PHINode *NPN = PHINode::Create(Ty);
7985     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7986       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7987       NPN->addIncoming(V, OPN->getIncomingBlock(i));
7988     }
7989     Res = NPN;
7990     break;
7991   }
7992   default: 
7993     // TODO: Can handle more cases here.
7994     assert(0 && "Unreachable!");
7995     break;
7996   }
7997   
7998   Res->takeName(I);
7999   return InsertNewInstBefore(Res, *I);
8000 }
8001
8002 /// @brief Implement the transforms common to all CastInst visitors.
8003 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8004   Value *Src = CI.getOperand(0);
8005
8006   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8007   // eliminate it now.
8008   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8009     if (Instruction::CastOps opc = 
8010         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8011       // The first cast (CSrc) is eliminable so we need to fix up or replace
8012       // the second cast (CI). CSrc will then have a good chance of being dead.
8013       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8014     }
8015   }
8016
8017   // If we are casting a select then fold the cast into the select
8018   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8019     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8020       return NV;
8021
8022   // If we are casting a PHI then fold the cast into the PHI
8023   if (isa<PHINode>(Src))
8024     if (Instruction *NV = FoldOpIntoPhi(CI))
8025       return NV;
8026   
8027   return 0;
8028 }
8029
8030 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8031 /// or not there is a sequence of GEP indices into the type that will land us at
8032 /// the specified offset.  If so, fill them into NewIndices and return the
8033 /// resultant element type, otherwise return null.
8034 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8035                                        SmallVectorImpl<Value*> &NewIndices,
8036                                        const TargetData *TD) {
8037   if (!Ty->isSized()) return 0;
8038   
8039   // Start with the index over the outer type.  Note that the type size
8040   // might be zero (even if the offset isn't zero) if the indexed type
8041   // is something like [0 x {int, int}]
8042   const Type *IntPtrTy = TD->getIntPtrType();
8043   int64_t FirstIdx = 0;
8044   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8045     FirstIdx = Offset/TySize;
8046     Offset -= FirstIdx*TySize;
8047     
8048     // Handle hosts where % returns negative instead of values [0..TySize).
8049     if (Offset < 0) {
8050       --FirstIdx;
8051       Offset += TySize;
8052       assert(Offset >= 0);
8053     }
8054     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8055   }
8056   
8057   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8058     
8059   // Index into the types.  If we fail, set OrigBase to null.
8060   while (Offset) {
8061     // Indexing into tail padding between struct/array elements.
8062     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8063       return 0;
8064     
8065     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8066       const StructLayout *SL = TD->getStructLayout(STy);
8067       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8068              "Offset must stay within the indexed type");
8069       
8070       unsigned Elt = SL->getElementContainingOffset(Offset);
8071       NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
8072       
8073       Offset -= SL->getElementOffset(Elt);
8074       Ty = STy->getElementType(Elt);
8075     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8076       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8077       assert(EltSize && "Cannot index into a zero-sized array");
8078       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8079       Offset %= EltSize;
8080       Ty = AT->getElementType();
8081     } else {
8082       // Otherwise, we can't index into the middle of this atomic type, bail.
8083       return 0;
8084     }
8085   }
8086   
8087   return Ty;
8088 }
8089
8090 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8091 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8092   Value *Src = CI.getOperand(0);
8093   
8094   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8095     // If casting the result of a getelementptr instruction with no offset, turn
8096     // this into a cast of the original pointer!
8097     if (GEP->hasAllZeroIndices()) {
8098       // Changing the cast operand is usually not a good idea but it is safe
8099       // here because the pointer operand is being replaced with another 
8100       // pointer operand so the opcode doesn't need to change.
8101       AddToWorkList(GEP);
8102       CI.setOperand(0, GEP->getOperand(0));
8103       return &CI;
8104     }
8105     
8106     // If the GEP has a single use, and the base pointer is a bitcast, and the
8107     // GEP computes a constant offset, see if we can convert these three
8108     // instructions into fewer.  This typically happens with unions and other
8109     // non-type-safe code.
8110     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8111       if (GEP->hasAllConstantIndices()) {
8112         // We are guaranteed to get a constant from EmitGEPOffset.
8113         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8114         int64_t Offset = OffsetV->getSExtValue();
8115         
8116         // Get the base pointer input of the bitcast, and the type it points to.
8117         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8118         const Type *GEPIdxTy =
8119           cast<PointerType>(OrigBase->getType())->getElementType();
8120         SmallVector<Value*, 8> NewIndices;
8121         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
8122           // If we were able to index down into an element, create the GEP
8123           // and bitcast the result.  This eliminates one bitcast, potentially
8124           // two.
8125           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
8126                                                         NewIndices.begin(),
8127                                                         NewIndices.end(), "");
8128           InsertNewInstBefore(NGEP, CI);
8129           NGEP->takeName(GEP);
8130           
8131           if (isa<BitCastInst>(CI))
8132             return new BitCastInst(NGEP, CI.getType());
8133           assert(isa<PtrToIntInst>(CI));
8134           return new PtrToIntInst(NGEP, CI.getType());
8135         }
8136       }      
8137     }
8138   }
8139     
8140   return commonCastTransforms(CI);
8141 }
8142
8143 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8144 /// type like i42.  We don't want to introduce operations on random non-legal
8145 /// integer types where they don't already exist in the code.  In the future,
8146 /// we should consider making this based off target-data, so that 32-bit targets
8147 /// won't get i64 operations etc.
8148 static bool isSafeIntegerType(const Type *Ty) {
8149   switch (Ty->getPrimitiveSizeInBits()) {
8150   case 8:
8151   case 16:
8152   case 32:
8153   case 64:
8154     return true;
8155   default: 
8156     return false;
8157   }
8158 }
8159
8160 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
8161 /// integer types. This function implements the common transforms for all those
8162 /// cases.
8163 /// @brief Implement the transforms common to CastInst with integer operands
8164 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8165   if (Instruction *Result = commonCastTransforms(CI))
8166     return Result;
8167
8168   Value *Src = CI.getOperand(0);
8169   const Type *SrcTy = Src->getType();
8170   const Type *DestTy = CI.getType();
8171   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8172   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8173
8174   // See if we can simplify any instructions used by the LHS whose sole 
8175   // purpose is to compute bits we don't care about.
8176   if (SimplifyDemandedInstructionBits(CI))
8177     return &CI;
8178
8179   // If the source isn't an instruction or has more than one use then we
8180   // can't do anything more. 
8181   Instruction *SrcI = dyn_cast<Instruction>(Src);
8182   if (!SrcI || !Src->hasOneUse())
8183     return 0;
8184
8185   // Attempt to propagate the cast into the instruction for int->int casts.
8186   int NumCastsRemoved = 0;
8187   if (!isa<BitCastInst>(CI) &&
8188       // Only do this if the dest type is a simple type, don't convert the
8189       // expression tree to something weird like i93 unless the source is also
8190       // strange.
8191       (isSafeIntegerType(DestTy->getScalarType()) ||
8192        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8193       CanEvaluateInDifferentType(SrcI, DestTy,
8194                                  CI.getOpcode(), NumCastsRemoved)) {
8195     // If this cast is a truncate, evaluting in a different type always
8196     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8197     // we need to do an AND to maintain the clear top-part of the computation,
8198     // so we require that the input have eliminated at least one cast.  If this
8199     // is a sign extension, we insert two new casts (to do the extension) so we
8200     // require that two casts have been eliminated.
8201     bool DoXForm = false;
8202     bool JustReplace = false;
8203     switch (CI.getOpcode()) {
8204     default:
8205       // All the others use floating point so we shouldn't actually 
8206       // get here because of the check above.
8207       assert(0 && "Unknown cast type");
8208     case Instruction::Trunc:
8209       DoXForm = true;
8210       break;
8211     case Instruction::ZExt: {
8212       DoXForm = NumCastsRemoved >= 1;
8213       if (!DoXForm && 0) {
8214         // If it's unnecessary to issue an AND to clear the high bits, it's
8215         // always profitable to do this xform.
8216         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8217         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8218         if (MaskedValueIsZero(TryRes, Mask))
8219           return ReplaceInstUsesWith(CI, TryRes);
8220         
8221         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8222           if (TryI->use_empty())
8223             EraseInstFromFunction(*TryI);
8224       }
8225       break;
8226     }
8227     case Instruction::SExt: {
8228       DoXForm = NumCastsRemoved >= 2;
8229       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8230         // If we do not have to emit the truncate + sext pair, then it's always
8231         // profitable to do this xform.
8232         //
8233         // It's not safe to eliminate the trunc + sext pair if one of the
8234         // eliminated cast is a truncate. e.g.
8235         // t2 = trunc i32 t1 to i16
8236         // t3 = sext i16 t2 to i32
8237         // !=
8238         // i32 t1
8239         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8240         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8241         if (NumSignBits > (DestBitSize - SrcBitSize))
8242           return ReplaceInstUsesWith(CI, TryRes);
8243         
8244         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8245           if (TryI->use_empty())
8246             EraseInstFromFunction(*TryI);
8247       }
8248       break;
8249     }
8250     }
8251     
8252     if (DoXForm) {
8253       DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8254            << " cast: " << CI;
8255       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8256                                            CI.getOpcode() == Instruction::SExt);
8257       if (JustReplace)
8258         // Just replace this cast with the result.
8259         return ReplaceInstUsesWith(CI, Res);
8260
8261       assert(Res->getType() == DestTy);
8262       switch (CI.getOpcode()) {
8263       default: assert(0 && "Unknown cast type!");
8264       case Instruction::Trunc:
8265       case Instruction::BitCast:
8266         // Just replace this cast with the result.
8267         return ReplaceInstUsesWith(CI, Res);
8268       case Instruction::ZExt: {
8269         assert(SrcBitSize < DestBitSize && "Not a zext?");
8270
8271         // If the high bits are already zero, just replace this cast with the
8272         // result.
8273         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8274         if (MaskedValueIsZero(Res, Mask))
8275           return ReplaceInstUsesWith(CI, Res);
8276
8277         // We need to emit an AND to clear the high bits.
8278         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
8279                                                             SrcBitSize));
8280         return BinaryOperator::CreateAnd(Res, C);
8281       }
8282       case Instruction::SExt: {
8283         // If the high bits are already filled with sign bit, just replace this
8284         // cast with the result.
8285         unsigned NumSignBits = ComputeNumSignBits(Res);
8286         if (NumSignBits > (DestBitSize - SrcBitSize))
8287           return ReplaceInstUsesWith(CI, Res);
8288
8289         // We need to emit a cast to truncate, then a cast to sext.
8290         return CastInst::Create(Instruction::SExt,
8291             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8292                              CI), DestTy);
8293       }
8294       }
8295     }
8296   }
8297   
8298   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8299   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8300
8301   switch (SrcI->getOpcode()) {
8302   case Instruction::Add:
8303   case Instruction::Mul:
8304   case Instruction::And:
8305   case Instruction::Or:
8306   case Instruction::Xor:
8307     // If we are discarding information, rewrite.
8308     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8309       // Don't insert two casts if they cannot be eliminated.  We allow 
8310       // two casts to be inserted if the sizes are the same.  This could 
8311       // only be converting signedness, which is a noop.
8312       if (DestBitSize == SrcBitSize || 
8313           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8314           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8315         Instruction::CastOps opcode = CI.getOpcode();
8316         Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8317         Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8318         return BinaryOperator::Create(
8319             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8320       }
8321     }
8322
8323     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8324     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8325         SrcI->getOpcode() == Instruction::Xor &&
8326         Op1 == ConstantInt::getTrue() &&
8327         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8328       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8329       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
8330     }
8331     break;
8332   case Instruction::SDiv:
8333   case Instruction::UDiv:
8334   case Instruction::SRem:
8335   case Instruction::URem:
8336     // If we are just changing the sign, rewrite.
8337     if (DestBitSize == SrcBitSize) {
8338       // Don't insert two casts if they cannot be eliminated.  We allow 
8339       // two casts to be inserted if the sizes are the same.  This could 
8340       // only be converting signedness, which is a noop.
8341       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
8342           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8343         Value *Op0c = InsertCastBefore(Instruction::BitCast, 
8344                                        Op0, DestTy, *SrcI);
8345         Value *Op1c = InsertCastBefore(Instruction::BitCast, 
8346                                        Op1, DestTy, *SrcI);
8347         return BinaryOperator::Create(
8348           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8349       }
8350     }
8351     break;
8352
8353   case Instruction::Shl:
8354     // Allow changing the sign of the source operand.  Do not allow 
8355     // changing the size of the shift, UNLESS the shift amount is a 
8356     // constant.  We must not change variable sized shifts to a smaller 
8357     // size, because it is undefined to shift more bits out than exist 
8358     // in the value.
8359     if (DestBitSize == SrcBitSize ||
8360         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
8361       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8362           Instruction::BitCast : Instruction::Trunc);
8363       Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8364       Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8365       return BinaryOperator::CreateShl(Op0c, Op1c);
8366     }
8367     break;
8368   case Instruction::AShr:
8369     // If this is a signed shr, and if all bits shifted in are about to be
8370     // truncated off, turn it into an unsigned shr to allow greater
8371     // simplifications.
8372     if (DestBitSize < SrcBitSize &&
8373         isa<ConstantInt>(Op1)) {
8374       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
8375       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8376         // Insert the new logical shift right.
8377         return BinaryOperator::CreateLShr(Op0, Op1);
8378       }
8379     }
8380     break;
8381   }
8382   return 0;
8383 }
8384
8385 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8386   if (Instruction *Result = commonIntCastTransforms(CI))
8387     return Result;
8388   
8389   Value *Src = CI.getOperand(0);
8390   const Type *Ty = CI.getType();
8391   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8392   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8393
8394   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8395   if (DestBitWidth == 1 &&
8396       isa<VectorType>(Ty) == isa<VectorType>(Src->getType())) {
8397     Constant *One = ConstantInt::get(Src->getType(), 1);
8398     Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8399     Value *Zero = Constant::getNullValue(Src->getType());
8400     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8401   }
8402
8403   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8404   ConstantInt *ShAmtV = 0;
8405   Value *ShiftOp = 0;
8406   if (Src->hasOneUse() &&
8407       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8408     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8409     
8410     // Get a mask for the bits shifting in.
8411     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8412     if (MaskedValueIsZero(ShiftOp, Mask)) {
8413       if (ShAmt >= DestBitWidth)        // All zeros.
8414         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8415       
8416       // Okay, we can shrink this.  Truncate the input, then return a new
8417       // shift.
8418       Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8419       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8420       return BinaryOperator::CreateLShr(V1, V2);
8421     }
8422   }
8423   
8424   return 0;
8425 }
8426
8427 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8428 /// in order to eliminate the icmp.
8429 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8430                                              bool DoXform) {
8431   // If we are just checking for a icmp eq of a single bit and zext'ing it
8432   // to an integer, then shift the bit to the appropriate place and then
8433   // cast to integer to avoid the comparison.
8434   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8435     const APInt &Op1CV = Op1C->getValue();
8436       
8437     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8438     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8439     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8440         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8441       if (!DoXform) return ICI;
8442
8443       Value *In = ICI->getOperand(0);
8444       Value *Sh = ConstantInt::get(In->getType(),
8445                                    In->getType()->getScalarSizeInBits()-1);
8446       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8447                                                         In->getName()+".lobit"),
8448                                CI);
8449       if (In->getType() != CI.getType())
8450         In = CastInst::CreateIntegerCast(In, CI.getType(),
8451                                          false/*ZExt*/, "tmp", &CI);
8452
8453       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8454         Constant *One = ConstantInt::get(In->getType(), 1);
8455         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8456                                                          In->getName()+".not"),
8457                                  CI);
8458       }
8459
8460       return ReplaceInstUsesWith(CI, In);
8461     }
8462       
8463       
8464       
8465     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8466     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8467     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8468     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8469     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8470     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8471     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8472     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8473     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8474         // This only works for EQ and NE
8475         ICI->isEquality()) {
8476       // If Op1C some other power of two, convert:
8477       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8478       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8479       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8480       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8481         
8482       APInt KnownZeroMask(~KnownZero);
8483       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8484         if (!DoXform) return ICI;
8485
8486         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8487         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8488           // (X&4) == 2 --> false
8489           // (X&4) != 2 --> true
8490           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8491           Res = ConstantExpr::getZExt(Res, CI.getType());
8492           return ReplaceInstUsesWith(CI, Res);
8493         }
8494           
8495         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8496         Value *In = ICI->getOperand(0);
8497         if (ShiftAmt) {
8498           // Perform a logical shr by shiftamt.
8499           // Insert the shift to put the result in the low bit.
8500           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8501                                   ConstantInt::get(In->getType(), ShiftAmt),
8502                                                    In->getName()+".lobit"), CI);
8503         }
8504           
8505         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8506           Constant *One = ConstantInt::get(In->getType(), 1);
8507           In = BinaryOperator::CreateXor(In, One, "tmp");
8508           InsertNewInstBefore(cast<Instruction>(In), CI);
8509         }
8510           
8511         if (CI.getType() == In->getType())
8512           return ReplaceInstUsesWith(CI, In);
8513         else
8514           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8515       }
8516     }
8517   }
8518
8519   return 0;
8520 }
8521
8522 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8523   // If one of the common conversion will work ..
8524   if (Instruction *Result = commonIntCastTransforms(CI))
8525     return Result;
8526
8527   Value *Src = CI.getOperand(0);
8528
8529   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8530   // types and if the sizes are just right we can convert this into a logical
8531   // 'and' which will be much cheaper than the pair of casts.
8532   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8533     // Get the sizes of the types involved.  We know that the intermediate type
8534     // will be smaller than A or C, but don't know the relation between A and C.
8535     Value *A = CSrc->getOperand(0);
8536     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8537     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8538     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8539     // If we're actually extending zero bits, then if
8540     // SrcSize <  DstSize: zext(a & mask)
8541     // SrcSize == DstSize: a & mask
8542     // SrcSize  > DstSize: trunc(a) & mask
8543     if (SrcSize < DstSize) {
8544       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8545       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8546       Instruction *And =
8547         BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8548       InsertNewInstBefore(And, CI);
8549       return new ZExtInst(And, CI.getType());
8550     } else if (SrcSize == DstSize) {
8551       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8552       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8553                                                            AndValue));
8554     } else if (SrcSize > DstSize) {
8555       Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8556       InsertNewInstBefore(Trunc, CI);
8557       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8558       return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(Trunc->getType(),
8559                                                                AndValue));
8560     }
8561   }
8562
8563   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8564     return transformZExtICmp(ICI, CI);
8565
8566   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8567   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8568     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8569     // of the (zext icmp) will be transformed.
8570     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8571     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8572     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8573         (transformZExtICmp(LHS, CI, false) ||
8574          transformZExtICmp(RHS, CI, false))) {
8575       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8576       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8577       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8578     }
8579   }
8580
8581   // zext(trunc(t) & C) -> (t & zext(C)).
8582   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8583     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8584       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8585         Value *TI0 = TI->getOperand(0);
8586         if (TI0->getType() == CI.getType())
8587           return
8588             BinaryOperator::CreateAnd(TI0,
8589                                       ConstantExpr::getZExt(C, CI.getType()));
8590       }
8591
8592   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8593   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8594     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8595       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8596         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8597             And->getOperand(1) == C)
8598           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8599             Value *TI0 = TI->getOperand(0);
8600             if (TI0->getType() == CI.getType()) {
8601               Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8602               Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8603               InsertNewInstBefore(NewAnd, *And);
8604               return BinaryOperator::CreateXor(NewAnd, ZC);
8605             }
8606           }
8607
8608   return 0;
8609 }
8610
8611 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8612   if (Instruction *I = commonIntCastTransforms(CI))
8613     return I;
8614   
8615   Value *Src = CI.getOperand(0);
8616   
8617   // Canonicalize sign-extend from i1 to a select.
8618   if (Src->getType() == Type::Int1Ty)
8619     return SelectInst::Create(Src,
8620                               ConstantInt::getAllOnesValue(CI.getType()),
8621                               Constant::getNullValue(CI.getType()));
8622
8623   // See if the value being truncated is already sign extended.  If so, just
8624   // eliminate the trunc/sext pair.
8625   if (getOpcode(Src) == Instruction::Trunc) {
8626     Value *Op = cast<User>(Src)->getOperand(0);
8627     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8628     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8629     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8630     unsigned NumSignBits = ComputeNumSignBits(Op);
8631
8632     if (OpBits == DestBits) {
8633       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8634       // bits, it is already ready.
8635       if (NumSignBits > DestBits-MidBits)
8636         return ReplaceInstUsesWith(CI, Op);
8637     } else if (OpBits < DestBits) {
8638       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8639       // bits, just sext from i32.
8640       if (NumSignBits > OpBits-MidBits)
8641         return new SExtInst(Op, CI.getType(), "tmp");
8642     } else {
8643       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8644       // bits, just truncate to i32.
8645       if (NumSignBits > OpBits-MidBits)
8646         return new TruncInst(Op, CI.getType(), "tmp");
8647     }
8648   }
8649
8650   // If the input is a shl/ashr pair of a same constant, then this is a sign
8651   // extension from a smaller value.  If we could trust arbitrary bitwidth
8652   // integers, we could turn this into a truncate to the smaller bit and then
8653   // use a sext for the whole extension.  Since we don't, look deeper and check
8654   // for a truncate.  If the source and dest are the same type, eliminate the
8655   // trunc and extend and just do shifts.  For example, turn:
8656   //   %a = trunc i32 %i to i8
8657   //   %b = shl i8 %a, 6
8658   //   %c = ashr i8 %b, 6
8659   //   %d = sext i8 %c to i32
8660   // into:
8661   //   %a = shl i32 %i, 30
8662   //   %d = ashr i32 %a, 30
8663   Value *A = 0;
8664   ConstantInt *BA = 0, *CA = 0;
8665   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8666                         m_ConstantInt(CA))) &&
8667       BA == CA && isa<TruncInst>(A)) {
8668     Value *I = cast<TruncInst>(A)->getOperand(0);
8669     if (I->getType() == CI.getType()) {
8670       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8671       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8672       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8673       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8674       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8675                                                         CI.getName()), CI);
8676       return BinaryOperator::CreateAShr(I, ShAmtV);
8677     }
8678   }
8679   
8680   return 0;
8681 }
8682
8683 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8684 /// in the specified FP type without changing its value.
8685 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
8686   bool losesInfo;
8687   APFloat F = CFP->getValueAPF();
8688   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8689   if (!losesInfo)
8690     return ConstantFP::get(F);
8691   return 0;
8692 }
8693
8694 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8695 /// through it until we get the source value.
8696 static Value *LookThroughFPExtensions(Value *V) {
8697   if (Instruction *I = dyn_cast<Instruction>(V))
8698     if (I->getOpcode() == Instruction::FPExt)
8699       return LookThroughFPExtensions(I->getOperand(0));
8700   
8701   // If this value is a constant, return the constant in the smallest FP type
8702   // that can accurately represent it.  This allows us to turn
8703   // (float)((double)X+2.0) into x+2.0f.
8704   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8705     if (CFP->getType() == Type::PPC_FP128Ty)
8706       return V;  // No constant folding of this.
8707     // See if the value can be truncated to float and then reextended.
8708     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
8709       return V;
8710     if (CFP->getType() == Type::DoubleTy)
8711       return V;  // Won't shrink.
8712     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
8713       return V;
8714     // Don't try to shrink to various long double types.
8715   }
8716   
8717   return V;
8718 }
8719
8720 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8721   if (Instruction *I = commonCastTransforms(CI))
8722     return I;
8723   
8724   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8725   // smaller than the destination type, we can eliminate the truncate by doing
8726   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8727   // many builtins (sqrt, etc).
8728   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8729   if (OpI && OpI->hasOneUse()) {
8730     switch (OpI->getOpcode()) {
8731     default: break;
8732     case Instruction::FAdd:
8733     case Instruction::FSub:
8734     case Instruction::FMul:
8735     case Instruction::FDiv:
8736     case Instruction::FRem:
8737       const Type *SrcTy = OpI->getType();
8738       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8739       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8740       if (LHSTrunc->getType() != SrcTy && 
8741           RHSTrunc->getType() != SrcTy) {
8742         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8743         // If the source types were both smaller than the destination type of
8744         // the cast, do this xform.
8745         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8746             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8747           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8748                                       CI.getType(), CI);
8749           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8750                                       CI.getType(), CI);
8751           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8752         }
8753       }
8754       break;  
8755     }
8756   }
8757   return 0;
8758 }
8759
8760 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8761   return commonCastTransforms(CI);
8762 }
8763
8764 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8765   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8766   if (OpI == 0)
8767     return commonCastTransforms(FI);
8768
8769   // fptoui(uitofp(X)) --> X
8770   // fptoui(sitofp(X)) --> X
8771   // This is safe if the intermediate type has enough bits in its mantissa to
8772   // accurately represent all values of X.  For example, do not do this with
8773   // i64->float->i64.  This is also safe for sitofp case, because any negative
8774   // 'X' value would cause an undefined result for the fptoui. 
8775   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8776       OpI->getOperand(0)->getType() == FI.getType() &&
8777       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8778                     OpI->getType()->getFPMantissaWidth())
8779     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8780
8781   return commonCastTransforms(FI);
8782 }
8783
8784 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8785   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8786   if (OpI == 0)
8787     return commonCastTransforms(FI);
8788   
8789   // fptosi(sitofp(X)) --> X
8790   // fptosi(uitofp(X)) --> X
8791   // This is safe if the intermediate type has enough bits in its mantissa to
8792   // accurately represent all values of X.  For example, do not do this with
8793   // i64->float->i64.  This is also safe for sitofp case, because any negative
8794   // 'X' value would cause an undefined result for the fptoui. 
8795   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8796       OpI->getOperand(0)->getType() == FI.getType() &&
8797       (int)FI.getType()->getScalarSizeInBits() <=
8798                     OpI->getType()->getFPMantissaWidth())
8799     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8800   
8801   return commonCastTransforms(FI);
8802 }
8803
8804 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8805   return commonCastTransforms(CI);
8806 }
8807
8808 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8809   return commonCastTransforms(CI);
8810 }
8811
8812 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8813   // If the destination integer type is smaller than the intptr_t type for
8814   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8815   // trunc to be exposed to other transforms.  Don't do this for extending
8816   // ptrtoint's, because we don't know if the target sign or zero extends its
8817   // pointers.
8818   if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8819     Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8820                                                     TD->getIntPtrType(),
8821                                                     "tmp"), CI);
8822     return new TruncInst(P, CI.getType());
8823   }
8824   
8825   return commonPointerCastTransforms(CI);
8826 }
8827
8828 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8829   // If the source integer type is larger than the intptr_t type for
8830   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8831   // allows the trunc to be exposed to other transforms.  Don't do this for
8832   // extending inttoptr's, because we don't know if the target sign or zero
8833   // extends to pointers.
8834   if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
8835       TD->getPointerSizeInBits()) {
8836     Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8837                                                  TD->getIntPtrType(),
8838                                                  "tmp"), CI);
8839     return new IntToPtrInst(P, CI.getType());
8840   }
8841   
8842   if (Instruction *I = commonCastTransforms(CI))
8843     return I;
8844   
8845   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8846   if (!DestPointee->isSized()) return 0;
8847
8848   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8849   ConstantInt *Cst;
8850   Value *X;
8851   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8852                                     m_ConstantInt(Cst)))) {
8853     // If the source and destination operands have the same type, see if this
8854     // is a single-index GEP.
8855     if (X->getType() == CI.getType()) {
8856       // Get the size of the pointee type.
8857       uint64_t Size = TD->getTypeAllocSize(DestPointee);
8858
8859       // Convert the constant to intptr type.
8860       APInt Offset = Cst->getValue();
8861       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8862
8863       // If Offset is evenly divisible by Size, we can do this xform.
8864       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8865         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8866         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
8867       }
8868     }
8869     // TODO: Could handle other cases, e.g. where add is indexing into field of
8870     // struct etc.
8871   } else if (CI.getOperand(0)->hasOneUse() &&
8872              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8873     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8874     // "inttoptr+GEP" instead of "add+intptr".
8875     
8876     // Get the size of the pointee type.
8877     uint64_t Size = TD->getTypeAllocSize(DestPointee);
8878     
8879     // Convert the constant to intptr type.
8880     APInt Offset = Cst->getValue();
8881     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8882     
8883     // If Offset is evenly divisible by Size, we can do this xform.
8884     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8885       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8886       
8887       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8888                                                             "tmp"), CI);
8889       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
8890     }
8891   }
8892   return 0;
8893 }
8894
8895 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8896   // If the operands are integer typed then apply the integer transforms,
8897   // otherwise just apply the common ones.
8898   Value *Src = CI.getOperand(0);
8899   const Type *SrcTy = Src->getType();
8900   const Type *DestTy = CI.getType();
8901
8902   if (SrcTy->isInteger() && DestTy->isInteger()) {
8903     if (Instruction *Result = commonIntCastTransforms(CI))
8904       return Result;
8905   } else if (isa<PointerType>(SrcTy)) {
8906     if (Instruction *I = commonPointerCastTransforms(CI))
8907       return I;
8908   } else {
8909     if (Instruction *Result = commonCastTransforms(CI))
8910       return Result;
8911   }
8912
8913
8914   // Get rid of casts from one type to the same type. These are useless and can
8915   // be replaced by the operand.
8916   if (DestTy == Src->getType())
8917     return ReplaceInstUsesWith(CI, Src);
8918
8919   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8920     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8921     const Type *DstElTy = DstPTy->getElementType();
8922     const Type *SrcElTy = SrcPTy->getElementType();
8923     
8924     // If the address spaces don't match, don't eliminate the bitcast, which is
8925     // required for changing types.
8926     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8927       return 0;
8928     
8929     // If we are casting a malloc or alloca to a pointer to a type of the same
8930     // size, rewrite the allocation instruction to allocate the "right" type.
8931     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8932       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8933         return V;
8934     
8935     // If the source and destination are pointers, and this cast is equivalent
8936     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8937     // This can enhance SROA and other transforms that want type-safe pointers.
8938     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8939     unsigned NumZeros = 0;
8940     while (SrcElTy != DstElTy && 
8941            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8942            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8943       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8944       ++NumZeros;
8945     }
8946
8947     // If we found a path from the src to dest, create the getelementptr now.
8948     if (SrcElTy == DstElTy) {
8949       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8950       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
8951                                        ((Instruction*) NULL));
8952     }
8953   }
8954
8955   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8956     if (SVI->hasOneUse()) {
8957       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8958       // a bitconvert to a vector with the same # elts.
8959       if (isa<VectorType>(DestTy) && 
8960           cast<VectorType>(DestTy)->getNumElements() ==
8961                 SVI->getType()->getNumElements() &&
8962           SVI->getType()->getNumElements() ==
8963             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8964         CastInst *Tmp;
8965         // If either of the operands is a cast from CI.getType(), then
8966         // evaluating the shuffle in the casted destination's type will allow
8967         // us to eliminate at least one cast.
8968         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8969              Tmp->getOperand(0)->getType() == DestTy) ||
8970             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8971              Tmp->getOperand(0)->getType() == DestTy)) {
8972           Value *LHS = InsertCastBefore(Instruction::BitCast,
8973                                         SVI->getOperand(0), DestTy, CI);
8974           Value *RHS = InsertCastBefore(Instruction::BitCast,
8975                                         SVI->getOperand(1), DestTy, CI);
8976           // Return a new shuffle vector.  Use the same element ID's, as we
8977           // know the vector types match #elts.
8978           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8979         }
8980       }
8981     }
8982   }
8983   return 0;
8984 }
8985
8986 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8987 ///   %C = or %A, %B
8988 ///   %D = select %cond, %C, %A
8989 /// into:
8990 ///   %C = select %cond, %B, 0
8991 ///   %D = or %A, %C
8992 ///
8993 /// Assuming that the specified instruction is an operand to the select, return
8994 /// a bitmask indicating which operands of this instruction are foldable if they
8995 /// equal the other incoming value of the select.
8996 ///
8997 static unsigned GetSelectFoldableOperands(Instruction *I) {
8998   switch (I->getOpcode()) {
8999   case Instruction::Add:
9000   case Instruction::Mul:
9001   case Instruction::And:
9002   case Instruction::Or:
9003   case Instruction::Xor:
9004     return 3;              // Can fold through either operand.
9005   case Instruction::Sub:   // Can only fold on the amount subtracted.
9006   case Instruction::Shl:   // Can only fold on the shift amount.
9007   case Instruction::LShr:
9008   case Instruction::AShr:
9009     return 1;
9010   default:
9011     return 0;              // Cannot fold
9012   }
9013 }
9014
9015 /// GetSelectFoldableConstant - For the same transformation as the previous
9016 /// function, return the identity constant that goes into the select.
9017 static Constant *GetSelectFoldableConstant(Instruction *I) {
9018   switch (I->getOpcode()) {
9019   default: assert(0 && "This cannot happen!"); abort();
9020   case Instruction::Add:
9021   case Instruction::Sub:
9022   case Instruction::Or:
9023   case Instruction::Xor:
9024   case Instruction::Shl:
9025   case Instruction::LShr:
9026   case Instruction::AShr:
9027     return Constant::getNullValue(I->getType());
9028   case Instruction::And:
9029     return Constant::getAllOnesValue(I->getType());
9030   case Instruction::Mul:
9031     return ConstantInt::get(I->getType(), 1);
9032   }
9033 }
9034
9035 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9036 /// have the same opcode and only one use each.  Try to simplify this.
9037 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9038                                           Instruction *FI) {
9039   if (TI->getNumOperands() == 1) {
9040     // If this is a non-volatile load or a cast from the same type,
9041     // merge.
9042     if (TI->isCast()) {
9043       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9044         return 0;
9045     } else {
9046       return 0;  // unknown unary op.
9047     }
9048
9049     // Fold this by inserting a select from the input values.
9050     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9051                                            FI->getOperand(0), SI.getName()+".v");
9052     InsertNewInstBefore(NewSI, SI);
9053     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9054                             TI->getType());
9055   }
9056
9057   // Only handle binary operators here.
9058   if (!isa<BinaryOperator>(TI))
9059     return 0;
9060
9061   // Figure out if the operations have any operands in common.
9062   Value *MatchOp, *OtherOpT, *OtherOpF;
9063   bool MatchIsOpZero;
9064   if (TI->getOperand(0) == FI->getOperand(0)) {
9065     MatchOp  = TI->getOperand(0);
9066     OtherOpT = TI->getOperand(1);
9067     OtherOpF = FI->getOperand(1);
9068     MatchIsOpZero = true;
9069   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9070     MatchOp  = TI->getOperand(1);
9071     OtherOpT = TI->getOperand(0);
9072     OtherOpF = FI->getOperand(0);
9073     MatchIsOpZero = false;
9074   } else if (!TI->isCommutative()) {
9075     return 0;
9076   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9077     MatchOp  = TI->getOperand(0);
9078     OtherOpT = TI->getOperand(1);
9079     OtherOpF = FI->getOperand(0);
9080     MatchIsOpZero = true;
9081   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9082     MatchOp  = TI->getOperand(1);
9083     OtherOpT = TI->getOperand(0);
9084     OtherOpF = FI->getOperand(1);
9085     MatchIsOpZero = true;
9086   } else {
9087     return 0;
9088   }
9089
9090   // If we reach here, they do have operations in common.
9091   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9092                                          OtherOpF, SI.getName()+".v");
9093   InsertNewInstBefore(NewSI, SI);
9094
9095   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9096     if (MatchIsOpZero)
9097       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9098     else
9099       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9100   }
9101   assert(0 && "Shouldn't get here");
9102   return 0;
9103 }
9104
9105 static bool isSelect01(Constant *C1, Constant *C2) {
9106   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9107   if (!C1I)
9108     return false;
9109   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9110   if (!C2I)
9111     return false;
9112   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9113 }
9114
9115 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9116 /// facilitate further optimization.
9117 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9118                                             Value *FalseVal) {
9119   // See the comment above GetSelectFoldableOperands for a description of the
9120   // transformation we are doing here.
9121   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9122     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9123         !isa<Constant>(FalseVal)) {
9124       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9125         unsigned OpToFold = 0;
9126         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9127           OpToFold = 1;
9128         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9129           OpToFold = 2;
9130         }
9131
9132         if (OpToFold) {
9133           Constant *C = GetSelectFoldableConstant(TVI);
9134           Value *OOp = TVI->getOperand(2-OpToFold);
9135           // Avoid creating select between 2 constants unless it's selecting
9136           // between 0 and 1.
9137           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9138             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9139             InsertNewInstBefore(NewSel, SI);
9140             NewSel->takeName(TVI);
9141             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9142               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9143             assert(0 && "Unknown instruction!!");
9144           }
9145         }
9146       }
9147     }
9148   }
9149
9150   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9151     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9152         !isa<Constant>(TrueVal)) {
9153       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9154         unsigned OpToFold = 0;
9155         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9156           OpToFold = 1;
9157         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9158           OpToFold = 2;
9159         }
9160
9161         if (OpToFold) {
9162           Constant *C = GetSelectFoldableConstant(FVI);
9163           Value *OOp = FVI->getOperand(2-OpToFold);
9164           // Avoid creating select between 2 constants unless it's selecting
9165           // between 0 and 1.
9166           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9167             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9168             InsertNewInstBefore(NewSel, SI);
9169             NewSel->takeName(FVI);
9170             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9171               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9172             assert(0 && "Unknown instruction!!");
9173           }
9174         }
9175       }
9176     }
9177   }
9178
9179   return 0;
9180 }
9181
9182 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9183 /// ICmpInst as its first operand.
9184 ///
9185 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9186                                                    ICmpInst *ICI) {
9187   bool Changed = false;
9188   ICmpInst::Predicate Pred = ICI->getPredicate();
9189   Value *CmpLHS = ICI->getOperand(0);
9190   Value *CmpRHS = ICI->getOperand(1);
9191   Value *TrueVal = SI.getTrueValue();
9192   Value *FalseVal = SI.getFalseValue();
9193
9194   // Check cases where the comparison is with a constant that
9195   // can be adjusted to fit the min/max idiom. We may edit ICI in
9196   // place here, so make sure the select is the only user.
9197   if (ICI->hasOneUse())
9198     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9199       switch (Pred) {
9200       default: break;
9201       case ICmpInst::ICMP_ULT:
9202       case ICmpInst::ICMP_SLT: {
9203         // X < MIN ? T : F  -->  F
9204         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9205           return ReplaceInstUsesWith(SI, FalseVal);
9206         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9207         Constant *AdjustedRHS = SubOne(CI);
9208         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9209             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9210           Pred = ICmpInst::getSwappedPredicate(Pred);
9211           CmpRHS = AdjustedRHS;
9212           std::swap(FalseVal, TrueVal);
9213           ICI->setPredicate(Pred);
9214           ICI->setOperand(1, CmpRHS);
9215           SI.setOperand(1, TrueVal);
9216           SI.setOperand(2, FalseVal);
9217           Changed = true;
9218         }
9219         break;
9220       }
9221       case ICmpInst::ICMP_UGT:
9222       case ICmpInst::ICMP_SGT: {
9223         // X > MAX ? T : F  -->  F
9224         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9225           return ReplaceInstUsesWith(SI, FalseVal);
9226         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9227         Constant *AdjustedRHS = AddOne(CI);
9228         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9229             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9230           Pred = ICmpInst::getSwappedPredicate(Pred);
9231           CmpRHS = AdjustedRHS;
9232           std::swap(FalseVal, TrueVal);
9233           ICI->setPredicate(Pred);
9234           ICI->setOperand(1, CmpRHS);
9235           SI.setOperand(1, TrueVal);
9236           SI.setOperand(2, FalseVal);
9237           Changed = true;
9238         }
9239         break;
9240       }
9241       }
9242
9243       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9244       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9245       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9246       if (match(TrueVal, m_ConstantInt<-1>()) &&
9247           match(FalseVal, m_ConstantInt<0>()))
9248         Pred = ICI->getPredicate();
9249       else if (match(TrueVal, m_ConstantInt<0>()) &&
9250                match(FalseVal, m_ConstantInt<-1>()))
9251         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9252       
9253       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9254         // If we are just checking for a icmp eq of a single bit and zext'ing it
9255         // to an integer, then shift the bit to the appropriate place and then
9256         // cast to integer to avoid the comparison.
9257         const APInt &Op1CV = CI->getValue();
9258     
9259         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9260         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9261         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9262             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9263           Value *In = ICI->getOperand(0);
9264           Value *Sh = ConstantInt::get(In->getType(),
9265                                        In->getType()->getScalarSizeInBits()-1);
9266           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9267                                                           In->getName()+".lobit"),
9268                                    *ICI);
9269           if (In->getType() != SI.getType())
9270             In = CastInst::CreateIntegerCast(In, SI.getType(),
9271                                              true/*SExt*/, "tmp", ICI);
9272     
9273           if (Pred == ICmpInst::ICMP_SGT)
9274             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9275                                        In->getName()+".not"), *ICI);
9276     
9277           return ReplaceInstUsesWith(SI, In);
9278         }
9279       }
9280     }
9281
9282   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9283     // Transform (X == Y) ? X : Y  -> Y
9284     if (Pred == ICmpInst::ICMP_EQ)
9285       return ReplaceInstUsesWith(SI, FalseVal);
9286     // Transform (X != Y) ? X : Y  -> X
9287     if (Pred == ICmpInst::ICMP_NE)
9288       return ReplaceInstUsesWith(SI, TrueVal);
9289     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9290
9291   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9292     // Transform (X == Y) ? Y : X  -> X
9293     if (Pred == ICmpInst::ICMP_EQ)
9294       return ReplaceInstUsesWith(SI, FalseVal);
9295     // Transform (X != Y) ? Y : X  -> Y
9296     if (Pred == ICmpInst::ICMP_NE)
9297       return ReplaceInstUsesWith(SI, TrueVal);
9298     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9299   }
9300
9301   /// NOTE: if we wanted to, this is where to detect integer ABS
9302
9303   return Changed ? &SI : 0;
9304 }
9305
9306 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9307   Value *CondVal = SI.getCondition();
9308   Value *TrueVal = SI.getTrueValue();
9309   Value *FalseVal = SI.getFalseValue();
9310
9311   // select true, X, Y  -> X
9312   // select false, X, Y -> Y
9313   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9314     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9315
9316   // select C, X, X -> X
9317   if (TrueVal == FalseVal)
9318     return ReplaceInstUsesWith(SI, TrueVal);
9319
9320   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9321     return ReplaceInstUsesWith(SI, FalseVal);
9322   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9323     return ReplaceInstUsesWith(SI, TrueVal);
9324   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9325     if (isa<Constant>(TrueVal))
9326       return ReplaceInstUsesWith(SI, TrueVal);
9327     else
9328       return ReplaceInstUsesWith(SI, FalseVal);
9329   }
9330
9331   if (SI.getType() == Type::Int1Ty) {
9332     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9333       if (C->getZExtValue()) {
9334         // Change: A = select B, true, C --> A = or B, C
9335         return BinaryOperator::CreateOr(CondVal, FalseVal);
9336       } else {
9337         // Change: A = select B, false, C --> A = and !B, C
9338         Value *NotCond =
9339           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9340                                              "not."+CondVal->getName()), SI);
9341         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9342       }
9343     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9344       if (C->getZExtValue() == false) {
9345         // Change: A = select B, C, false --> A = and B, C
9346         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9347       } else {
9348         // Change: A = select B, C, true --> A = or !B, C
9349         Value *NotCond =
9350           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9351                                              "not."+CondVal->getName()), SI);
9352         return BinaryOperator::CreateOr(NotCond, TrueVal);
9353       }
9354     }
9355     
9356     // select a, b, a  -> a&b
9357     // select a, a, b  -> a|b
9358     if (CondVal == TrueVal)
9359       return BinaryOperator::CreateOr(CondVal, FalseVal);
9360     else if (CondVal == FalseVal)
9361       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9362   }
9363
9364   // Selecting between two integer constants?
9365   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9366     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9367       // select C, 1, 0 -> zext C to int
9368       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9369         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9370       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9371         // select C, 0, 1 -> zext !C to int
9372         Value *NotCond =
9373           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9374                                                "not."+CondVal->getName()), SI);
9375         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9376       }
9377
9378       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9379
9380         // (x <s 0) ? -1 : 0 -> ashr x, 31
9381         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
9382           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
9383             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
9384               // The comparison constant and the result are not neccessarily the
9385               // same width. Make an all-ones value by inserting a AShr.
9386               Value *X = IC->getOperand(0);
9387               uint32_t Bits = X->getType()->getScalarSizeInBits();
9388               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
9389               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
9390                                                         ShAmt, "ones");
9391               InsertNewInstBefore(SRA, SI);
9392
9393               // Then cast to the appropriate width.
9394               return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
9395             }
9396           }
9397
9398
9399         // If one of the constants is zero (we know they can't both be) and we
9400         // have an icmp instruction with zero, and we have an 'and' with the
9401         // non-constant value, eliminate this whole mess.  This corresponds to
9402         // cases like this: ((X & 27) ? 27 : 0)
9403         if (TrueValC->isZero() || FalseValC->isZero())
9404           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9405               cast<Constant>(IC->getOperand(1))->isNullValue())
9406             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9407               if (ICA->getOpcode() == Instruction::And &&
9408                   isa<ConstantInt>(ICA->getOperand(1)) &&
9409                   (ICA->getOperand(1) == TrueValC ||
9410                    ICA->getOperand(1) == FalseValC) &&
9411                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9412                 // Okay, now we know that everything is set up, we just don't
9413                 // know whether we have a icmp_ne or icmp_eq and whether the 
9414                 // true or false val is the zero.
9415                 bool ShouldNotVal = !TrueValC->isZero();
9416                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9417                 Value *V = ICA;
9418                 if (ShouldNotVal)
9419                   V = InsertNewInstBefore(BinaryOperator::Create(
9420                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9421                 return ReplaceInstUsesWith(SI, V);
9422               }
9423       }
9424     }
9425
9426   // See if we are selecting two values based on a comparison of the two values.
9427   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9428     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9429       // Transform (X == Y) ? X : Y  -> Y
9430       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9431         // This is not safe in general for floating point:  
9432         // consider X== -0, Y== +0.
9433         // It becomes safe if either operand is a nonzero constant.
9434         ConstantFP *CFPt, *CFPf;
9435         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9436               !CFPt->getValueAPF().isZero()) ||
9437             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9438              !CFPf->getValueAPF().isZero()))
9439         return ReplaceInstUsesWith(SI, FalseVal);
9440       }
9441       // Transform (X != Y) ? X : Y  -> X
9442       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9443         return ReplaceInstUsesWith(SI, TrueVal);
9444       // NOTE: if we wanted to, this is where to detect MIN/MAX
9445
9446     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9447       // Transform (X == Y) ? Y : X  -> X
9448       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9449         // This is not safe in general for floating point:  
9450         // consider X== -0, Y== +0.
9451         // It becomes safe if either operand is a nonzero constant.
9452         ConstantFP *CFPt, *CFPf;
9453         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9454               !CFPt->getValueAPF().isZero()) ||
9455             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9456              !CFPf->getValueAPF().isZero()))
9457           return ReplaceInstUsesWith(SI, FalseVal);
9458       }
9459       // Transform (X != Y) ? Y : X  -> Y
9460       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9461         return ReplaceInstUsesWith(SI, TrueVal);
9462       // NOTE: if we wanted to, this is where to detect MIN/MAX
9463     }
9464     // NOTE: if we wanted to, this is where to detect ABS
9465   }
9466
9467   // See if we are selecting two values based on a comparison of the two values.
9468   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9469     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9470       return Result;
9471
9472   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9473     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9474       if (TI->hasOneUse() && FI->hasOneUse()) {
9475         Instruction *AddOp = 0, *SubOp = 0;
9476
9477         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9478         if (TI->getOpcode() == FI->getOpcode())
9479           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9480             return IV;
9481
9482         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9483         // even legal for FP.
9484         if ((TI->getOpcode() == Instruction::Sub &&
9485              FI->getOpcode() == Instruction::Add) ||
9486             (TI->getOpcode() == Instruction::FSub &&
9487              FI->getOpcode() == Instruction::FAdd)) {
9488           AddOp = FI; SubOp = TI;
9489         } else if ((FI->getOpcode() == Instruction::Sub &&
9490                     TI->getOpcode() == Instruction::Add) ||
9491                    (FI->getOpcode() == Instruction::FSub &&
9492                     TI->getOpcode() == Instruction::FAdd)) {
9493           AddOp = TI; SubOp = FI;
9494         }
9495
9496         if (AddOp) {
9497           Value *OtherAddOp = 0;
9498           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9499             OtherAddOp = AddOp->getOperand(1);
9500           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9501             OtherAddOp = AddOp->getOperand(0);
9502           }
9503
9504           if (OtherAddOp) {
9505             // So at this point we know we have (Y -> OtherAddOp):
9506             //        select C, (add X, Y), (sub X, Z)
9507             Value *NegVal;  // Compute -Z
9508             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9509               NegVal = ConstantExpr::getNeg(C);
9510             } else {
9511               NegVal = InsertNewInstBefore(
9512                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
9513             }
9514
9515             Value *NewTrueOp = OtherAddOp;
9516             Value *NewFalseOp = NegVal;
9517             if (AddOp != TI)
9518               std::swap(NewTrueOp, NewFalseOp);
9519             Instruction *NewSel =
9520               SelectInst::Create(CondVal, NewTrueOp,
9521                                  NewFalseOp, SI.getName() + ".p");
9522
9523             NewSel = InsertNewInstBefore(NewSel, SI);
9524             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9525           }
9526         }
9527       }
9528
9529   // See if we can fold the select into one of our operands.
9530   if (SI.getType()->isInteger()) {
9531     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9532     if (FoldI)
9533       return FoldI;
9534   }
9535
9536   if (BinaryOperator::isNot(CondVal)) {
9537     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9538     SI.setOperand(1, FalseVal);
9539     SI.setOperand(2, TrueVal);
9540     return &SI;
9541   }
9542
9543   return 0;
9544 }
9545
9546 /// EnforceKnownAlignment - If the specified pointer points to an object that
9547 /// we control, modify the object's alignment to PrefAlign. This isn't
9548 /// often possible though. If alignment is important, a more reliable approach
9549 /// is to simply align all global variables and allocation instructions to
9550 /// their preferred alignment from the beginning.
9551 ///
9552 static unsigned EnforceKnownAlignment(Value *V,
9553                                       unsigned Align, unsigned PrefAlign) {
9554
9555   User *U = dyn_cast<User>(V);
9556   if (!U) return Align;
9557
9558   switch (getOpcode(U)) {
9559   default: break;
9560   case Instruction::BitCast:
9561     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9562   case Instruction::GetElementPtr: {
9563     // If all indexes are zero, it is just the alignment of the base pointer.
9564     bool AllZeroOperands = true;
9565     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9566       if (!isa<Constant>(*i) ||
9567           !cast<Constant>(*i)->isNullValue()) {
9568         AllZeroOperands = false;
9569         break;
9570       }
9571
9572     if (AllZeroOperands) {
9573       // Treat this like a bitcast.
9574       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9575     }
9576     break;
9577   }
9578   }
9579
9580   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9581     // If there is a large requested alignment and we can, bump up the alignment
9582     // of the global.
9583     if (!GV->isDeclaration()) {
9584       if (GV->getAlignment() >= PrefAlign)
9585         Align = GV->getAlignment();
9586       else {
9587         GV->setAlignment(PrefAlign);
9588         Align = PrefAlign;
9589       }
9590     }
9591   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9592     // If there is a requested alignment and if this is an alloca, round up.  We
9593     // don't do this for malloc, because some systems can't respect the request.
9594     if (isa<AllocaInst>(AI)) {
9595       if (AI->getAlignment() >= PrefAlign)
9596         Align = AI->getAlignment();
9597       else {
9598         AI->setAlignment(PrefAlign);
9599         Align = PrefAlign;
9600       }
9601     }
9602   }
9603
9604   return Align;
9605 }
9606
9607 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9608 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9609 /// and it is more than the alignment of the ultimate object, see if we can
9610 /// increase the alignment of the ultimate object, making this check succeed.
9611 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9612                                                   unsigned PrefAlign) {
9613   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9614                       sizeof(PrefAlign) * CHAR_BIT;
9615   APInt Mask = APInt::getAllOnesValue(BitWidth);
9616   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9617   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9618   unsigned TrailZ = KnownZero.countTrailingOnes();
9619   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9620
9621   if (PrefAlign > Align)
9622     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9623   
9624     // We don't need to make any adjustment.
9625   return Align;
9626 }
9627
9628 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9629   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9630   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9631   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9632   unsigned CopyAlign = MI->getAlignment();
9633
9634   if (CopyAlign < MinAlign) {
9635     MI->setAlignment(MinAlign);
9636     return MI;
9637   }
9638   
9639   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9640   // load/store.
9641   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9642   if (MemOpLength == 0) return 0;
9643   
9644   // Source and destination pointer types are always "i8*" for intrinsic.  See
9645   // if the size is something we can handle with a single primitive load/store.
9646   // A single load+store correctly handles overlapping memory in the memmove
9647   // case.
9648   unsigned Size = MemOpLength->getZExtValue();
9649   if (Size == 0) return MI;  // Delete this mem transfer.
9650   
9651   if (Size > 8 || (Size&(Size-1)))
9652     return 0;  // If not 1/2/4/8 bytes, exit.
9653   
9654   // Use an integer load+store unless we can find something better.
9655   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
9656   
9657   // Memcpy forces the use of i8* for the source and destination.  That means
9658   // that if you're using memcpy to move one double around, you'll get a cast
9659   // from double* to i8*.  We'd much rather use a double load+store rather than
9660   // an i64 load+store, here because this improves the odds that the source or
9661   // dest address will be promotable.  See if we can find a better type than the
9662   // integer datatype.
9663   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9664     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9665     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9666       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9667       // down through these levels if so.
9668       while (!SrcETy->isSingleValueType()) {
9669         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9670           if (STy->getNumElements() == 1)
9671             SrcETy = STy->getElementType(0);
9672           else
9673             break;
9674         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9675           if (ATy->getNumElements() == 1)
9676             SrcETy = ATy->getElementType();
9677           else
9678             break;
9679         } else
9680           break;
9681       }
9682       
9683       if (SrcETy->isSingleValueType())
9684         NewPtrTy = PointerType::getUnqual(SrcETy);
9685     }
9686   }
9687   
9688   
9689   // If the memcpy/memmove provides better alignment info than we can
9690   // infer, use it.
9691   SrcAlign = std::max(SrcAlign, CopyAlign);
9692   DstAlign = std::max(DstAlign, CopyAlign);
9693   
9694   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9695   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9696   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9697   InsertNewInstBefore(L, *MI);
9698   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9699
9700   // Set the size of the copy to 0, it will be deleted on the next iteration.
9701   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9702   return MI;
9703 }
9704
9705 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9706   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9707   if (MI->getAlignment() < Alignment) {
9708     MI->setAlignment(Alignment);
9709     return MI;
9710   }
9711   
9712   // Extract the length and alignment and fill if they are constant.
9713   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9714   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9715   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9716     return 0;
9717   uint64_t Len = LenC->getZExtValue();
9718   Alignment = MI->getAlignment();
9719   
9720   // If the length is zero, this is a no-op
9721   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9722   
9723   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9724   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9725     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
9726     
9727     Value *Dest = MI->getDest();
9728     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9729
9730     // Alignment 0 is identity for alignment 1 for memset, but not store.
9731     if (Alignment == 0) Alignment = 1;
9732     
9733     // Extract the fill value and store.
9734     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9735     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9736                                       Alignment), *MI);
9737     
9738     // Set the size of the copy to 0, it will be deleted on the next iteration.
9739     MI->setLength(Constant::getNullValue(LenC->getType()));
9740     return MI;
9741   }
9742
9743   return 0;
9744 }
9745
9746
9747 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9748 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9749 /// the heavy lifting.
9750 ///
9751 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9752   // If the caller function is nounwind, mark the call as nounwind, even if the
9753   // callee isn't.
9754   if (CI.getParent()->getParent()->doesNotThrow() &&
9755       !CI.doesNotThrow()) {
9756     CI.setDoesNotThrow();
9757     return &CI;
9758   }
9759   
9760   
9761   
9762   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9763   if (!II) return visitCallSite(&CI);
9764   
9765   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9766   // visitCallSite.
9767   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9768     bool Changed = false;
9769
9770     // memmove/cpy/set of zero bytes is a noop.
9771     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9772       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9773
9774       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9775         if (CI->getZExtValue() == 1) {
9776           // Replace the instruction with just byte operations.  We would
9777           // transform other cases to loads/stores, but we don't know if
9778           // alignment is sufficient.
9779         }
9780     }
9781
9782     // If we have a memmove and the source operation is a constant global,
9783     // then the source and dest pointers can't alias, so we can change this
9784     // into a call to memcpy.
9785     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9786       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9787         if (GVSrc->isConstant()) {
9788           Module *M = CI.getParent()->getParent()->getParent();
9789           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9790           const Type *Tys[1];
9791           Tys[0] = CI.getOperand(3)->getType();
9792           CI.setOperand(0, 
9793                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9794           Changed = true;
9795         }
9796
9797       // memmove(x,x,size) -> noop.
9798       if (MMI->getSource() == MMI->getDest())
9799         return EraseInstFromFunction(CI);
9800     }
9801
9802     // If we can determine a pointer alignment that is bigger than currently
9803     // set, update the alignment.
9804     if (isa<MemTransferInst>(MI)) {
9805       if (Instruction *I = SimplifyMemTransfer(MI))
9806         return I;
9807     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9808       if (Instruction *I = SimplifyMemSet(MSI))
9809         return I;
9810     }
9811           
9812     if (Changed) return II;
9813   }
9814   
9815   switch (II->getIntrinsicID()) {
9816   default: break;
9817   case Intrinsic::bswap:
9818     // bswap(bswap(x)) -> x
9819     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9820       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9821         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9822     break;
9823   case Intrinsic::ppc_altivec_lvx:
9824   case Intrinsic::ppc_altivec_lvxl:
9825   case Intrinsic::x86_sse_loadu_ps:
9826   case Intrinsic::x86_sse2_loadu_pd:
9827   case Intrinsic::x86_sse2_loadu_dq:
9828     // Turn PPC lvx     -> load if the pointer is known aligned.
9829     // Turn X86 loadups -> load if the pointer is known aligned.
9830     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9831       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9832                                        PointerType::getUnqual(II->getType()),
9833                                        CI);
9834       return new LoadInst(Ptr);
9835     }
9836     break;
9837   case Intrinsic::ppc_altivec_stvx:
9838   case Intrinsic::ppc_altivec_stvxl:
9839     // Turn stvx -> store if the pointer is known aligned.
9840     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9841       const Type *OpPtrTy = 
9842         PointerType::getUnqual(II->getOperand(1)->getType());
9843       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9844       return new StoreInst(II->getOperand(1), Ptr);
9845     }
9846     break;
9847   case Intrinsic::x86_sse_storeu_ps:
9848   case Intrinsic::x86_sse2_storeu_pd:
9849   case Intrinsic::x86_sse2_storeu_dq:
9850     // Turn X86 storeu -> store if the pointer is known aligned.
9851     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9852       const Type *OpPtrTy = 
9853         PointerType::getUnqual(II->getOperand(2)->getType());
9854       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9855       return new StoreInst(II->getOperand(2), Ptr);
9856     }
9857     break;
9858     
9859   case Intrinsic::x86_sse_cvttss2si: {
9860     // These intrinsics only demands the 0th element of its input vector.  If
9861     // we can simplify the input based on that, do so now.
9862     unsigned VWidth =
9863       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9864     APInt DemandedElts(VWidth, 1);
9865     APInt UndefElts(VWidth, 0);
9866     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9867                                               UndefElts)) {
9868       II->setOperand(1, V);
9869       return II;
9870     }
9871     break;
9872   }
9873     
9874   case Intrinsic::ppc_altivec_vperm:
9875     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9876     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9877       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9878       
9879       // Check that all of the elements are integer constants or undefs.
9880       bool AllEltsOk = true;
9881       for (unsigned i = 0; i != 16; ++i) {
9882         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9883             !isa<UndefValue>(Mask->getOperand(i))) {
9884           AllEltsOk = false;
9885           break;
9886         }
9887       }
9888       
9889       if (AllEltsOk) {
9890         // Cast the input vectors to byte vectors.
9891         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9892         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9893         Value *Result = UndefValue::get(Op0->getType());
9894         
9895         // Only extract each element once.
9896         Value *ExtractedElts[32];
9897         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9898         
9899         for (unsigned i = 0; i != 16; ++i) {
9900           if (isa<UndefValue>(Mask->getOperand(i)))
9901             continue;
9902           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9903           Idx &= 31;  // Match the hardware behavior.
9904           
9905           if (ExtractedElts[Idx] == 0) {
9906             Instruction *Elt = 
9907               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9908             InsertNewInstBefore(Elt, CI);
9909             ExtractedElts[Idx] = Elt;
9910           }
9911         
9912           // Insert this value into the result vector.
9913           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9914                                              i, "tmp");
9915           InsertNewInstBefore(cast<Instruction>(Result), CI);
9916         }
9917         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9918       }
9919     }
9920     break;
9921
9922   case Intrinsic::stackrestore: {
9923     // If the save is right next to the restore, remove the restore.  This can
9924     // happen when variable allocas are DCE'd.
9925     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9926       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9927         BasicBlock::iterator BI = SS;
9928         if (&*++BI == II)
9929           return EraseInstFromFunction(CI);
9930       }
9931     }
9932     
9933     // Scan down this block to see if there is another stack restore in the
9934     // same block without an intervening call/alloca.
9935     BasicBlock::iterator BI = II;
9936     TerminatorInst *TI = II->getParent()->getTerminator();
9937     bool CannotRemove = false;
9938     for (++BI; &*BI != TI; ++BI) {
9939       if (isa<AllocaInst>(BI)) {
9940         CannotRemove = true;
9941         break;
9942       }
9943       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9944         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9945           // If there is a stackrestore below this one, remove this one.
9946           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9947             return EraseInstFromFunction(CI);
9948           // Otherwise, ignore the intrinsic.
9949         } else {
9950           // If we found a non-intrinsic call, we can't remove the stack
9951           // restore.
9952           CannotRemove = true;
9953           break;
9954         }
9955       }
9956     }
9957     
9958     // If the stack restore is in a return/unwind block and if there are no
9959     // allocas or calls between the restore and the return, nuke the restore.
9960     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9961       return EraseInstFromFunction(CI);
9962     break;
9963   }
9964   }
9965
9966   return visitCallSite(II);
9967 }
9968
9969 // InvokeInst simplification
9970 //
9971 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9972   return visitCallSite(&II);
9973 }
9974
9975 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9976 /// passed through the varargs area, we can eliminate the use of the cast.
9977 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9978                                          const CastInst * const CI,
9979                                          const TargetData * const TD,
9980                                          const int ix) {
9981   if (!CI->isLosslessCast())
9982     return false;
9983
9984   // The size of ByVal arguments is derived from the type, so we
9985   // can't change to a type with a different size.  If the size were
9986   // passed explicitly we could avoid this check.
9987   if (!CS.paramHasAttr(ix, Attribute::ByVal))
9988     return true;
9989
9990   const Type* SrcTy = 
9991             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9992   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9993   if (!SrcTy->isSized() || !DstTy->isSized())
9994     return false;
9995   if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
9996     return false;
9997   return true;
9998 }
9999
10000 // visitCallSite - Improvements for call and invoke instructions.
10001 //
10002 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10003   bool Changed = false;
10004
10005   // If the callee is a constexpr cast of a function, attempt to move the cast
10006   // to the arguments of the call/invoke.
10007   if (transformConstExprCastCall(CS)) return 0;
10008
10009   Value *Callee = CS.getCalledValue();
10010
10011   if (Function *CalleeF = dyn_cast<Function>(Callee))
10012     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10013       Instruction *OldCall = CS.getInstruction();
10014       // If the call and callee calling conventions don't match, this call must
10015       // be unreachable, as the call is undefined.
10016       new StoreInst(ConstantInt::getTrue(),
10017                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
10018                                     OldCall);
10019       if (!OldCall->use_empty())
10020         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
10021       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10022         return EraseInstFromFunction(*OldCall);
10023       return 0;
10024     }
10025
10026   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10027     // This instruction is not reachable, just remove it.  We insert a store to
10028     // undef so that we know that this code is not reachable, despite the fact
10029     // that we can't modify the CFG here.
10030     new StoreInst(ConstantInt::getTrue(),
10031                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
10032                   CS.getInstruction());
10033
10034     if (!CS.getInstruction()->use_empty())
10035       CS.getInstruction()->
10036         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
10037
10038     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10039       // Don't break the CFG, insert a dummy cond branch.
10040       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10041                          ConstantInt::getTrue(), II);
10042     }
10043     return EraseInstFromFunction(*CS.getInstruction());
10044   }
10045
10046   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10047     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10048       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10049         return transformCallThroughTrampoline(CS);
10050
10051   const PointerType *PTy = cast<PointerType>(Callee->getType());
10052   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10053   if (FTy->isVarArg()) {
10054     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10055     // See if we can optimize any arguments passed through the varargs area of
10056     // the call.
10057     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10058            E = CS.arg_end(); I != E; ++I, ++ix) {
10059       CastInst *CI = dyn_cast<CastInst>(*I);
10060       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10061         *I = CI->getOperand(0);
10062         Changed = true;
10063       }
10064     }
10065   }
10066
10067   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10068     // Inline asm calls cannot throw - mark them 'nounwind'.
10069     CS.setDoesNotThrow();
10070     Changed = true;
10071   }
10072
10073   return Changed ? CS.getInstruction() : 0;
10074 }
10075
10076 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10077 // attempt to move the cast to the arguments of the call/invoke.
10078 //
10079 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10080   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10081   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10082   if (CE->getOpcode() != Instruction::BitCast || 
10083       !isa<Function>(CE->getOperand(0)))
10084     return false;
10085   Function *Callee = cast<Function>(CE->getOperand(0));
10086   Instruction *Caller = CS.getInstruction();
10087   const AttrListPtr &CallerPAL = CS.getAttributes();
10088
10089   // Okay, this is a cast from a function to a different type.  Unless doing so
10090   // would cause a type conversion of one of our arguments, change this call to
10091   // be a direct call with arguments casted to the appropriate types.
10092   //
10093   const FunctionType *FT = Callee->getFunctionType();
10094   const Type *OldRetTy = Caller->getType();
10095   const Type *NewRetTy = FT->getReturnType();
10096
10097   if (isa<StructType>(NewRetTy))
10098     return false; // TODO: Handle multiple return values.
10099
10100   // Check to see if we are changing the return type...
10101   if (OldRetTy != NewRetTy) {
10102     if (Callee->isDeclaration() &&
10103         // Conversion is ok if changing from one pointer type to another or from
10104         // a pointer to an integer of the same size.
10105         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
10106           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
10107       return false;   // Cannot transform this return value.
10108
10109     if (!Caller->use_empty() &&
10110         // void -> non-void is handled specially
10111         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
10112       return false;   // Cannot transform this return value.
10113
10114     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10115       Attributes RAttrs = CallerPAL.getRetAttributes();
10116       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10117         return false;   // Attribute not compatible with transformed value.
10118     }
10119
10120     // If the callsite is an invoke instruction, and the return value is used by
10121     // a PHI node in a successor, we cannot change the return type of the call
10122     // because there is no place to put the cast instruction (without breaking
10123     // the critical edge).  Bail out in this case.
10124     if (!Caller->use_empty())
10125       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10126         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10127              UI != E; ++UI)
10128           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10129             if (PN->getParent() == II->getNormalDest() ||
10130                 PN->getParent() == II->getUnwindDest())
10131               return false;
10132   }
10133
10134   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10135   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10136
10137   CallSite::arg_iterator AI = CS.arg_begin();
10138   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10139     const Type *ParamTy = FT->getParamType(i);
10140     const Type *ActTy = (*AI)->getType();
10141
10142     if (!CastInst::isCastable(ActTy, ParamTy))
10143       return false;   // Cannot transform this parameter value.
10144
10145     if (CallerPAL.getParamAttributes(i + 1) 
10146         & Attribute::typeIncompatible(ParamTy))
10147       return false;   // Attribute not compatible with transformed value.
10148
10149     // Converting from one pointer type to another or between a pointer and an
10150     // integer of the same size is safe even if we do not have a body.
10151     bool isConvertible = ActTy == ParamTy ||
10152       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10153        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
10154     if (Callee->isDeclaration() && !isConvertible) return false;
10155   }
10156
10157   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10158       Callee->isDeclaration())
10159     return false;   // Do not delete arguments unless we have a function body.
10160
10161   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10162       !CallerPAL.isEmpty())
10163     // In this case we have more arguments than the new function type, but we
10164     // won't be dropping them.  Check that these extra arguments have attributes
10165     // that are compatible with being a vararg call argument.
10166     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10167       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10168         break;
10169       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10170       if (PAttrs & Attribute::VarArgsIncompatible)
10171         return false;
10172     }
10173
10174   // Okay, we decided that this is a safe thing to do: go ahead and start
10175   // inserting cast instructions as necessary...
10176   std::vector<Value*> Args;
10177   Args.reserve(NumActualArgs);
10178   SmallVector<AttributeWithIndex, 8> attrVec;
10179   attrVec.reserve(NumCommonArgs);
10180
10181   // Get any return attributes.
10182   Attributes RAttrs = CallerPAL.getRetAttributes();
10183
10184   // If the return value is not being used, the type may not be compatible
10185   // with the existing attributes.  Wipe out any problematic attributes.
10186   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10187
10188   // Add the new return attributes.
10189   if (RAttrs)
10190     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10191
10192   AI = CS.arg_begin();
10193   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10194     const Type *ParamTy = FT->getParamType(i);
10195     if ((*AI)->getType() == ParamTy) {
10196       Args.push_back(*AI);
10197     } else {
10198       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10199           false, ParamTy, false);
10200       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10201       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10202     }
10203
10204     // Add any parameter attributes.
10205     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10206       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10207   }
10208
10209   // If the function takes more arguments than the call was taking, add them
10210   // now...
10211   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10212     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10213
10214   // If we are removing arguments to the function, emit an obnoxious warning...
10215   if (FT->getNumParams() < NumActualArgs) {
10216     if (!FT->isVarArg()) {
10217       cerr << "WARNING: While resolving call to function '"
10218            << Callee->getName() << "' arguments were dropped!\n";
10219     } else {
10220       // Add all of the arguments in their promoted form to the arg list...
10221       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10222         const Type *PTy = getPromotedType((*AI)->getType());
10223         if (PTy != (*AI)->getType()) {
10224           // Must promote to pass through va_arg area!
10225           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
10226                                                                 PTy, false);
10227           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10228           InsertNewInstBefore(Cast, *Caller);
10229           Args.push_back(Cast);
10230         } else {
10231           Args.push_back(*AI);
10232         }
10233
10234         // Add any parameter attributes.
10235         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10236           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10237       }
10238     }
10239   }
10240
10241   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10242     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10243
10244   if (NewRetTy == Type::VoidTy)
10245     Caller->setName("");   // Void type should not have a name.
10246
10247   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
10248
10249   Instruction *NC;
10250   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10251     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10252                             Args.begin(), Args.end(),
10253                             Caller->getName(), Caller);
10254     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10255     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10256   } else {
10257     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10258                           Caller->getName(), Caller);
10259     CallInst *CI = cast<CallInst>(Caller);
10260     if (CI->isTailCall())
10261       cast<CallInst>(NC)->setTailCall();
10262     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10263     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10264   }
10265
10266   // Insert a cast of the return type as necessary.
10267   Value *NV = NC;
10268   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10269     if (NV->getType() != Type::VoidTy) {
10270       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10271                                                             OldRetTy, false);
10272       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10273
10274       // If this is an invoke instruction, we should insert it after the first
10275       // non-phi, instruction in the normal successor block.
10276       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10277         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10278         InsertNewInstBefore(NC, *I);
10279       } else {
10280         // Otherwise, it's a call, just insert cast right after the call instr
10281         InsertNewInstBefore(NC, *Caller);
10282       }
10283       AddUsersToWorkList(*Caller);
10284     } else {
10285       NV = UndefValue::get(Caller->getType());
10286     }
10287   }
10288
10289   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10290     Caller->replaceAllUsesWith(NV);
10291   Caller->eraseFromParent();
10292   RemoveFromWorkList(Caller);
10293   return true;
10294 }
10295
10296 // transformCallThroughTrampoline - Turn a call to a function created by the
10297 // init_trampoline intrinsic into a direct call to the underlying function.
10298 //
10299 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10300   Value *Callee = CS.getCalledValue();
10301   const PointerType *PTy = cast<PointerType>(Callee->getType());
10302   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10303   const AttrListPtr &Attrs = CS.getAttributes();
10304
10305   // If the call already has the 'nest' attribute somewhere then give up -
10306   // otherwise 'nest' would occur twice after splicing in the chain.
10307   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10308     return 0;
10309
10310   IntrinsicInst *Tramp =
10311     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10312
10313   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10314   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10315   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10316
10317   const AttrListPtr &NestAttrs = NestF->getAttributes();
10318   if (!NestAttrs.isEmpty()) {
10319     unsigned NestIdx = 1;
10320     const Type *NestTy = 0;
10321     Attributes NestAttr = Attribute::None;
10322
10323     // Look for a parameter marked with the 'nest' attribute.
10324     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10325          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10326       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10327         // Record the parameter type and any other attributes.
10328         NestTy = *I;
10329         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10330         break;
10331       }
10332
10333     if (NestTy) {
10334       Instruction *Caller = CS.getInstruction();
10335       std::vector<Value*> NewArgs;
10336       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10337
10338       SmallVector<AttributeWithIndex, 8> NewAttrs;
10339       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10340
10341       // Insert the nest argument into the call argument list, which may
10342       // mean appending it.  Likewise for attributes.
10343
10344       // Add any result attributes.
10345       if (Attributes Attr = Attrs.getRetAttributes())
10346         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10347
10348       {
10349         unsigned Idx = 1;
10350         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10351         do {
10352           if (Idx == NestIdx) {
10353             // Add the chain argument and attributes.
10354             Value *NestVal = Tramp->getOperand(3);
10355             if (NestVal->getType() != NestTy)
10356               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10357             NewArgs.push_back(NestVal);
10358             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10359           }
10360
10361           if (I == E)
10362             break;
10363
10364           // Add the original argument and attributes.
10365           NewArgs.push_back(*I);
10366           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10367             NewAttrs.push_back
10368               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10369
10370           ++Idx, ++I;
10371         } while (1);
10372       }
10373
10374       // Add any function attributes.
10375       if (Attributes Attr = Attrs.getFnAttributes())
10376         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10377
10378       // The trampoline may have been bitcast to a bogus type (FTy).
10379       // Handle this by synthesizing a new function type, equal to FTy
10380       // with the chain parameter inserted.
10381
10382       std::vector<const Type*> NewTypes;
10383       NewTypes.reserve(FTy->getNumParams()+1);
10384
10385       // Insert the chain's type into the list of parameter types, which may
10386       // mean appending it.
10387       {
10388         unsigned Idx = 1;
10389         FunctionType::param_iterator I = FTy->param_begin(),
10390           E = FTy->param_end();
10391
10392         do {
10393           if (Idx == NestIdx)
10394             // Add the chain's type.
10395             NewTypes.push_back(NestTy);
10396
10397           if (I == E)
10398             break;
10399
10400           // Add the original type.
10401           NewTypes.push_back(*I);
10402
10403           ++Idx, ++I;
10404         } while (1);
10405       }
10406
10407       // Replace the trampoline call with a direct call.  Let the generic
10408       // code sort out any function type mismatches.
10409       FunctionType *NewFTy =
10410         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
10411       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
10412         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
10413       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
10414
10415       Instruction *NewCaller;
10416       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10417         NewCaller = InvokeInst::Create(NewCallee,
10418                                        II->getNormalDest(), II->getUnwindDest(),
10419                                        NewArgs.begin(), NewArgs.end(),
10420                                        Caller->getName(), Caller);
10421         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10422         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10423       } else {
10424         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10425                                      Caller->getName(), Caller);
10426         if (cast<CallInst>(Caller)->isTailCall())
10427           cast<CallInst>(NewCaller)->setTailCall();
10428         cast<CallInst>(NewCaller)->
10429           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10430         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10431       }
10432       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10433         Caller->replaceAllUsesWith(NewCaller);
10434       Caller->eraseFromParent();
10435       RemoveFromWorkList(Caller);
10436       return 0;
10437     }
10438   }
10439
10440   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10441   // parameter, there is no need to adjust the argument list.  Let the generic
10442   // code sort out any function type mismatches.
10443   Constant *NewCallee =
10444     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
10445   CS.setCalledFunction(NewCallee);
10446   return CS.getInstruction();
10447 }
10448
10449 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10450 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10451 /// and a single binop.
10452 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10453   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10454   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10455   unsigned Opc = FirstInst->getOpcode();
10456   Value *LHSVal = FirstInst->getOperand(0);
10457   Value *RHSVal = FirstInst->getOperand(1);
10458     
10459   const Type *LHSType = LHSVal->getType();
10460   const Type *RHSType = RHSVal->getType();
10461   
10462   // Scan to see if all operands are the same opcode, all have one use, and all
10463   // kill their operands (i.e. the operands have one use).
10464   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10465     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10466     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10467         // Verify type of the LHS matches so we don't fold cmp's of different
10468         // types or GEP's with different index types.
10469         I->getOperand(0)->getType() != LHSType ||
10470         I->getOperand(1)->getType() != RHSType)
10471       return 0;
10472
10473     // If they are CmpInst instructions, check their predicates
10474     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10475       if (cast<CmpInst>(I)->getPredicate() !=
10476           cast<CmpInst>(FirstInst)->getPredicate())
10477         return 0;
10478     
10479     // Keep track of which operand needs a phi node.
10480     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10481     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10482   }
10483   
10484   // Otherwise, this is safe to transform!
10485   
10486   Value *InLHS = FirstInst->getOperand(0);
10487   Value *InRHS = FirstInst->getOperand(1);
10488   PHINode *NewLHS = 0, *NewRHS = 0;
10489   if (LHSVal == 0) {
10490     NewLHS = PHINode::Create(LHSType,
10491                              FirstInst->getOperand(0)->getName() + ".pn");
10492     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10493     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10494     InsertNewInstBefore(NewLHS, PN);
10495     LHSVal = NewLHS;
10496   }
10497   
10498   if (RHSVal == 0) {
10499     NewRHS = PHINode::Create(RHSType,
10500                              FirstInst->getOperand(1)->getName() + ".pn");
10501     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10502     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10503     InsertNewInstBefore(NewRHS, PN);
10504     RHSVal = NewRHS;
10505   }
10506   
10507   // Add all operands to the new PHIs.
10508   if (NewLHS || NewRHS) {
10509     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10510       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10511       if (NewLHS) {
10512         Value *NewInLHS = InInst->getOperand(0);
10513         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10514       }
10515       if (NewRHS) {
10516         Value *NewInRHS = InInst->getOperand(1);
10517         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10518       }
10519     }
10520   }
10521     
10522   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10523     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10524   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10525   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10526                          RHSVal);
10527 }
10528
10529 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10530   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10531   
10532   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10533                                         FirstInst->op_end());
10534   // This is true if all GEP bases are allocas and if all indices into them are
10535   // constants.
10536   bool AllBasePointersAreAllocas = true;
10537   
10538   // Scan to see if all operands are the same opcode, all have one use, and all
10539   // kill their operands (i.e. the operands have one use).
10540   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10541     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10542     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10543       GEP->getNumOperands() != FirstInst->getNumOperands())
10544       return 0;
10545
10546     // Keep track of whether or not all GEPs are of alloca pointers.
10547     if (AllBasePointersAreAllocas &&
10548         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10549          !GEP->hasAllConstantIndices()))
10550       AllBasePointersAreAllocas = false;
10551     
10552     // Compare the operand lists.
10553     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10554       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10555         continue;
10556       
10557       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10558       // if one of the PHIs has a constant for the index.  The index may be
10559       // substantially cheaper to compute for the constants, so making it a
10560       // variable index could pessimize the path.  This also handles the case
10561       // for struct indices, which must always be constant.
10562       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10563           isa<ConstantInt>(GEP->getOperand(op)))
10564         return 0;
10565       
10566       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10567         return 0;
10568       FixedOperands[op] = 0;  // Needs a PHI.
10569     }
10570   }
10571   
10572   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10573   // bother doing this transformation.  At best, this will just save a bit of
10574   // offset calculation, but all the predecessors will have to materialize the
10575   // stack address into a register anyway.  We'd actually rather *clone* the
10576   // load up into the predecessors so that we have a load of a gep of an alloca,
10577   // which can usually all be folded into the load.
10578   if (AllBasePointersAreAllocas)
10579     return 0;
10580   
10581   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10582   // that is variable.
10583   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10584   
10585   bool HasAnyPHIs = false;
10586   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10587     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10588     Value *FirstOp = FirstInst->getOperand(i);
10589     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10590                                      FirstOp->getName()+".pn");
10591     InsertNewInstBefore(NewPN, PN);
10592     
10593     NewPN->reserveOperandSpace(e);
10594     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10595     OperandPhis[i] = NewPN;
10596     FixedOperands[i] = NewPN;
10597     HasAnyPHIs = true;
10598   }
10599
10600   
10601   // Add all operands to the new PHIs.
10602   if (HasAnyPHIs) {
10603     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10604       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10605       BasicBlock *InBB = PN.getIncomingBlock(i);
10606       
10607       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10608         if (PHINode *OpPhi = OperandPhis[op])
10609           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10610     }
10611   }
10612   
10613   Value *Base = FixedOperands[0];
10614   return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10615                                    FixedOperands.end());
10616 }
10617
10618
10619 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10620 /// sink the load out of the block that defines it.  This means that it must be
10621 /// obvious the value of the load is not changed from the point of the load to
10622 /// the end of the block it is in.
10623 ///
10624 /// Finally, it is safe, but not profitable, to sink a load targetting a
10625 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10626 /// to a register.
10627 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10628   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10629   
10630   for (++BBI; BBI != E; ++BBI)
10631     if (BBI->mayWriteToMemory())
10632       return false;
10633   
10634   // Check for non-address taken alloca.  If not address-taken already, it isn't
10635   // profitable to do this xform.
10636   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10637     bool isAddressTaken = false;
10638     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10639          UI != E; ++UI) {
10640       if (isa<LoadInst>(UI)) continue;
10641       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10642         // If storing TO the alloca, then the address isn't taken.
10643         if (SI->getOperand(1) == AI) continue;
10644       }
10645       isAddressTaken = true;
10646       break;
10647     }
10648     
10649     if (!isAddressTaken && AI->isStaticAlloca())
10650       return false;
10651   }
10652   
10653   // If this load is a load from a GEP with a constant offset from an alloca,
10654   // then we don't want to sink it.  In its present form, it will be
10655   // load [constant stack offset].  Sinking it will cause us to have to
10656   // materialize the stack addresses in each predecessor in a register only to
10657   // do a shared load from register in the successor.
10658   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10659     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10660       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10661         return false;
10662   
10663   return true;
10664 }
10665
10666
10667 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10668 // operator and they all are only used by the PHI, PHI together their
10669 // inputs, and do the operation once, to the result of the PHI.
10670 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10671   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10672
10673   // Scan the instruction, looking for input operations that can be folded away.
10674   // If all input operands to the phi are the same instruction (e.g. a cast from
10675   // the same type or "+42") we can pull the operation through the PHI, reducing
10676   // code size and simplifying code.
10677   Constant *ConstantOp = 0;
10678   const Type *CastSrcTy = 0;
10679   bool isVolatile = false;
10680   if (isa<CastInst>(FirstInst)) {
10681     CastSrcTy = FirstInst->getOperand(0)->getType();
10682   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10683     // Can fold binop, compare or shift here if the RHS is a constant, 
10684     // otherwise call FoldPHIArgBinOpIntoPHI.
10685     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10686     if (ConstantOp == 0)
10687       return FoldPHIArgBinOpIntoPHI(PN);
10688   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10689     isVolatile = LI->isVolatile();
10690     // We can't sink the load if the loaded value could be modified between the
10691     // load and the PHI.
10692     if (LI->getParent() != PN.getIncomingBlock(0) ||
10693         !isSafeAndProfitableToSinkLoad(LI))
10694       return 0;
10695     
10696     // If the PHI is of volatile loads and the load block has multiple
10697     // successors, sinking it would remove a load of the volatile value from
10698     // the path through the other successor.
10699     if (isVolatile &&
10700         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10701       return 0;
10702     
10703   } else if (isa<GetElementPtrInst>(FirstInst)) {
10704     return FoldPHIArgGEPIntoPHI(PN);
10705   } else {
10706     return 0;  // Cannot fold this operation.
10707   }
10708
10709   // Check to see if all arguments are the same operation.
10710   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10711     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10712     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10713     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10714       return 0;
10715     if (CastSrcTy) {
10716       if (I->getOperand(0)->getType() != CastSrcTy)
10717         return 0;  // Cast operation must match.
10718     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10719       // We can't sink the load if the loaded value could be modified between 
10720       // the load and the PHI.
10721       if (LI->isVolatile() != isVolatile ||
10722           LI->getParent() != PN.getIncomingBlock(i) ||
10723           !isSafeAndProfitableToSinkLoad(LI))
10724         return 0;
10725       
10726       // If the PHI is of volatile loads and the load block has multiple
10727       // successors, sinking it would remove a load of the volatile value from
10728       // the path through the other successor.
10729       if (isVolatile &&
10730           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10731         return 0;
10732       
10733     } else if (I->getOperand(1) != ConstantOp) {
10734       return 0;
10735     }
10736   }
10737
10738   // Okay, they are all the same operation.  Create a new PHI node of the
10739   // correct type, and PHI together all of the LHS's of the instructions.
10740   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10741                                    PN.getName()+".in");
10742   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10743
10744   Value *InVal = FirstInst->getOperand(0);
10745   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10746
10747   // Add all operands to the new PHI.
10748   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10749     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10750     if (NewInVal != InVal)
10751       InVal = 0;
10752     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10753   }
10754
10755   Value *PhiVal;
10756   if (InVal) {
10757     // The new PHI unions all of the same values together.  This is really
10758     // common, so we handle it intelligently here for compile-time speed.
10759     PhiVal = InVal;
10760     delete NewPN;
10761   } else {
10762     InsertNewInstBefore(NewPN, PN);
10763     PhiVal = NewPN;
10764   }
10765
10766   // Insert and return the new operation.
10767   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10768     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10769   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10770     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10771   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10772     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
10773                            PhiVal, ConstantOp);
10774   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10775   
10776   // If this was a volatile load that we are merging, make sure to loop through
10777   // and mark all the input loads as non-volatile.  If we don't do this, we will
10778   // insert a new volatile load and the old ones will not be deletable.
10779   if (isVolatile)
10780     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10781       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10782   
10783   return new LoadInst(PhiVal, "", isVolatile);
10784 }
10785
10786 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10787 /// that is dead.
10788 static bool DeadPHICycle(PHINode *PN,
10789                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10790   if (PN->use_empty()) return true;
10791   if (!PN->hasOneUse()) return false;
10792
10793   // Remember this node, and if we find the cycle, return.
10794   if (!PotentiallyDeadPHIs.insert(PN))
10795     return true;
10796   
10797   // Don't scan crazily complex things.
10798   if (PotentiallyDeadPHIs.size() == 16)
10799     return false;
10800
10801   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10802     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10803
10804   return false;
10805 }
10806
10807 /// PHIsEqualValue - Return true if this phi node is always equal to
10808 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10809 ///   z = some value; x = phi (y, z); y = phi (x, z)
10810 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10811                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10812   // See if we already saw this PHI node.
10813   if (!ValueEqualPHIs.insert(PN))
10814     return true;
10815   
10816   // Don't scan crazily complex things.
10817   if (ValueEqualPHIs.size() == 16)
10818     return false;
10819  
10820   // Scan the operands to see if they are either phi nodes or are equal to
10821   // the value.
10822   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10823     Value *Op = PN->getIncomingValue(i);
10824     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10825       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10826         return false;
10827     } else if (Op != NonPhiInVal)
10828       return false;
10829   }
10830   
10831   return true;
10832 }
10833
10834
10835 // PHINode simplification
10836 //
10837 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10838   // If LCSSA is around, don't mess with Phi nodes
10839   if (MustPreserveLCSSA) return 0;
10840   
10841   if (Value *V = PN.hasConstantValue())
10842     return ReplaceInstUsesWith(PN, V);
10843
10844   // If all PHI operands are the same operation, pull them through the PHI,
10845   // reducing code size.
10846   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10847       isa<Instruction>(PN.getIncomingValue(1)) &&
10848       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10849       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10850       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10851       // than themselves more than once.
10852       PN.getIncomingValue(0)->hasOneUse())
10853     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10854       return Result;
10855
10856   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10857   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10858   // PHI)... break the cycle.
10859   if (PN.hasOneUse()) {
10860     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10861     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10862       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10863       PotentiallyDeadPHIs.insert(&PN);
10864       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10865         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10866     }
10867    
10868     // If this phi has a single use, and if that use just computes a value for
10869     // the next iteration of a loop, delete the phi.  This occurs with unused
10870     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10871     // common case here is good because the only other things that catch this
10872     // are induction variable analysis (sometimes) and ADCE, which is only run
10873     // late.
10874     if (PHIUser->hasOneUse() &&
10875         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10876         PHIUser->use_back() == &PN) {
10877       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10878     }
10879   }
10880
10881   // We sometimes end up with phi cycles that non-obviously end up being the
10882   // same value, for example:
10883   //   z = some value; x = phi (y, z); y = phi (x, z)
10884   // where the phi nodes don't necessarily need to be in the same block.  Do a
10885   // quick check to see if the PHI node only contains a single non-phi value, if
10886   // so, scan to see if the phi cycle is actually equal to that value.
10887   {
10888     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10889     // Scan for the first non-phi operand.
10890     while (InValNo != NumOperandVals && 
10891            isa<PHINode>(PN.getIncomingValue(InValNo)))
10892       ++InValNo;
10893
10894     if (InValNo != NumOperandVals) {
10895       Value *NonPhiInVal = PN.getOperand(InValNo);
10896       
10897       // Scan the rest of the operands to see if there are any conflicts, if so
10898       // there is no need to recursively scan other phis.
10899       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10900         Value *OpVal = PN.getIncomingValue(InValNo);
10901         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10902           break;
10903       }
10904       
10905       // If we scanned over all operands, then we have one unique value plus
10906       // phi values.  Scan PHI nodes to see if they all merge in each other or
10907       // the value.
10908       if (InValNo == NumOperandVals) {
10909         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10910         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10911           return ReplaceInstUsesWith(PN, NonPhiInVal);
10912       }
10913     }
10914   }
10915   return 0;
10916 }
10917
10918 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10919                                    Instruction *InsertPoint,
10920                                    InstCombiner *IC) {
10921   unsigned PtrSize = DTy->getScalarSizeInBits();
10922   unsigned VTySize = V->getType()->getScalarSizeInBits();
10923   // We must cast correctly to the pointer type. Ensure that we
10924   // sign extend the integer value if it is smaller as this is
10925   // used for address computation.
10926   Instruction::CastOps opcode = 
10927      (VTySize < PtrSize ? Instruction::SExt :
10928       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10929   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10930 }
10931
10932
10933 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10934   Value *PtrOp = GEP.getOperand(0);
10935   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10936   // If so, eliminate the noop.
10937   if (GEP.getNumOperands() == 1)
10938     return ReplaceInstUsesWith(GEP, PtrOp);
10939
10940   if (isa<UndefValue>(GEP.getOperand(0)))
10941     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10942
10943   bool HasZeroPointerIndex = false;
10944   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10945     HasZeroPointerIndex = C->isNullValue();
10946
10947   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10948     return ReplaceInstUsesWith(GEP, PtrOp);
10949
10950   // Eliminate unneeded casts for indices.
10951   bool MadeChange = false;
10952   
10953   gep_type_iterator GTI = gep_type_begin(GEP);
10954   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10955        i != e; ++i, ++GTI) {
10956     if (isa<SequentialType>(*GTI)) {
10957       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
10958         if (CI->getOpcode() == Instruction::ZExt ||
10959             CI->getOpcode() == Instruction::SExt) {
10960           const Type *SrcTy = CI->getOperand(0)->getType();
10961           // We can eliminate a cast from i32 to i64 iff the target 
10962           // is a 32-bit pointer target.
10963           if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
10964             MadeChange = true;
10965             *i = CI->getOperand(0);
10966           }
10967         }
10968       }
10969       // If we are using a wider index than needed for this platform, shrink it
10970       // to what we need.  If narrower, sign-extend it to what we need.
10971       // If the incoming value needs a cast instruction,
10972       // insert it.  This explicit cast can make subsequent optimizations more
10973       // obvious.
10974       Value *Op = *i;
10975       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
10976         if (Constant *C = dyn_cast<Constant>(Op)) {
10977           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
10978           MadeChange = true;
10979         } else {
10980           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10981                                 GEP);
10982           *i = Op;
10983           MadeChange = true;
10984         }
10985       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10986         if (Constant *C = dyn_cast<Constant>(Op)) {
10987           *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10988           MadeChange = true;
10989         } else {
10990           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10991                                 GEP);
10992           *i = Op;
10993           MadeChange = true;
10994         }
10995       }
10996     }
10997   }
10998   if (MadeChange) return &GEP;
10999
11000   // Combine Indices - If the source pointer to this getelementptr instruction
11001   // is a getelementptr instruction, combine the indices of the two
11002   // getelementptr instructions into a single instruction.
11003   //
11004   SmallVector<Value*, 8> SrcGEPOperands;
11005   if (User *Src = dyn_castGetElementPtr(PtrOp))
11006     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
11007
11008   if (!SrcGEPOperands.empty()) {
11009     // Note that if our source is a gep chain itself that we wait for that
11010     // chain to be resolved before we perform this transformation.  This
11011     // avoids us creating a TON of code in some cases.
11012     //
11013     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11014         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11015       return 0;   // Wait until our source is folded to completion.
11016
11017     SmallVector<Value*, 8> Indices;
11018
11019     // Find out whether the last index in the source GEP is a sequential idx.
11020     bool EndsWithSequential = false;
11021     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11022            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11023       EndsWithSequential = !isa<StructType>(*I);
11024
11025     // Can we combine the two pointer arithmetics offsets?
11026     if (EndsWithSequential) {
11027       // Replace: gep (gep %P, long B), long A, ...
11028       // With:    T = long A+B; gep %P, T, ...
11029       //
11030       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
11031       if (SO1 == Constant::getNullValue(SO1->getType())) {
11032         Sum = GO1;
11033       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
11034         Sum = SO1;
11035       } else {
11036         // If they aren't the same type, convert both to an integer of the
11037         // target's pointer size.
11038         if (SO1->getType() != GO1->getType()) {
11039           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
11040             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
11041           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
11042             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
11043           } else {
11044             unsigned PS = TD->getPointerSizeInBits();
11045             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
11046               // Convert GO1 to SO1's type.
11047               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11048
11049             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
11050               // Convert SO1 to GO1's type.
11051               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11052             } else {
11053               const Type *PT = TD->getIntPtrType();
11054               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11055               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11056             }
11057           }
11058         }
11059         if (isa<Constant>(SO1) && isa<Constant>(GO1))
11060           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
11061         else {
11062           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11063           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11064         }
11065       }
11066
11067       // Recycle the GEP we already have if possible.
11068       if (SrcGEPOperands.size() == 2) {
11069         GEP.setOperand(0, SrcGEPOperands[0]);
11070         GEP.setOperand(1, Sum);
11071         return &GEP;
11072       } else {
11073         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11074                        SrcGEPOperands.end()-1);
11075         Indices.push_back(Sum);
11076         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11077       }
11078     } else if (isa<Constant>(*GEP.idx_begin()) &&
11079                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11080                SrcGEPOperands.size() != 1) {
11081       // Otherwise we can do the fold if the first index of the GEP is a zero
11082       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11083                      SrcGEPOperands.end());
11084       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11085     }
11086
11087     if (!Indices.empty())
11088       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11089                                        Indices.end(), GEP.getName());
11090
11091   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11092     // GEP of global variable.  If all of the indices for this GEP are
11093     // constants, we can promote this to a constexpr instead of an instruction.
11094
11095     // Scan for nonconstants...
11096     SmallVector<Constant*, 8> Indices;
11097     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11098     for (; I != E && isa<Constant>(*I); ++I)
11099       Indices.push_back(cast<Constant>(*I));
11100
11101     if (I == E) {  // If they are all constants...
11102       Constant *CE = ConstantExpr::getGetElementPtr(GV,
11103                                                     &Indices[0],Indices.size());
11104
11105       // Replace all uses of the GEP with the new constexpr...
11106       return ReplaceInstUsesWith(GEP, CE);
11107     }
11108   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
11109     if (!isa<PointerType>(X->getType())) {
11110       // Not interesting.  Source pointer must be a cast from pointer.
11111     } else if (HasZeroPointerIndex) {
11112       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11113       // into     : GEP [10 x i8]* X, i32 0, ...
11114       //
11115       // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11116       //           into     : GEP i8* X, ...
11117       // 
11118       // This occurs when the program declares an array extern like "int X[];"
11119       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11120       const PointerType *XTy = cast<PointerType>(X->getType());
11121       if (const ArrayType *CATy =
11122           dyn_cast<ArrayType>(CPTy->getElementType())) {
11123         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11124         if (CATy->getElementType() == XTy->getElementType()) {
11125           // -> GEP i8* X, ...
11126           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11127           return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11128                                            GEP.getName());
11129         } else if (const ArrayType *XATy =
11130                  dyn_cast<ArrayType>(XTy->getElementType())) {
11131           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11132           if (CATy->getElementType() == XATy->getElementType()) {
11133             // -> GEP [10 x i8]* X, i32 0, ...
11134             // At this point, we know that the cast source type is a pointer
11135             // to an array of the same type as the destination pointer
11136             // array.  Because the array type is never stepped over (there
11137             // is a leading zero) we can fold the cast into this GEP.
11138             GEP.setOperand(0, X);
11139             return &GEP;
11140           }
11141         }
11142       }
11143     } else if (GEP.getNumOperands() == 2) {
11144       // Transform things like:
11145       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11146       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11147       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11148       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11149       if (isa<ArrayType>(SrcElTy) &&
11150           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11151           TD->getTypeAllocSize(ResElTy)) {
11152         Value *Idx[2];
11153         Idx[0] = Constant::getNullValue(Type::Int32Ty);
11154         Idx[1] = GEP.getOperand(1);
11155         Value *V = InsertNewInstBefore(
11156                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
11157         // V and GEP are both pointer types --> BitCast
11158         return new BitCastInst(V, GEP.getType());
11159       }
11160       
11161       // Transform things like:
11162       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11163       //   (where tmp = 8*tmp2) into:
11164       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11165       
11166       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
11167         uint64_t ArrayEltSize =
11168             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11169         
11170         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11171         // allow either a mul, shift, or constant here.
11172         Value *NewIdx = 0;
11173         ConstantInt *Scale = 0;
11174         if (ArrayEltSize == 1) {
11175           NewIdx = GEP.getOperand(1);
11176           Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
11177         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11178           NewIdx = ConstantInt::get(CI->getType(), 1);
11179           Scale = CI;
11180         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11181           if (Inst->getOpcode() == Instruction::Shl &&
11182               isa<ConstantInt>(Inst->getOperand(1))) {
11183             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11184             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11185             Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11186                                      1ULL << ShAmtVal);
11187             NewIdx = Inst->getOperand(0);
11188           } else if (Inst->getOpcode() == Instruction::Mul &&
11189                      isa<ConstantInt>(Inst->getOperand(1))) {
11190             Scale = cast<ConstantInt>(Inst->getOperand(1));
11191             NewIdx = Inst->getOperand(0);
11192           }
11193         }
11194         
11195         // If the index will be to exactly the right offset with the scale taken
11196         // out, perform the transformation. Note, we don't know whether Scale is
11197         // signed or not. We'll use unsigned version of division/modulo
11198         // operation after making sure Scale doesn't have the sign bit set.
11199         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11200             Scale->getZExtValue() % ArrayEltSize == 0) {
11201           Scale = ConstantInt::get(Scale->getType(),
11202                                    Scale->getZExtValue() / ArrayEltSize);
11203           if (Scale->getZExtValue() != 1) {
11204             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11205                                                        false /*ZExt*/);
11206             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11207             NewIdx = InsertNewInstBefore(Sc, GEP);
11208           }
11209
11210           // Insert the new GEP instruction.
11211           Value *Idx[2];
11212           Idx[0] = Constant::getNullValue(Type::Int32Ty);
11213           Idx[1] = NewIdx;
11214           Instruction *NewGEP =
11215             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11216           NewGEP = InsertNewInstBefore(NewGEP, GEP);
11217           // The NewGEP must be pointer typed, so must the old one -> BitCast
11218           return new BitCastInst(NewGEP, GEP.getType());
11219         }
11220       }
11221     }
11222   }
11223   
11224   /// See if we can simplify:
11225   ///   X = bitcast A to B*
11226   ///   Y = gep X, <...constant indices...>
11227   /// into a gep of the original struct.  This is important for SROA and alias
11228   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11229   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11230     if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11231       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11232       // a constant back from EmitGEPOffset.
11233       ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11234       int64_t Offset = OffsetV->getSExtValue();
11235       
11236       // If this GEP instruction doesn't move the pointer, just replace the GEP
11237       // with a bitcast of the real input to the dest type.
11238       if (Offset == 0) {
11239         // If the bitcast is of an allocation, and the allocation will be
11240         // converted to match the type of the cast, don't touch this.
11241         if (isa<AllocationInst>(BCI->getOperand(0))) {
11242           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11243           if (Instruction *I = visitBitCast(*BCI)) {
11244             if (I != BCI) {
11245               I->takeName(BCI);
11246               BCI->getParent()->getInstList().insert(BCI, I);
11247               ReplaceInstUsesWith(*BCI, I);
11248             }
11249             return &GEP;
11250           }
11251         }
11252         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11253       }
11254       
11255       // Otherwise, if the offset is non-zero, we need to find out if there is a
11256       // field at Offset in 'A's type.  If so, we can pull the cast through the
11257       // GEP.
11258       SmallVector<Value*, 8> NewIndices;
11259       const Type *InTy =
11260         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11261       if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
11262         Instruction *NGEP =
11263            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11264                                      NewIndices.end());
11265         if (NGEP->getType() == GEP.getType()) return NGEP;
11266         InsertNewInstBefore(NGEP, GEP);
11267         NGEP->takeName(&GEP);
11268         return new BitCastInst(NGEP, GEP.getType());
11269       }
11270     }
11271   }    
11272     
11273   return 0;
11274 }
11275
11276 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11277   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11278   if (AI.isArrayAllocation()) {  // Check C != 1
11279     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11280       const Type *NewTy = 
11281         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11282       AllocationInst *New = 0;
11283
11284       // Create and insert the replacement instruction...
11285       if (isa<MallocInst>(AI))
11286         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11287       else {
11288         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11289         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11290       }
11291
11292       InsertNewInstBefore(New, AI);
11293
11294       // Scan to the end of the allocation instructions, to skip over a block of
11295       // allocas if possible...also skip interleaved debug info
11296       //
11297       BasicBlock::iterator It = New;
11298       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11299
11300       // Now that I is pointing to the first non-allocation-inst in the block,
11301       // insert our getelementptr instruction...
11302       //
11303       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
11304       Value *Idx[2];
11305       Idx[0] = NullIdx;
11306       Idx[1] = NullIdx;
11307       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11308                                            New->getName()+".sub", It);
11309
11310       // Now make everything use the getelementptr instead of the original
11311       // allocation.
11312       return ReplaceInstUsesWith(AI, V);
11313     } else if (isa<UndefValue>(AI.getArraySize())) {
11314       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11315     }
11316   }
11317
11318   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11319     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11320     // Note that we only do this for alloca's, because malloc should allocate
11321     // and return a unique pointer, even for a zero byte allocation.
11322     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11323       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11324
11325     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11326     if (AI.getAlignment() == 0)
11327       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11328   }
11329
11330   return 0;
11331 }
11332
11333 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11334   Value *Op = FI.getOperand(0);
11335
11336   // free undef -> unreachable.
11337   if (isa<UndefValue>(Op)) {
11338     // Insert a new store to null because we cannot modify the CFG here.
11339     new StoreInst(ConstantInt::getTrue(),
11340                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
11341     return EraseInstFromFunction(FI);
11342   }
11343   
11344   // If we have 'free null' delete the instruction.  This can happen in stl code
11345   // when lots of inlining happens.
11346   if (isa<ConstantPointerNull>(Op))
11347     return EraseInstFromFunction(FI);
11348   
11349   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11350   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11351     FI.setOperand(0, CI->getOperand(0));
11352     return &FI;
11353   }
11354   
11355   // Change free (gep X, 0,0,0,0) into free(X)
11356   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11357     if (GEPI->hasAllZeroIndices()) {
11358       AddToWorkList(GEPI);
11359       FI.setOperand(0, GEPI->getOperand(0));
11360       return &FI;
11361     }
11362   }
11363   
11364   // Change free(malloc) into nothing, if the malloc has a single use.
11365   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11366     if (MI->hasOneUse()) {
11367       EraseInstFromFunction(FI);
11368       return EraseInstFromFunction(*MI);
11369     }
11370
11371   return 0;
11372 }
11373
11374
11375 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11376 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11377                                         const TargetData *TD) {
11378   User *CI = cast<User>(LI.getOperand(0));
11379   Value *CastOp = CI->getOperand(0);
11380
11381   if (TD) {
11382     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11383       // Instead of loading constant c string, use corresponding integer value
11384       // directly if string length is small enough.
11385       std::string Str;
11386       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11387         unsigned len = Str.length();
11388         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11389         unsigned numBits = Ty->getPrimitiveSizeInBits();
11390         // Replace LI with immediate integer store.
11391         if ((numBits >> 3) == len + 1) {
11392           APInt StrVal(numBits, 0);
11393           APInt SingleChar(numBits, 0);
11394           if (TD->isLittleEndian()) {
11395             for (signed i = len-1; i >= 0; i--) {
11396               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11397               StrVal = (StrVal << 8) | SingleChar;
11398             }
11399           } else {
11400             for (unsigned i = 0; i < len; i++) {
11401               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11402               StrVal = (StrVal << 8) | SingleChar;
11403             }
11404             // Append NULL at the end.
11405             SingleChar = 0;
11406             StrVal = (StrVal << 8) | SingleChar;
11407           }
11408           Value *NL = ConstantInt::get(StrVal);
11409           return IC.ReplaceInstUsesWith(LI, NL);
11410         }
11411       }
11412     }
11413   }
11414
11415   const PointerType *DestTy = cast<PointerType>(CI->getType());
11416   const Type *DestPTy = DestTy->getElementType();
11417   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11418
11419     // If the address spaces don't match, don't eliminate the cast.
11420     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11421       return 0;
11422
11423     const Type *SrcPTy = SrcTy->getElementType();
11424
11425     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11426          isa<VectorType>(DestPTy)) {
11427       // If the source is an array, the code below will not succeed.  Check to
11428       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11429       // constants.
11430       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11431         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11432           if (ASrcTy->getNumElements() != 0) {
11433             Value *Idxs[2];
11434             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
11435             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11436             SrcTy = cast<PointerType>(CastOp->getType());
11437             SrcPTy = SrcTy->getElementType();
11438           }
11439
11440       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11441             isa<VectorType>(SrcPTy)) &&
11442           // Do not allow turning this into a load of an integer, which is then
11443           // casted to a pointer, this pessimizes pointer analysis a lot.
11444           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11445           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11446                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11447
11448         // Okay, we are casting from one integer or pointer type to another of
11449         // the same size.  Instead of casting the pointer before the load, cast
11450         // the result of the loaded value.
11451         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11452                                                              CI->getName(),
11453                                                          LI.isVolatile()),LI);
11454         // Now cast the result of the load.
11455         return new BitCastInst(NewLoad, LI.getType());
11456       }
11457     }
11458   }
11459   return 0;
11460 }
11461
11462 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11463   Value *Op = LI.getOperand(0);
11464
11465   // Attempt to improve the alignment.
11466   unsigned KnownAlign =
11467     GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11468   if (KnownAlign >
11469       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11470                                 LI.getAlignment()))
11471     LI.setAlignment(KnownAlign);
11472
11473   // load (cast X) --> cast (load X) iff safe
11474   if (isa<CastInst>(Op))
11475     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11476       return Res;
11477
11478   // None of the following transforms are legal for volatile loads.
11479   if (LI.isVolatile()) return 0;
11480   
11481   // Do really simple store-to-load forwarding and load CSE, to catch cases
11482   // where there are several consequtive memory accesses to the same location,
11483   // separated by a few arithmetic operations.
11484   BasicBlock::iterator BBI = &LI;
11485   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11486     return ReplaceInstUsesWith(LI, AvailableVal);
11487
11488   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11489     const Value *GEPI0 = GEPI->getOperand(0);
11490     // TODO: Consider a target hook for valid address spaces for this xform.
11491     if (isa<ConstantPointerNull>(GEPI0) &&
11492         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11493       // Insert a new store to null instruction before the load to indicate
11494       // that this code is not reachable.  We do this instead of inserting
11495       // an unreachable instruction directly because we cannot modify the
11496       // CFG.
11497       new StoreInst(UndefValue::get(LI.getType()),
11498                     Constant::getNullValue(Op->getType()), &LI);
11499       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11500     }
11501   } 
11502
11503   if (Constant *C = dyn_cast<Constant>(Op)) {
11504     // load null/undef -> undef
11505     // TODO: Consider a target hook for valid address spaces for this xform.
11506     if (isa<UndefValue>(C) || (C->isNullValue() && 
11507         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11508       // Insert a new store to null instruction before the load to indicate that
11509       // this code is not reachable.  We do this instead of inserting an
11510       // unreachable instruction directly because we cannot modify the CFG.
11511       new StoreInst(UndefValue::get(LI.getType()),
11512                     Constant::getNullValue(Op->getType()), &LI);
11513       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11514     }
11515
11516     // Instcombine load (constant global) into the value loaded.
11517     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11518       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11519         return ReplaceInstUsesWith(LI, GV->getInitializer());
11520
11521     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11522     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11523       if (CE->getOpcode() == Instruction::GetElementPtr) {
11524         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11525           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11526             if (Constant *V = 
11527                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
11528               return ReplaceInstUsesWith(LI, V);
11529         if (CE->getOperand(0)->isNullValue()) {
11530           // Insert a new store to null instruction before the load to indicate
11531           // that this code is not reachable.  We do this instead of inserting
11532           // an unreachable instruction directly because we cannot modify the
11533           // CFG.
11534           new StoreInst(UndefValue::get(LI.getType()),
11535                         Constant::getNullValue(Op->getType()), &LI);
11536           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11537         }
11538
11539       } else if (CE->isCast()) {
11540         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11541           return Res;
11542       }
11543     }
11544   }
11545     
11546   // If this load comes from anywhere in a constant global, and if the global
11547   // is all undef or zero, we know what it loads.
11548   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11549     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11550       if (GV->getInitializer()->isNullValue())
11551         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11552       else if (isa<UndefValue>(GV->getInitializer()))
11553         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11554     }
11555   }
11556
11557   if (Op->hasOneUse()) {
11558     // Change select and PHI nodes to select values instead of addresses: this
11559     // helps alias analysis out a lot, allows many others simplifications, and
11560     // exposes redundancy in the code.
11561     //
11562     // Note that we cannot do the transformation unless we know that the
11563     // introduced loads cannot trap!  Something like this is valid as long as
11564     // the condition is always false: load (select bool %C, int* null, int* %G),
11565     // but it would not be valid if we transformed it to load from null
11566     // unconditionally.
11567     //
11568     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11569       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11570       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11571           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11572         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11573                                      SI->getOperand(1)->getName()+".val"), LI);
11574         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11575                                      SI->getOperand(2)->getName()+".val"), LI);
11576         return SelectInst::Create(SI->getCondition(), V1, V2);
11577       }
11578
11579       // load (select (cond, null, P)) -> load P
11580       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11581         if (C->isNullValue()) {
11582           LI.setOperand(0, SI->getOperand(2));
11583           return &LI;
11584         }
11585
11586       // load (select (cond, P, null)) -> load P
11587       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11588         if (C->isNullValue()) {
11589           LI.setOperand(0, SI->getOperand(1));
11590           return &LI;
11591         }
11592     }
11593   }
11594   return 0;
11595 }
11596
11597 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11598 /// when possible.  This makes it generally easy to do alias analysis and/or
11599 /// SROA/mem2reg of the memory object.
11600 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11601   User *CI = cast<User>(SI.getOperand(1));
11602   Value *CastOp = CI->getOperand(0);
11603
11604   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11605   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11606   if (SrcTy == 0) return 0;
11607   
11608   const Type *SrcPTy = SrcTy->getElementType();
11609
11610   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11611     return 0;
11612   
11613   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11614   /// to its first element.  This allows us to handle things like:
11615   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11616   /// on 32-bit hosts.
11617   SmallVector<Value*, 4> NewGEPIndices;
11618   
11619   // If the source is an array, the code below will not succeed.  Check to
11620   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11621   // constants.
11622   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11623     // Index through pointer.
11624     Constant *Zero = Constant::getNullValue(Type::Int32Ty);
11625     NewGEPIndices.push_back(Zero);
11626     
11627     while (1) {
11628       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11629         if (!STy->getNumElements()) /* Struct can be empty {} */
11630           break;
11631         NewGEPIndices.push_back(Zero);
11632         SrcPTy = STy->getElementType(0);
11633       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11634         NewGEPIndices.push_back(Zero);
11635         SrcPTy = ATy->getElementType();
11636       } else {
11637         break;
11638       }
11639     }
11640     
11641     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11642   }
11643
11644   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11645     return 0;
11646   
11647   // If the pointers point into different address spaces or if they point to
11648   // values with different sizes, we can't do the transformation.
11649   if (SrcTy->getAddressSpace() != 
11650         cast<PointerType>(CI->getType())->getAddressSpace() ||
11651       IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
11652       IC.getTargetData().getTypeSizeInBits(DestPTy))
11653     return 0;
11654
11655   // Okay, we are casting from one integer or pointer type to another of
11656   // the same size.  Instead of casting the pointer before 
11657   // the store, cast the value to be stored.
11658   Value *NewCast;
11659   Value *SIOp0 = SI.getOperand(0);
11660   Instruction::CastOps opcode = Instruction::BitCast;
11661   const Type* CastSrcTy = SIOp0->getType();
11662   const Type* CastDstTy = SrcPTy;
11663   if (isa<PointerType>(CastDstTy)) {
11664     if (CastSrcTy->isInteger())
11665       opcode = Instruction::IntToPtr;
11666   } else if (isa<IntegerType>(CastDstTy)) {
11667     if (isa<PointerType>(SIOp0->getType()))
11668       opcode = Instruction::PtrToInt;
11669   }
11670   
11671   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11672   // emit a GEP to index into its first field.
11673   if (!NewGEPIndices.empty()) {
11674     if (Constant *C = dyn_cast<Constant>(CastOp))
11675       CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0], 
11676                                               NewGEPIndices.size());
11677     else
11678       CastOp = IC.InsertNewInstBefore(
11679               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11680                                         NewGEPIndices.end()), SI);
11681   }
11682   
11683   if (Constant *C = dyn_cast<Constant>(SIOp0))
11684     NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11685   else
11686     NewCast = IC.InsertNewInstBefore(
11687       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11688       SI);
11689   return new StoreInst(NewCast, CastOp);
11690 }
11691
11692 /// equivalentAddressValues - Test if A and B will obviously have the same
11693 /// value. This includes recognizing that %t0 and %t1 will have the same
11694 /// value in code like this:
11695 ///   %t0 = getelementptr \@a, 0, 3
11696 ///   store i32 0, i32* %t0
11697 ///   %t1 = getelementptr \@a, 0, 3
11698 ///   %t2 = load i32* %t1
11699 ///
11700 static bool equivalentAddressValues(Value *A, Value *B) {
11701   // Test if the values are trivially equivalent.
11702   if (A == B) return true;
11703   
11704   // Test if the values come form identical arithmetic instructions.
11705   if (isa<BinaryOperator>(A) ||
11706       isa<CastInst>(A) ||
11707       isa<PHINode>(A) ||
11708       isa<GetElementPtrInst>(A))
11709     if (Instruction *BI = dyn_cast<Instruction>(B))
11710       if (cast<Instruction>(A)->isIdenticalTo(BI))
11711         return true;
11712   
11713   // Otherwise they may not be equivalent.
11714   return false;
11715 }
11716
11717 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11718 // return the llvm.dbg.declare.
11719 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11720   if (!V->hasNUses(2))
11721     return 0;
11722   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11723        UI != E; ++UI) {
11724     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11725       return DI;
11726     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11727       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11728         return DI;
11729       }
11730   }
11731   return 0;
11732 }
11733
11734 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11735   Value *Val = SI.getOperand(0);
11736   Value *Ptr = SI.getOperand(1);
11737
11738   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11739     EraseInstFromFunction(SI);
11740     ++NumCombined;
11741     return 0;
11742   }
11743   
11744   // If the RHS is an alloca with a single use, zapify the store, making the
11745   // alloca dead.
11746   // If the RHS is an alloca with a two uses, the other one being a 
11747   // llvm.dbg.declare, zapify the store and the declare, making the
11748   // alloca dead.  We must do this to prevent declare's from affecting
11749   // codegen.
11750   if (!SI.isVolatile()) {
11751     if (Ptr->hasOneUse()) {
11752       if (isa<AllocaInst>(Ptr)) {
11753         EraseInstFromFunction(SI);
11754         ++NumCombined;
11755         return 0;
11756       }
11757       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11758         if (isa<AllocaInst>(GEP->getOperand(0))) {
11759           if (GEP->getOperand(0)->hasOneUse()) {
11760             EraseInstFromFunction(SI);
11761             ++NumCombined;
11762             return 0;
11763           }
11764           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11765             EraseInstFromFunction(*DI);
11766             EraseInstFromFunction(SI);
11767             ++NumCombined;
11768             return 0;
11769           }
11770         }
11771       }
11772     }
11773     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11774       EraseInstFromFunction(*DI);
11775       EraseInstFromFunction(SI);
11776       ++NumCombined;
11777       return 0;
11778     }
11779   }
11780
11781   // Attempt to improve the alignment.
11782   unsigned KnownAlign =
11783     GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11784   if (KnownAlign >
11785       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11786                                 SI.getAlignment()))
11787     SI.setAlignment(KnownAlign);
11788
11789   // Do really simple DSE, to catch cases where there are several consecutive
11790   // stores to the same location, separated by a few arithmetic operations. This
11791   // situation often occurs with bitfield accesses.
11792   BasicBlock::iterator BBI = &SI;
11793   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11794        --ScanInsts) {
11795     --BBI;
11796     // Don't count debug info directives, lest they affect codegen,
11797     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11798     // It is necessary for correctness to skip those that feed into a
11799     // llvm.dbg.declare, as these are not present when debugging is off.
11800     if (isa<DbgInfoIntrinsic>(BBI) ||
11801         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11802       ScanInsts++;
11803       continue;
11804     }    
11805     
11806     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11807       // Prev store isn't volatile, and stores to the same location?
11808       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11809                                                           SI.getOperand(1))) {
11810         ++NumDeadStore;
11811         ++BBI;
11812         EraseInstFromFunction(*PrevSI);
11813         continue;
11814       }
11815       break;
11816     }
11817     
11818     // If this is a load, we have to stop.  However, if the loaded value is from
11819     // the pointer we're loading and is producing the pointer we're storing,
11820     // then *this* store is dead (X = load P; store X -> P).
11821     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11822       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11823           !SI.isVolatile()) {
11824         EraseInstFromFunction(SI);
11825         ++NumCombined;
11826         return 0;
11827       }
11828       // Otherwise, this is a load from some other location.  Stores before it
11829       // may not be dead.
11830       break;
11831     }
11832     
11833     // Don't skip over loads or things that can modify memory.
11834     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11835       break;
11836   }
11837   
11838   
11839   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11840
11841   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11842   if (isa<ConstantPointerNull>(Ptr) &&
11843       cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11844     if (!isa<UndefValue>(Val)) {
11845       SI.setOperand(0, UndefValue::get(Val->getType()));
11846       if (Instruction *U = dyn_cast<Instruction>(Val))
11847         AddToWorkList(U);  // Dropped a use.
11848       ++NumCombined;
11849     }
11850     return 0;  // Do not modify these!
11851   }
11852
11853   // store undef, Ptr -> noop
11854   if (isa<UndefValue>(Val)) {
11855     EraseInstFromFunction(SI);
11856     ++NumCombined;
11857     return 0;
11858   }
11859
11860   // If the pointer destination is a cast, see if we can fold the cast into the
11861   // source instead.
11862   if (isa<CastInst>(Ptr))
11863     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11864       return Res;
11865   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11866     if (CE->isCast())
11867       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11868         return Res;
11869
11870   
11871   // If this store is the last instruction in the basic block (possibly
11872   // excepting debug info instructions and the pointer bitcasts that feed
11873   // into them), and if the block ends with an unconditional branch, try
11874   // to move it to the successor block.
11875   BBI = &SI; 
11876   do {
11877     ++BBI;
11878   } while (isa<DbgInfoIntrinsic>(BBI) ||
11879            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11880   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11881     if (BI->isUnconditional())
11882       if (SimplifyStoreAtEndOfBlock(SI))
11883         return 0;  // xform done!
11884   
11885   return 0;
11886 }
11887
11888 /// SimplifyStoreAtEndOfBlock - Turn things like:
11889 ///   if () { *P = v1; } else { *P = v2 }
11890 /// into a phi node with a store in the successor.
11891 ///
11892 /// Simplify things like:
11893 ///   *P = v1; if () { *P = v2; }
11894 /// into a phi node with a store in the successor.
11895 ///
11896 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11897   BasicBlock *StoreBB = SI.getParent();
11898   
11899   // Check to see if the successor block has exactly two incoming edges.  If
11900   // so, see if the other predecessor contains a store to the same location.
11901   // if so, insert a PHI node (if needed) and move the stores down.
11902   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11903   
11904   // Determine whether Dest has exactly two predecessors and, if so, compute
11905   // the other predecessor.
11906   pred_iterator PI = pred_begin(DestBB);
11907   BasicBlock *OtherBB = 0;
11908   if (*PI != StoreBB)
11909     OtherBB = *PI;
11910   ++PI;
11911   if (PI == pred_end(DestBB))
11912     return false;
11913   
11914   if (*PI != StoreBB) {
11915     if (OtherBB)
11916       return false;
11917     OtherBB = *PI;
11918   }
11919   if (++PI != pred_end(DestBB))
11920     return false;
11921
11922   // Bail out if all the relevant blocks aren't distinct (this can happen,
11923   // for example, if SI is in an infinite loop)
11924   if (StoreBB == DestBB || OtherBB == DestBB)
11925     return false;
11926
11927   // Verify that the other block ends in a branch and is not otherwise empty.
11928   BasicBlock::iterator BBI = OtherBB->getTerminator();
11929   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11930   if (!OtherBr || BBI == OtherBB->begin())
11931     return false;
11932   
11933   // If the other block ends in an unconditional branch, check for the 'if then
11934   // else' case.  there is an instruction before the branch.
11935   StoreInst *OtherStore = 0;
11936   if (OtherBr->isUnconditional()) {
11937     --BBI;
11938     // Skip over debugging info.
11939     while (isa<DbgInfoIntrinsic>(BBI) ||
11940            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11941       if (BBI==OtherBB->begin())
11942         return false;
11943       --BBI;
11944     }
11945     // If this isn't a store, or isn't a store to the same location, bail out.
11946     OtherStore = dyn_cast<StoreInst>(BBI);
11947     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11948       return false;
11949   } else {
11950     // Otherwise, the other block ended with a conditional branch. If one of the
11951     // destinations is StoreBB, then we have the if/then case.
11952     if (OtherBr->getSuccessor(0) != StoreBB && 
11953         OtherBr->getSuccessor(1) != StoreBB)
11954       return false;
11955     
11956     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11957     // if/then triangle.  See if there is a store to the same ptr as SI that
11958     // lives in OtherBB.
11959     for (;; --BBI) {
11960       // Check to see if we find the matching store.
11961       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11962         if (OtherStore->getOperand(1) != SI.getOperand(1))
11963           return false;
11964         break;
11965       }
11966       // If we find something that may be using or overwriting the stored
11967       // value, or if we run out of instructions, we can't do the xform.
11968       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11969           BBI == OtherBB->begin())
11970         return false;
11971     }
11972     
11973     // In order to eliminate the store in OtherBr, we have to
11974     // make sure nothing reads or overwrites the stored value in
11975     // StoreBB.
11976     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11977       // FIXME: This should really be AA driven.
11978       if (I->mayReadFromMemory() || I->mayWriteToMemory())
11979         return false;
11980     }
11981   }
11982   
11983   // Insert a PHI node now if we need it.
11984   Value *MergedVal = OtherStore->getOperand(0);
11985   if (MergedVal != SI.getOperand(0)) {
11986     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11987     PN->reserveOperandSpace(2);
11988     PN->addIncoming(SI.getOperand(0), SI.getParent());
11989     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11990     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11991   }
11992   
11993   // Advance to a place where it is safe to insert the new store and
11994   // insert it.
11995   BBI = DestBB->getFirstNonPHI();
11996   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11997                                     OtherStore->isVolatile()), *BBI);
11998   
11999   // Nuke the old stores.
12000   EraseInstFromFunction(SI);
12001   EraseInstFromFunction(*OtherStore);
12002   ++NumCombined;
12003   return true;
12004 }
12005
12006
12007 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12008   // Change br (not X), label True, label False to: br X, label False, True
12009   Value *X = 0;
12010   BasicBlock *TrueDest;
12011   BasicBlock *FalseDest;
12012   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
12013       !isa<Constant>(X)) {
12014     // Swap Destinations and condition...
12015     BI.setCondition(X);
12016     BI.setSuccessor(0, FalseDest);
12017     BI.setSuccessor(1, TrueDest);
12018     return &BI;
12019   }
12020
12021   // Cannonicalize fcmp_one -> fcmp_oeq
12022   FCmpInst::Predicate FPred; Value *Y;
12023   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
12024                              TrueDest, FalseDest)))
12025     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12026          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12027       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12028       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
12029       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
12030       NewSCC->takeName(I);
12031       // Swap Destinations and condition...
12032       BI.setCondition(NewSCC);
12033       BI.setSuccessor(0, FalseDest);
12034       BI.setSuccessor(1, TrueDest);
12035       RemoveFromWorkList(I);
12036       I->eraseFromParent();
12037       AddToWorkList(NewSCC);
12038       return &BI;
12039     }
12040
12041   // Cannonicalize icmp_ne -> icmp_eq
12042   ICmpInst::Predicate IPred;
12043   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12044                       TrueDest, FalseDest)))
12045     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12046          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12047          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12048       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12049       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
12050       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
12051       NewSCC->takeName(I);
12052       // Swap Destinations and condition...
12053       BI.setCondition(NewSCC);
12054       BI.setSuccessor(0, FalseDest);
12055       BI.setSuccessor(1, TrueDest);
12056       RemoveFromWorkList(I);
12057       I->eraseFromParent();;
12058       AddToWorkList(NewSCC);
12059       return &BI;
12060     }
12061
12062   return 0;
12063 }
12064
12065 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12066   Value *Cond = SI.getCondition();
12067   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12068     if (I->getOpcode() == Instruction::Add)
12069       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12070         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12071         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12072           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
12073                                                 AddRHS));
12074         SI.setOperand(0, I->getOperand(0));
12075         AddToWorkList(I);
12076         return &SI;
12077       }
12078   }
12079   return 0;
12080 }
12081
12082 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12083   Value *Agg = EV.getAggregateOperand();
12084
12085   if (!EV.hasIndices())
12086     return ReplaceInstUsesWith(EV, Agg);
12087
12088   if (Constant *C = dyn_cast<Constant>(Agg)) {
12089     if (isa<UndefValue>(C))
12090       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12091       
12092     if (isa<ConstantAggregateZero>(C))
12093       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12094
12095     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12096       // Extract the element indexed by the first index out of the constant
12097       Value *V = C->getOperand(*EV.idx_begin());
12098       if (EV.getNumIndices() > 1)
12099         // Extract the remaining indices out of the constant indexed by the
12100         // first index
12101         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12102       else
12103         return ReplaceInstUsesWith(EV, V);
12104     }
12105     return 0; // Can't handle other constants
12106   } 
12107   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12108     // We're extracting from an insertvalue instruction, compare the indices
12109     const unsigned *exti, *exte, *insi, *inse;
12110     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12111          exte = EV.idx_end(), inse = IV->idx_end();
12112          exti != exte && insi != inse;
12113          ++exti, ++insi) {
12114       if (*insi != *exti)
12115         // The insert and extract both reference distinctly different elements.
12116         // This means the extract is not influenced by the insert, and we can
12117         // replace the aggregate operand of the extract with the aggregate
12118         // operand of the insert. i.e., replace
12119         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12120         // %E = extractvalue { i32, { i32 } } %I, 0
12121         // with
12122         // %E = extractvalue { i32, { i32 } } %A, 0
12123         return ExtractValueInst::Create(IV->getAggregateOperand(),
12124                                         EV.idx_begin(), EV.idx_end());
12125     }
12126     if (exti == exte && insi == inse)
12127       // Both iterators are at the end: Index lists are identical. Replace
12128       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12129       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12130       // with "i32 42"
12131       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12132     if (exti == exte) {
12133       // The extract list is a prefix of the insert list. i.e. replace
12134       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12135       // %E = extractvalue { i32, { i32 } } %I, 1
12136       // with
12137       // %X = extractvalue { i32, { i32 } } %A, 1
12138       // %E = insertvalue { i32 } %X, i32 42, 0
12139       // by switching the order of the insert and extract (though the
12140       // insertvalue should be left in, since it may have other uses).
12141       Value *NewEV = InsertNewInstBefore(
12142         ExtractValueInst::Create(IV->getAggregateOperand(),
12143                                  EV.idx_begin(), EV.idx_end()),
12144         EV);
12145       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12146                                      insi, inse);
12147     }
12148     if (insi == inse)
12149       // The insert list is a prefix of the extract list
12150       // We can simply remove the common indices from the extract and make it
12151       // operate on the inserted value instead of the insertvalue result.
12152       // i.e., replace
12153       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12154       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12155       // with
12156       // %E extractvalue { i32 } { i32 42 }, 0
12157       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12158                                       exti, exte);
12159   }
12160   // Can't simplify extracts from other values. Note that nested extracts are
12161   // already simplified implicitely by the above (extract ( extract (insert) )
12162   // will be translated into extract ( insert ( extract ) ) first and then just
12163   // the value inserted, if appropriate).
12164   return 0;
12165 }
12166
12167 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12168 /// is to leave as a vector operation.
12169 static bool CheapToScalarize(Value *V, bool isConstant) {
12170   if (isa<ConstantAggregateZero>(V)) 
12171     return true;
12172   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12173     if (isConstant) return true;
12174     // If all elts are the same, we can extract.
12175     Constant *Op0 = C->getOperand(0);
12176     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12177       if (C->getOperand(i) != Op0)
12178         return false;
12179     return true;
12180   }
12181   Instruction *I = dyn_cast<Instruction>(V);
12182   if (!I) return false;
12183   
12184   // Insert element gets simplified to the inserted element or is deleted if
12185   // this is constant idx extract element and its a constant idx insertelt.
12186   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12187       isa<ConstantInt>(I->getOperand(2)))
12188     return true;
12189   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12190     return true;
12191   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12192     if (BO->hasOneUse() &&
12193         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12194          CheapToScalarize(BO->getOperand(1), isConstant)))
12195       return true;
12196   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12197     if (CI->hasOneUse() &&
12198         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12199          CheapToScalarize(CI->getOperand(1), isConstant)))
12200       return true;
12201   
12202   return false;
12203 }
12204
12205 /// Read and decode a shufflevector mask.
12206 ///
12207 /// It turns undef elements into values that are larger than the number of
12208 /// elements in the input.
12209 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12210   unsigned NElts = SVI->getType()->getNumElements();
12211   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12212     return std::vector<unsigned>(NElts, 0);
12213   if (isa<UndefValue>(SVI->getOperand(2)))
12214     return std::vector<unsigned>(NElts, 2*NElts);
12215
12216   std::vector<unsigned> Result;
12217   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12218   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12219     if (isa<UndefValue>(*i))
12220       Result.push_back(NElts*2);  // undef -> 8
12221     else
12222       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12223   return Result;
12224 }
12225
12226 /// FindScalarElement - Given a vector and an element number, see if the scalar
12227 /// value is already around as a register, for example if it were inserted then
12228 /// extracted from the vector.
12229 static Value *FindScalarElement(Value *V, unsigned EltNo) {
12230   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12231   const VectorType *PTy = cast<VectorType>(V->getType());
12232   unsigned Width = PTy->getNumElements();
12233   if (EltNo >= Width)  // Out of range access.
12234     return UndefValue::get(PTy->getElementType());
12235   
12236   if (isa<UndefValue>(V))
12237     return UndefValue::get(PTy->getElementType());
12238   else if (isa<ConstantAggregateZero>(V))
12239     return Constant::getNullValue(PTy->getElementType());
12240   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12241     return CP->getOperand(EltNo);
12242   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12243     // If this is an insert to a variable element, we don't know what it is.
12244     if (!isa<ConstantInt>(III->getOperand(2))) 
12245       return 0;
12246     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12247     
12248     // If this is an insert to the element we are looking for, return the
12249     // inserted value.
12250     if (EltNo == IIElt) 
12251       return III->getOperand(1);
12252     
12253     // Otherwise, the insertelement doesn't modify the value, recurse on its
12254     // vector input.
12255     return FindScalarElement(III->getOperand(0), EltNo);
12256   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12257     unsigned LHSWidth =
12258       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12259     unsigned InEl = getShuffleMask(SVI)[EltNo];
12260     if (InEl < LHSWidth)
12261       return FindScalarElement(SVI->getOperand(0), InEl);
12262     else if (InEl < LHSWidth*2)
12263       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
12264     else
12265       return UndefValue::get(PTy->getElementType());
12266   }
12267   
12268   // Otherwise, we don't know.
12269   return 0;
12270 }
12271
12272 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12273   // If vector val is undef, replace extract with scalar undef.
12274   if (isa<UndefValue>(EI.getOperand(0)))
12275     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12276
12277   // If vector val is constant 0, replace extract with scalar 0.
12278   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12279     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12280   
12281   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12282     // If vector val is constant with all elements the same, replace EI with
12283     // that element. When the elements are not identical, we cannot replace yet
12284     // (we do that below, but only when the index is constant).
12285     Constant *op0 = C->getOperand(0);
12286     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12287       if (C->getOperand(i) != op0) {
12288         op0 = 0; 
12289         break;
12290       }
12291     if (op0)
12292       return ReplaceInstUsesWith(EI, op0);
12293   }
12294   
12295   // If extracting a specified index from the vector, see if we can recursively
12296   // find a previously computed scalar that was inserted into the vector.
12297   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12298     unsigned IndexVal = IdxC->getZExtValue();
12299     unsigned VectorWidth = 
12300       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12301       
12302     // If this is extracting an invalid index, turn this into undef, to avoid
12303     // crashing the code below.
12304     if (IndexVal >= VectorWidth)
12305       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12306     
12307     // This instruction only demands the single element from the input vector.
12308     // If the input vector has a single use, simplify it based on this use
12309     // property.
12310     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12311       APInt UndefElts(VectorWidth, 0);
12312       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12313       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12314                                                 DemandedMask, UndefElts)) {
12315         EI.setOperand(0, V);
12316         return &EI;
12317       }
12318     }
12319     
12320     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
12321       return ReplaceInstUsesWith(EI, Elt);
12322     
12323     // If the this extractelement is directly using a bitcast from a vector of
12324     // the same number of elements, see if we can find the source element from
12325     // it.  In this case, we will end up needing to bitcast the scalars.
12326     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12327       if (const VectorType *VT = 
12328               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12329         if (VT->getNumElements() == VectorWidth)
12330           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
12331             return new BitCastInst(Elt, EI.getType());
12332     }
12333   }
12334   
12335   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12336     if (I->hasOneUse()) {
12337       // Push extractelement into predecessor operation if legal and
12338       // profitable to do so
12339       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12340         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12341         if (CheapToScalarize(BO, isConstantElt)) {
12342           ExtractElementInst *newEI0 = 
12343             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12344                                    EI.getName()+".lhs");
12345           ExtractElementInst *newEI1 =
12346             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12347                                    EI.getName()+".rhs");
12348           InsertNewInstBefore(newEI0, EI);
12349           InsertNewInstBefore(newEI1, EI);
12350           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12351         }
12352       } else if (isa<LoadInst>(I)) {
12353         unsigned AS = 
12354           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12355         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12356                                          PointerType::get(EI.getType(), AS),EI);
12357         GetElementPtrInst *GEP =
12358           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12359         InsertNewInstBefore(GEP, EI);
12360         return new LoadInst(GEP);
12361       }
12362     }
12363     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12364       // Extracting the inserted element?
12365       if (IE->getOperand(2) == EI.getOperand(1))
12366         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12367       // If the inserted and extracted elements are constants, they must not
12368       // be the same value, extract from the pre-inserted value instead.
12369       if (isa<Constant>(IE->getOperand(2)) &&
12370           isa<Constant>(EI.getOperand(1))) {
12371         AddUsesToWorkList(EI);
12372         EI.setOperand(0, IE->getOperand(0));
12373         return &EI;
12374       }
12375     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12376       // If this is extracting an element from a shufflevector, figure out where
12377       // it came from and extract from the appropriate input element instead.
12378       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12379         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12380         Value *Src;
12381         unsigned LHSWidth =
12382           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12383
12384         if (SrcIdx < LHSWidth)
12385           Src = SVI->getOperand(0);
12386         else if (SrcIdx < LHSWidth*2) {
12387           SrcIdx -= LHSWidth;
12388           Src = SVI->getOperand(1);
12389         } else {
12390           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12391         }
12392         return new ExtractElementInst(Src, SrcIdx);
12393       }
12394     }
12395   }
12396   return 0;
12397 }
12398
12399 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12400 /// elements from either LHS or RHS, return the shuffle mask and true. 
12401 /// Otherwise, return false.
12402 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12403                                          std::vector<Constant*> &Mask) {
12404   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12405          "Invalid CollectSingleShuffleElements");
12406   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12407
12408   if (isa<UndefValue>(V)) {
12409     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12410     return true;
12411   } else if (V == LHS) {
12412     for (unsigned i = 0; i != NumElts; ++i)
12413       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12414     return true;
12415   } else if (V == RHS) {
12416     for (unsigned i = 0; i != NumElts; ++i)
12417       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
12418     return true;
12419   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12420     // If this is an insert of an extract from some other vector, include it.
12421     Value *VecOp    = IEI->getOperand(0);
12422     Value *ScalarOp = IEI->getOperand(1);
12423     Value *IdxOp    = IEI->getOperand(2);
12424     
12425     if (!isa<ConstantInt>(IdxOp))
12426       return false;
12427     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12428     
12429     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12430       // Okay, we can handle this if the vector we are insertinting into is
12431       // transitively ok.
12432       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12433         // If so, update the mask to reflect the inserted undef.
12434         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
12435         return true;
12436       }      
12437     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12438       if (isa<ConstantInt>(EI->getOperand(1)) &&
12439           EI->getOperand(0)->getType() == V->getType()) {
12440         unsigned ExtractedIdx =
12441           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12442         
12443         // This must be extracting from either LHS or RHS.
12444         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12445           // Okay, we can handle this if the vector we are insertinting into is
12446           // transitively ok.
12447           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12448             // If so, update the mask to reflect the inserted value.
12449             if (EI->getOperand(0) == LHS) {
12450               Mask[InsertedIdx % NumElts] = 
12451                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12452             } else {
12453               assert(EI->getOperand(0) == RHS);
12454               Mask[InsertedIdx % NumElts] = 
12455                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
12456               
12457             }
12458             return true;
12459           }
12460         }
12461       }
12462     }
12463   }
12464   // TODO: Handle shufflevector here!
12465   
12466   return false;
12467 }
12468
12469 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12470 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12471 /// that computes V and the LHS value of the shuffle.
12472 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12473                                      Value *&RHS) {
12474   assert(isa<VectorType>(V->getType()) && 
12475          (RHS == 0 || V->getType() == RHS->getType()) &&
12476          "Invalid shuffle!");
12477   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12478
12479   if (isa<UndefValue>(V)) {
12480     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12481     return V;
12482   } else if (isa<ConstantAggregateZero>(V)) {
12483     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
12484     return V;
12485   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12486     // If this is an insert of an extract from some other vector, include it.
12487     Value *VecOp    = IEI->getOperand(0);
12488     Value *ScalarOp = IEI->getOperand(1);
12489     Value *IdxOp    = IEI->getOperand(2);
12490     
12491     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12492       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12493           EI->getOperand(0)->getType() == V->getType()) {
12494         unsigned ExtractedIdx =
12495           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12496         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12497         
12498         // Either the extracted from or inserted into vector must be RHSVec,
12499         // otherwise we'd end up with a shuffle of three inputs.
12500         if (EI->getOperand(0) == RHS || RHS == 0) {
12501           RHS = EI->getOperand(0);
12502           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
12503           Mask[InsertedIdx % NumElts] = 
12504             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
12505           return V;
12506         }
12507         
12508         if (VecOp == RHS) {
12509           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
12510           // Everything but the extracted element is replaced with the RHS.
12511           for (unsigned i = 0; i != NumElts; ++i) {
12512             if (i != InsertedIdx)
12513               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
12514           }
12515           return V;
12516         }
12517         
12518         // If this insertelement is a chain that comes from exactly these two
12519         // vectors, return the vector and the effective shuffle.
12520         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
12521           return EI->getOperand(0);
12522         
12523       }
12524     }
12525   }
12526   // TODO: Handle shufflevector here!
12527   
12528   // Otherwise, can't do anything fancy.  Return an identity vector.
12529   for (unsigned i = 0; i != NumElts; ++i)
12530     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12531   return V;
12532 }
12533
12534 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12535   Value *VecOp    = IE.getOperand(0);
12536   Value *ScalarOp = IE.getOperand(1);
12537   Value *IdxOp    = IE.getOperand(2);
12538   
12539   // Inserting an undef or into an undefined place, remove this.
12540   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12541     ReplaceInstUsesWith(IE, VecOp);
12542   
12543   // If the inserted element was extracted from some other vector, and if the 
12544   // indexes are constant, try to turn this into a shufflevector operation.
12545   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12546     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12547         EI->getOperand(0)->getType() == IE.getType()) {
12548       unsigned NumVectorElts = IE.getType()->getNumElements();
12549       unsigned ExtractedIdx =
12550         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12551       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12552       
12553       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12554         return ReplaceInstUsesWith(IE, VecOp);
12555       
12556       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12557         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12558       
12559       // If we are extracting a value from a vector, then inserting it right
12560       // back into the same place, just use the input vector.
12561       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12562         return ReplaceInstUsesWith(IE, VecOp);      
12563       
12564       // We could theoretically do this for ANY input.  However, doing so could
12565       // turn chains of insertelement instructions into a chain of shufflevector
12566       // instructions, and right now we do not merge shufflevectors.  As such,
12567       // only do this in a situation where it is clear that there is benefit.
12568       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12569         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12570         // the values of VecOp, except then one read from EIOp0.
12571         // Build a new shuffle mask.
12572         std::vector<Constant*> Mask;
12573         if (isa<UndefValue>(VecOp))
12574           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
12575         else {
12576           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12577           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
12578                                                        NumVectorElts));
12579         } 
12580         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12581         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12582                                      ConstantVector::get(Mask));
12583       }
12584       
12585       // If this insertelement isn't used by some other insertelement, turn it
12586       // (and any insertelements it points to), into one big shuffle.
12587       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12588         std::vector<Constant*> Mask;
12589         Value *RHS = 0;
12590         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12591         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12592         // We now have a shuffle of LHS, RHS, Mask.
12593         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
12594       }
12595     }
12596   }
12597
12598   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12599   APInt UndefElts(VWidth, 0);
12600   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12601   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12602     return &IE;
12603
12604   return 0;
12605 }
12606
12607
12608 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12609   Value *LHS = SVI.getOperand(0);
12610   Value *RHS = SVI.getOperand(1);
12611   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12612
12613   bool MadeChange = false;
12614
12615   // Undefined shuffle mask -> undefined value.
12616   if (isa<UndefValue>(SVI.getOperand(2)))
12617     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12618
12619   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12620
12621   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12622     return 0;
12623
12624   APInt UndefElts(VWidth, 0);
12625   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12626   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12627     LHS = SVI.getOperand(0);
12628     RHS = SVI.getOperand(1);
12629     MadeChange = true;
12630   }
12631   
12632   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12633   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12634   if (LHS == RHS || isa<UndefValue>(LHS)) {
12635     if (isa<UndefValue>(LHS) && LHS == RHS) {
12636       // shuffle(undef,undef,mask) -> undef.
12637       return ReplaceInstUsesWith(SVI, LHS);
12638     }
12639     
12640     // Remap any references to RHS to use LHS.
12641     std::vector<Constant*> Elts;
12642     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12643       if (Mask[i] >= 2*e)
12644         Elts.push_back(UndefValue::get(Type::Int32Ty));
12645       else {
12646         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12647             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12648           Mask[i] = 2*e;     // Turn into undef.
12649           Elts.push_back(UndefValue::get(Type::Int32Ty));
12650         } else {
12651           Mask[i] = Mask[i] % e;  // Force to LHS.
12652           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12653         }
12654       }
12655     }
12656     SVI.setOperand(0, SVI.getOperand(1));
12657     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12658     SVI.setOperand(2, ConstantVector::get(Elts));
12659     LHS = SVI.getOperand(0);
12660     RHS = SVI.getOperand(1);
12661     MadeChange = true;
12662   }
12663   
12664   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12665   bool isLHSID = true, isRHSID = true;
12666     
12667   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12668     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12669     // Is this an identity shuffle of the LHS value?
12670     isLHSID &= (Mask[i] == i);
12671       
12672     // Is this an identity shuffle of the RHS value?
12673     isRHSID &= (Mask[i]-e == i);
12674   }
12675
12676   // Eliminate identity shuffles.
12677   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12678   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12679   
12680   // If the LHS is a shufflevector itself, see if we can combine it with this
12681   // one without producing an unusual shuffle.  Here we are really conservative:
12682   // we are absolutely afraid of producing a shuffle mask not in the input
12683   // program, because the code gen may not be smart enough to turn a merged
12684   // shuffle into two specific shuffles: it may produce worse code.  As such,
12685   // we only merge two shuffles if the result is one of the two input shuffle
12686   // masks.  In this case, merging the shuffles just removes one instruction,
12687   // which we know is safe.  This is good for things like turning:
12688   // (splat(splat)) -> splat.
12689   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12690     if (isa<UndefValue>(RHS)) {
12691       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12692
12693       std::vector<unsigned> NewMask;
12694       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12695         if (Mask[i] >= 2*e)
12696           NewMask.push_back(2*e);
12697         else
12698           NewMask.push_back(LHSMask[Mask[i]]);
12699       
12700       // If the result mask is equal to the src shuffle or this shuffle mask, do
12701       // the replacement.
12702       if (NewMask == LHSMask || NewMask == Mask) {
12703         unsigned LHSInNElts =
12704           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12705         std::vector<Constant*> Elts;
12706         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12707           if (NewMask[i] >= LHSInNElts*2) {
12708             Elts.push_back(UndefValue::get(Type::Int32Ty));
12709           } else {
12710             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
12711           }
12712         }
12713         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12714                                      LHSSVI->getOperand(1),
12715                                      ConstantVector::get(Elts));
12716       }
12717     }
12718   }
12719
12720   return MadeChange ? &SVI : 0;
12721 }
12722
12723
12724
12725
12726 /// TryToSinkInstruction - Try to move the specified instruction from its
12727 /// current block into the beginning of DestBlock, which can only happen if it's
12728 /// safe to move the instruction past all of the instructions between it and the
12729 /// end of its block.
12730 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12731   assert(I->hasOneUse() && "Invariants didn't hold!");
12732
12733   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12734   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12735     return false;
12736
12737   // Do not sink alloca instructions out of the entry block.
12738   if (isa<AllocaInst>(I) && I->getParent() ==
12739         &DestBlock->getParent()->getEntryBlock())
12740     return false;
12741
12742   // We can only sink load instructions if there is nothing between the load and
12743   // the end of block that could change the value.
12744   if (I->mayReadFromMemory()) {
12745     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12746          Scan != E; ++Scan)
12747       if (Scan->mayWriteToMemory())
12748         return false;
12749   }
12750
12751   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12752
12753   CopyPrecedingStopPoint(I, InsertPos);
12754   I->moveBefore(InsertPos);
12755   ++NumSunkInst;
12756   return true;
12757 }
12758
12759
12760 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12761 /// all reachable code to the worklist.
12762 ///
12763 /// This has a couple of tricks to make the code faster and more powerful.  In
12764 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12765 /// them to the worklist (this significantly speeds up instcombine on code where
12766 /// many instructions are dead or constant).  Additionally, if we find a branch
12767 /// whose condition is a known constant, we only visit the reachable successors.
12768 ///
12769 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12770                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12771                                        InstCombiner &IC,
12772                                        const TargetData *TD) {
12773   SmallVector<BasicBlock*, 256> Worklist;
12774   Worklist.push_back(BB);
12775
12776   while (!Worklist.empty()) {
12777     BB = Worklist.back();
12778     Worklist.pop_back();
12779     
12780     // We have now visited this block!  If we've already been here, ignore it.
12781     if (!Visited.insert(BB)) continue;
12782
12783     DbgInfoIntrinsic *DBI_Prev = NULL;
12784     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12785       Instruction *Inst = BBI++;
12786       
12787       // DCE instruction if trivially dead.
12788       if (isInstructionTriviallyDead(Inst)) {
12789         ++NumDeadInst;
12790         DOUT << "IC: DCE: " << *Inst;
12791         Inst->eraseFromParent();
12792         continue;
12793       }
12794       
12795       // ConstantProp instruction if trivially constant.
12796       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12797         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12798         Inst->replaceAllUsesWith(C);
12799         ++NumConstProp;
12800         Inst->eraseFromParent();
12801         continue;
12802       }
12803      
12804       // If there are two consecutive llvm.dbg.stoppoint calls then
12805       // it is likely that the optimizer deleted code in between these
12806       // two intrinsics. 
12807       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12808       if (DBI_Next) {
12809         if (DBI_Prev
12810             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12811             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12812           IC.RemoveFromWorkList(DBI_Prev);
12813           DBI_Prev->eraseFromParent();
12814         }
12815         DBI_Prev = DBI_Next;
12816       } else {
12817         DBI_Prev = 0;
12818       }
12819
12820       IC.AddToWorkList(Inst);
12821     }
12822
12823     // Recursively visit successors.  If this is a branch or switch on a
12824     // constant, only visit the reachable successor.
12825     TerminatorInst *TI = BB->getTerminator();
12826     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12827       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12828         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12829         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12830         Worklist.push_back(ReachableBB);
12831         continue;
12832       }
12833     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12834       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12835         // See if this is an explicit destination.
12836         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12837           if (SI->getCaseValue(i) == Cond) {
12838             BasicBlock *ReachableBB = SI->getSuccessor(i);
12839             Worklist.push_back(ReachableBB);
12840             continue;
12841           }
12842         
12843         // Otherwise it is the default destination.
12844         Worklist.push_back(SI->getSuccessor(0));
12845         continue;
12846       }
12847     }
12848     
12849     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12850       Worklist.push_back(TI->getSuccessor(i));
12851   }
12852 }
12853
12854 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12855   bool Changed = false;
12856   TD = &getAnalysis<TargetData>();
12857   
12858   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12859              << F.getNameStr() << "\n");
12860
12861   {
12862     // Do a depth-first traversal of the function, populate the worklist with
12863     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12864     // track of which blocks we visit.
12865     SmallPtrSet<BasicBlock*, 64> Visited;
12866     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12867
12868     // Do a quick scan over the function.  If we find any blocks that are
12869     // unreachable, remove any instructions inside of them.  This prevents
12870     // the instcombine code from having to deal with some bad special cases.
12871     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12872       if (!Visited.count(BB)) {
12873         Instruction *Term = BB->getTerminator();
12874         while (Term != BB->begin()) {   // Remove instrs bottom-up
12875           BasicBlock::iterator I = Term; --I;
12876
12877           DOUT << "IC: DCE: " << *I;
12878           // A debug intrinsic shouldn't force another iteration if we weren't
12879           // going to do one without it.
12880           if (!isa<DbgInfoIntrinsic>(I)) {
12881             ++NumDeadInst;
12882             Changed = true;
12883           }
12884           if (!I->use_empty())
12885             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12886           I->eraseFromParent();
12887         }
12888       }
12889   }
12890
12891   while (!Worklist.empty()) {
12892     Instruction *I = RemoveOneFromWorkList();
12893     if (I == 0) continue;  // skip null values.
12894
12895     // Check to see if we can DCE the instruction.
12896     if (isInstructionTriviallyDead(I)) {
12897       // Add operands to the worklist.
12898       if (I->getNumOperands() < 4)
12899         AddUsesToWorkList(*I);
12900       ++NumDeadInst;
12901
12902       DOUT << "IC: DCE: " << *I;
12903
12904       I->eraseFromParent();
12905       RemoveFromWorkList(I);
12906       Changed = true;
12907       continue;
12908     }
12909
12910     // Instruction isn't dead, see if we can constant propagate it.
12911     if (Constant *C = ConstantFoldInstruction(I, TD)) {
12912       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12913
12914       // Add operands to the worklist.
12915       AddUsesToWorkList(*I);
12916       ReplaceInstUsesWith(*I, C);
12917
12918       ++NumConstProp;
12919       I->eraseFromParent();
12920       RemoveFromWorkList(I);
12921       Changed = true;
12922       continue;
12923     }
12924
12925     if (TD &&
12926         (I->getType()->getTypeID() == Type::VoidTyID ||
12927          I->isTrapping())) {
12928       // See if we can constant fold its operands.
12929       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12930         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
12931           if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
12932             if (NewC != CE) {
12933               i->set(NewC);
12934               Changed = true;
12935             }
12936     }
12937
12938     // See if we can trivially sink this instruction to a successor basic block.
12939     if (I->hasOneUse()) {
12940       BasicBlock *BB = I->getParent();
12941       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12942       if (UserParent != BB) {
12943         bool UserIsSuccessor = false;
12944         // See if the user is one of our successors.
12945         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12946           if (*SI == UserParent) {
12947             UserIsSuccessor = true;
12948             break;
12949           }
12950
12951         // If the user is one of our immediate successors, and if that successor
12952         // only has us as a predecessors (we'd have to split the critical edge
12953         // otherwise), we can keep going.
12954         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12955             next(pred_begin(UserParent)) == pred_end(UserParent))
12956           // Okay, the CFG is simple enough, try to sink this instruction.
12957           Changed |= TryToSinkInstruction(I, UserParent);
12958       }
12959     }
12960
12961     // Now that we have an instruction, try combining it to simplify it...
12962 #ifndef NDEBUG
12963     std::string OrigI;
12964 #endif
12965     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
12966     if (Instruction *Result = visit(*I)) {
12967       ++NumCombined;
12968       // Should we replace the old instruction with a new one?
12969       if (Result != I) {
12970         DOUT << "IC: Old = " << *I
12971              << "    New = " << *Result;
12972
12973         // Everything uses the new instruction now.
12974         I->replaceAllUsesWith(Result);
12975
12976         // Push the new instruction and any users onto the worklist.
12977         AddToWorkList(Result);
12978         AddUsersToWorkList(*Result);
12979
12980         // Move the name to the new instruction first.
12981         Result->takeName(I);
12982
12983         // Insert the new instruction into the basic block...
12984         BasicBlock *InstParent = I->getParent();
12985         BasicBlock::iterator InsertPos = I;
12986
12987         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
12988           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12989             ++InsertPos;
12990
12991         InstParent->getInstList().insert(InsertPos, Result);
12992
12993         // Make sure that we reprocess all operands now that we reduced their
12994         // use counts.
12995         AddUsesToWorkList(*I);
12996
12997         // Instructions can end up on the worklist more than once.  Make sure
12998         // we do not process an instruction that has been deleted.
12999         RemoveFromWorkList(I);
13000
13001         // Erase the old instruction.
13002         InstParent->getInstList().erase(I);
13003       } else {
13004 #ifndef NDEBUG
13005         DOUT << "IC: Mod = " << OrigI
13006              << "    New = " << *I;
13007 #endif
13008
13009         // If the instruction was modified, it's possible that it is now dead.
13010         // if so, remove it.
13011         if (isInstructionTriviallyDead(I)) {
13012           // Make sure we process all operands now that we are reducing their
13013           // use counts.
13014           AddUsesToWorkList(*I);
13015
13016           // Instructions may end up in the worklist more than once.  Erase all
13017           // occurrences of this instruction.
13018           RemoveFromWorkList(I);
13019           I->eraseFromParent();
13020         } else {
13021           AddToWorkList(I);
13022           AddUsersToWorkList(*I);
13023         }
13024       }
13025       Changed = true;
13026     }
13027   }
13028
13029   assert(WorklistMap.empty() && "Worklist empty, but map not?");
13030     
13031   // Do an explicit clear, this shrinks the map if needed.
13032   WorklistMap.clear();
13033   return Changed;
13034 }
13035
13036
13037 bool InstCombiner::runOnFunction(Function &F) {
13038   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13039   
13040   bool EverMadeChange = false;
13041
13042   // Iterate while there is work to do.
13043   unsigned Iteration = 0;
13044   while (DoOneIteration(F, Iteration++))
13045     EverMadeChange = true;
13046   return EverMadeChange;
13047 }
13048
13049 FunctionPass *llvm::createInstructionCombiningPass() {
13050   return new InstCombiner();
13051 }