fix a bug I introduced with my 'instcombine builder' refactoring
[oota-llvm.git] / lib / Transforms / Scalar / InstructionCombining.cpp
1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions.  This pass does not modify the CFG.  This pass is where
12 // algebraic simplification happens.
13 //
14 // This pass combines things like:
15 //    %Y = add i32 %X, 1
16 //    %Z = add i32 %Y, 1
17 // into:
18 //    %Z = add i32 %X, 2
19 //
20 // This is a simple worklist driven algorithm.
21 //
22 // This pass guarantees that the following canonicalizations are performed on
23 // the program:
24 //    1. If a binary operator has a constant operand, it is moved to the RHS
25 //    2. Bitwise operators with constant operands are always grouped so that
26 //       shifts are performed first, then or's, then and's, then xor's.
27 //    3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All cmp instructions on boolean values are replaced with logical ops
29 //    5. add X, X is represented as (X*2) => (X << 1)
30 //    6. Multiplies with a power-of-two constant argument are transformed into
31 //       shifts.
32 //   ... etc.
33 //
34 //===----------------------------------------------------------------------===//
35
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/LLVMContext.h"
40 #include "llvm/Pass.h"
41 #include "llvm/DerivedTypes.h"
42 #include "llvm/GlobalVariable.h"
43 #include "llvm/Operator.h"
44 #include "llvm/Analysis/ConstantFolding.h"
45 #include "llvm/Analysis/ValueTracking.h"
46 #include "llvm/Target/TargetData.h"
47 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
48 #include "llvm/Transforms/Utils/Local.h"
49 #include "llvm/Support/CallSite.h"
50 #include "llvm/Support/ConstantRange.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/GetElementPtrTypeIterator.h"
54 #include "llvm/Support/InstVisitor.h"
55 #include "llvm/Support/IRBuilder.h"
56 #include "llvm/Support/MathExtras.h"
57 #include "llvm/Support/PatternMatch.h"
58 #include "llvm/Support/Compiler.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include "llvm/ADT/DenseMap.h"
61 #include "llvm/ADT/SmallVector.h"
62 #include "llvm/ADT/SmallPtrSet.h"
63 #include "llvm/ADT/Statistic.h"
64 #include "llvm/ADT/STLExtras.h"
65 #include <algorithm>
66 #include <climits>
67 using namespace llvm;
68 using namespace llvm::PatternMatch;
69
70 STATISTIC(NumCombined , "Number of insts combined");
71 STATISTIC(NumConstProp, "Number of constant folds");
72 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
73 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
74 STATISTIC(NumSunkInst , "Number of instructions sunk");
75
76 namespace {
77   /// InstCombineWorklist - This is the worklist management logic for
78   /// InstCombine.
79   class InstCombineWorklist {
80     SmallVector<Instruction*, 256> Worklist;
81     DenseMap<Instruction*, unsigned> WorklistMap;
82     
83     void operator=(const InstCombineWorklist&RHS);   // DO NOT IMPLEMENT
84     InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
85   public:
86     InstCombineWorklist() {}
87     
88     bool isEmpty() const { return Worklist.empty(); }
89     
90     /// Add - Add the specified instruction to the worklist if it isn't already
91     /// in it.
92     void Add(Instruction *I) {
93       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
94         Worklist.push_back(I);
95     }
96     
97     void AddValue(Value *V) {
98       if (Instruction *I = dyn_cast<Instruction>(V))
99         Add(I);
100     }
101     
102     // Remove - remove I from the worklist if it exists.
103     void Remove(Instruction *I) {
104       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
105       if (It == WorklistMap.end()) return; // Not in worklist.
106       
107       // Don't bother moving everything down, just null out the slot.
108       Worklist[It->second] = 0;
109       
110       WorklistMap.erase(It);
111     }
112     
113     Instruction *RemoveOne() {
114       Instruction *I = Worklist.back();
115       Worklist.pop_back();
116       WorklistMap.erase(I);
117       return I;
118     }
119
120     /// AddUsersToWorkList - When an instruction is simplified, add all users of
121     /// the instruction to the work lists because they might get more simplified
122     /// now.
123     ///
124     void AddUsersToWorkList(Instruction &I) {
125       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
126            UI != UE; ++UI)
127         Add(cast<Instruction>(*UI));
128     }
129     
130     
131     /// Zap - check that the worklist is empty and nuke the backing store for
132     /// the map if it is large.
133     void Zap() {
134       assert(WorklistMap.empty() && "Worklist empty, but map not?");
135       
136       // Do an explicit clear, this shrinks the map if needed.
137       WorklistMap.clear();
138     }
139   };
140 } // end anonymous namespace.
141
142
143 namespace {
144   /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
145   /// just like the normal insertion helper, but also adds any new instructions
146   /// to the instcombine worklist.
147   class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
148     InstCombineWorklist &Worklist;
149   public:
150     InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
151     
152     void InsertHelper(Instruction *I, const Twine &Name,
153                       BasicBlock *BB, BasicBlock::iterator InsertPt) const {
154       IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
155       Worklist.Add(I);
156     }
157   };
158 } // end anonymous namespace
159
160
161 namespace {
162   class VISIBILITY_HIDDEN InstCombiner
163     : public FunctionPass,
164       public InstVisitor<InstCombiner, Instruction*> {
165     TargetData *TD;
166     bool MustPreserveLCSSA;
167   public:
168     /// Worklist - All of the instructions that need to be simplified.
169     InstCombineWorklist Worklist;
170
171     /// Builder - This is an IRBuilder that automatically inserts new
172     /// instructions into the worklist when they are created.
173     typedef IRBuilder<true, ConstantFolder, InstCombineIRInserter> BuilderTy;
174     BuilderTy *Builder;
175         
176     static char ID; // Pass identification, replacement for typeid
177     InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
178
179     LLVMContext *Context;
180     LLVMContext *getContext() const { return Context; }
181
182   public:
183     virtual bool runOnFunction(Function &F);
184     
185     bool DoOneIteration(Function &F, unsigned ItNum);
186
187     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
188       AU.addPreservedID(LCSSAID);
189       AU.setPreservesCFG();
190     }
191
192     TargetData *getTargetData() const { return TD; }
193
194     // Visitation implementation - Implement instruction combining for different
195     // instruction types.  The semantics are as follows:
196     // Return Value:
197     //    null        - No change was made
198     //     I          - Change was made, I is still valid, I may be dead though
199     //   otherwise    - Change was made, replace I with returned instruction
200     //
201     Instruction *visitAdd(BinaryOperator &I);
202     Instruction *visitFAdd(BinaryOperator &I);
203     Instruction *visitSub(BinaryOperator &I);
204     Instruction *visitFSub(BinaryOperator &I);
205     Instruction *visitMul(BinaryOperator &I);
206     Instruction *visitFMul(BinaryOperator &I);
207     Instruction *visitURem(BinaryOperator &I);
208     Instruction *visitSRem(BinaryOperator &I);
209     Instruction *visitFRem(BinaryOperator &I);
210     bool SimplifyDivRemOfSelect(BinaryOperator &I);
211     Instruction *commonRemTransforms(BinaryOperator &I);
212     Instruction *commonIRemTransforms(BinaryOperator &I);
213     Instruction *commonDivTransforms(BinaryOperator &I);
214     Instruction *commonIDivTransforms(BinaryOperator &I);
215     Instruction *visitUDiv(BinaryOperator &I);
216     Instruction *visitSDiv(BinaryOperator &I);
217     Instruction *visitFDiv(BinaryOperator &I);
218     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
219     Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
220     Instruction *visitAnd(BinaryOperator &I);
221     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
222     Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
223     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
224                                      Value *A, Value *B, Value *C);
225     Instruction *visitOr (BinaryOperator &I);
226     Instruction *visitXor(BinaryOperator &I);
227     Instruction *visitShl(BinaryOperator &I);
228     Instruction *visitAShr(BinaryOperator &I);
229     Instruction *visitLShr(BinaryOperator &I);
230     Instruction *commonShiftTransforms(BinaryOperator &I);
231     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
232                                       Constant *RHSC);
233     Instruction *visitFCmpInst(FCmpInst &I);
234     Instruction *visitICmpInst(ICmpInst &I);
235     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
236     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
237                                                 Instruction *LHS,
238                                                 ConstantInt *RHS);
239     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
240                                 ConstantInt *DivRHS);
241
242     Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
243                              ICmpInst::Predicate Cond, Instruction &I);
244     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
245                                      BinaryOperator &I);
246     Instruction *commonCastTransforms(CastInst &CI);
247     Instruction *commonIntCastTransforms(CastInst &CI);
248     Instruction *commonPointerCastTransforms(CastInst &CI);
249     Instruction *visitTrunc(TruncInst &CI);
250     Instruction *visitZExt(ZExtInst &CI);
251     Instruction *visitSExt(SExtInst &CI);
252     Instruction *visitFPTrunc(FPTruncInst &CI);
253     Instruction *visitFPExt(CastInst &CI);
254     Instruction *visitFPToUI(FPToUIInst &FI);
255     Instruction *visitFPToSI(FPToSIInst &FI);
256     Instruction *visitUIToFP(CastInst &CI);
257     Instruction *visitSIToFP(CastInst &CI);
258     Instruction *visitPtrToInt(PtrToIntInst &CI);
259     Instruction *visitIntToPtr(IntToPtrInst &CI);
260     Instruction *visitBitCast(BitCastInst &CI);
261     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
262                                 Instruction *FI);
263     Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
264     Instruction *visitSelectInst(SelectInst &SI);
265     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
266     Instruction *visitCallInst(CallInst &CI);
267     Instruction *visitInvokeInst(InvokeInst &II);
268     Instruction *visitPHINode(PHINode &PN);
269     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
270     Instruction *visitAllocationInst(AllocationInst &AI);
271     Instruction *visitFreeInst(FreeInst &FI);
272     Instruction *visitLoadInst(LoadInst &LI);
273     Instruction *visitStoreInst(StoreInst &SI);
274     Instruction *visitBranchInst(BranchInst &BI);
275     Instruction *visitSwitchInst(SwitchInst &SI);
276     Instruction *visitInsertElementInst(InsertElementInst &IE);
277     Instruction *visitExtractElementInst(ExtractElementInst &EI);
278     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
279     Instruction *visitExtractValueInst(ExtractValueInst &EV);
280
281     // visitInstruction - Specify what to return for unhandled instructions...
282     Instruction *visitInstruction(Instruction &I) { return 0; }
283
284   private:
285     Instruction *visitCallSite(CallSite CS);
286     bool transformConstExprCastCall(CallSite CS);
287     Instruction *transformCallThroughTrampoline(CallSite CS);
288     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
289                                    bool DoXform = true);
290     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
291     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
292
293
294   public:
295     // InsertNewInstBefore - insert an instruction New before instruction Old
296     // in the program.  Add the new instruction to the worklist.
297     //
298     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
299       assert(New && New->getParent() == 0 &&
300              "New instruction already inserted into a basic block!");
301       BasicBlock *BB = Old.getParent();
302       BB->getInstList().insert(&Old, New);  // Insert inst
303       Worklist.Add(New);
304       return New;
305     }
306         
307     // ReplaceInstUsesWith - This method is to be used when an instruction is
308     // found to be dead, replacable with another preexisting expression.  Here
309     // we add all uses of I to the worklist, replace all uses of I with the new
310     // value, then return I, so that the inst combiner will know that I was
311     // modified.
312     //
313     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
314       Worklist.AddUsersToWorkList(I);   // Add all modified instrs to worklist.
315       
316       // If we are replacing the instruction with itself, this must be in a
317       // segment of unreachable code, so just clobber the instruction.
318       if (&I == V) 
319         V = UndefValue::get(I.getType());
320         
321       I.replaceAllUsesWith(V);
322       return &I;
323     }
324
325     // EraseInstFromFunction - When dealing with an instruction that has side
326     // effects or produces a void value, we can't rely on DCE to delete the
327     // instruction.  Instead, visit methods should return the value returned by
328     // this function.
329     Instruction *EraseInstFromFunction(Instruction &I) {
330       assert(I.use_empty() && "Cannot erase instruction that is used!");
331       // Make sure that we reprocess all operands now that we reduced their
332       // use counts.
333       if (I.getNumOperands() < 8) {
334         for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
335           if (Instruction *Op = dyn_cast<Instruction>(*i))
336             Worklist.Add(Op);
337       }
338       Worklist.Remove(&I);
339       I.eraseFromParent();
340       return 0;  // Don't do anything with FI
341     }
342         
343     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
344                            APInt &KnownOne, unsigned Depth = 0) const {
345       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
346     }
347     
348     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
349                            unsigned Depth = 0) const {
350       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
351     }
352     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
353       return llvm::ComputeNumSignBits(Op, TD, Depth);
354     }
355
356   private:
357
358     /// SimplifyCommutative - This performs a few simplifications for 
359     /// commutative operators.
360     bool SimplifyCommutative(BinaryOperator &I);
361
362     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
363     /// most-complex to least-complex order.
364     bool SimplifyCompare(CmpInst &I);
365
366     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
367     /// based on the demanded bits.
368     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
369                                    APInt& KnownZero, APInt& KnownOne,
370                                    unsigned Depth);
371     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
372                               APInt& KnownZero, APInt& KnownOne,
373                               unsigned Depth=0);
374         
375     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
376     /// SimplifyDemandedBits knows about.  See if the instruction has any
377     /// properties that allow us to simplify its operands.
378     bool SimplifyDemandedInstructionBits(Instruction &Inst);
379         
380     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
381                                       APInt& UndefElts, unsigned Depth = 0);
382       
383     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
384     // PHI node as operand #0, see if we can fold the instruction into the PHI
385     // (which is only possible if all operands to the PHI are constants).
386     Instruction *FoldOpIntoPhi(Instruction &I);
387
388     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
389     // operator and they all are only used by the PHI, PHI together their
390     // inputs, and do the operation once, to the result of the PHI.
391     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
392     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
393     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
394
395     
396     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
397                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
398     
399     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
400                               bool isSub, Instruction &I);
401     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
402                                  bool isSigned, bool Inside, Instruction &IB);
403     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
404     Instruction *MatchBSwap(BinaryOperator &I);
405     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
406     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
407     Instruction *SimplifyMemSet(MemSetInst *MI);
408
409
410     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
411
412     bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
413                                     unsigned CastOpc, int &NumCastsRemoved);
414     unsigned GetOrEnforceKnownAlignment(Value *V,
415                                         unsigned PrefAlign = 0);
416
417   };
418 } // end anonymous namespace
419
420 char InstCombiner::ID = 0;
421 static RegisterPass<InstCombiner>
422 X("instcombine", "Combine redundant instructions");
423
424 // getComplexity:  Assign a complexity or rank value to LLVM Values...
425 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
426 static unsigned getComplexity(Value *V) {
427   if (isa<Instruction>(V)) {
428     if (BinaryOperator::isNeg(V) ||
429         BinaryOperator::isFNeg(V) ||
430         BinaryOperator::isNot(V))
431       return 3;
432     return 4;
433   }
434   if (isa<Argument>(V)) return 3;
435   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
436 }
437
438 // isOnlyUse - Return true if this instruction will be deleted if we stop using
439 // it.
440 static bool isOnlyUse(Value *V) {
441   return V->hasOneUse() || isa<Constant>(V);
442 }
443
444 // getPromotedType - Return the specified type promoted as it would be to pass
445 // though a va_arg area...
446 static const Type *getPromotedType(const Type *Ty) {
447   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
448     if (ITy->getBitWidth() < 32)
449       return Type::getInt32Ty(Ty->getContext());
450   }
451   return Ty;
452 }
453
454 /// getBitCastOperand - If the specified operand is a CastInst, a constant
455 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
456 /// operand value, otherwise return null.
457 static Value *getBitCastOperand(Value *V) {
458   if (Operator *O = dyn_cast<Operator>(V)) {
459     if (O->getOpcode() == Instruction::BitCast)
460       return O->getOperand(0);
461     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
462       if (GEP->hasAllZeroIndices())
463         return GEP->getPointerOperand();
464   }
465   return 0;
466 }
467
468 /// This function is a wrapper around CastInst::isEliminableCastPair. It
469 /// simply extracts arguments and returns what that function returns.
470 static Instruction::CastOps 
471 isEliminableCastPair(
472   const CastInst *CI, ///< The first cast instruction
473   unsigned opcode,       ///< The opcode of the second cast instruction
474   const Type *DstTy,     ///< The target type for the second cast instruction
475   TargetData *TD         ///< The target data for pointer size
476 ) {
477
478   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
479   const Type *MidTy = CI->getType();                  // B from above
480
481   // Get the opcodes of the two Cast instructions
482   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
483   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
484
485   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
486                                                 DstTy,
487                                   TD ? TD->getIntPtrType(CI->getContext()) : 0);
488   
489   // We don't want to form an inttoptr or ptrtoint that converts to an integer
490   // type that differs from the pointer size.
491   if ((Res == Instruction::IntToPtr &&
492           (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
493       (Res == Instruction::PtrToInt &&
494           (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
495     Res = 0;
496   
497   return Instruction::CastOps(Res);
498 }
499
500 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
501 /// in any code being generated.  It does not require codegen if V is simple
502 /// enough or if the cast can be folded into other casts.
503 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
504                               const Type *Ty, TargetData *TD) {
505   if (V->getType() == Ty || isa<Constant>(V)) return false;
506   
507   // If this is another cast that can be eliminated, it isn't codegen either.
508   if (const CastInst *CI = dyn_cast<CastInst>(V))
509     if (isEliminableCastPair(CI, opcode, Ty, TD))
510       return false;
511   return true;
512 }
513
514 // SimplifyCommutative - This performs a few simplifications for commutative
515 // operators:
516 //
517 //  1. Order operands such that they are listed from right (least complex) to
518 //     left (most complex).  This puts constants before unary operators before
519 //     binary operators.
520 //
521 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
522 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
523 //
524 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
525   bool Changed = false;
526   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
527     Changed = !I.swapOperands();
528
529   if (!I.isAssociative()) return Changed;
530   Instruction::BinaryOps Opcode = I.getOpcode();
531   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
532     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
533       if (isa<Constant>(I.getOperand(1))) {
534         Constant *Folded = ConstantExpr::get(I.getOpcode(),
535                                              cast<Constant>(I.getOperand(1)),
536                                              cast<Constant>(Op->getOperand(1)));
537         I.setOperand(0, Op->getOperand(0));
538         I.setOperand(1, Folded);
539         return true;
540       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
541         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
542             isOnlyUse(Op) && isOnlyUse(Op1)) {
543           Constant *C1 = cast<Constant>(Op->getOperand(1));
544           Constant *C2 = cast<Constant>(Op1->getOperand(1));
545
546           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
547           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
548           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
549                                                     Op1->getOperand(0),
550                                                     Op1->getName(), &I);
551           Worklist.Add(New);
552           I.setOperand(0, New);
553           I.setOperand(1, Folded);
554           return true;
555         }
556     }
557   return Changed;
558 }
559
560 /// SimplifyCompare - For a CmpInst this function just orders the operands
561 /// so that theyare listed from right (least complex) to left (most complex).
562 /// This puts constants before unary operators before binary operators.
563 bool InstCombiner::SimplifyCompare(CmpInst &I) {
564   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
565     return false;
566   I.swapOperands();
567   // Compare instructions are not associative so there's nothing else we can do.
568   return true;
569 }
570
571 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
572 // if the LHS is a constant zero (which is the 'negate' form).
573 //
574 static inline Value *dyn_castNegVal(Value *V) {
575   if (BinaryOperator::isNeg(V))
576     return BinaryOperator::getNegArgument(V);
577
578   // Constants can be considered to be negated values if they can be folded.
579   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
580     return ConstantExpr::getNeg(C);
581
582   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
583     if (C->getType()->getElementType()->isInteger())
584       return ConstantExpr::getNeg(C);
585
586   return 0;
587 }
588
589 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
590 // instruction if the LHS is a constant negative zero (which is the 'negate'
591 // form).
592 //
593 static inline Value *dyn_castFNegVal(Value *V) {
594   if (BinaryOperator::isFNeg(V))
595     return BinaryOperator::getFNegArgument(V);
596
597   // Constants can be considered to be negated values if they can be folded.
598   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
599     return ConstantExpr::getFNeg(C);
600
601   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
602     if (C->getType()->getElementType()->isFloatingPoint())
603       return ConstantExpr::getFNeg(C);
604
605   return 0;
606 }
607
608 static inline Value *dyn_castNotVal(Value *V) {
609   if (BinaryOperator::isNot(V))
610     return BinaryOperator::getNotArgument(V);
611
612   // Constants can be considered to be not'ed values...
613   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
614     return ConstantInt::get(C->getType(), ~C->getValue());
615   return 0;
616 }
617
618 // dyn_castFoldableMul - If this value is a multiply that can be folded into
619 // other computations (because it has a constant operand), return the
620 // non-constant operand of the multiply, and set CST to point to the multiplier.
621 // Otherwise, return null.
622 //
623 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
624   if (V->hasOneUse() && V->getType()->isInteger())
625     if (Instruction *I = dyn_cast<Instruction>(V)) {
626       if (I->getOpcode() == Instruction::Mul)
627         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
628           return I->getOperand(0);
629       if (I->getOpcode() == Instruction::Shl)
630         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
631           // The multiplier is really 1 << CST.
632           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
633           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
634           CST = ConstantInt::get(V->getType()->getContext(),
635                                  APInt(BitWidth, 1).shl(CSTVal));
636           return I->getOperand(0);
637         }
638     }
639   return 0;
640 }
641
642 /// AddOne - Add one to a ConstantInt
643 static Constant *AddOne(Constant *C) {
644   return ConstantExpr::getAdd(C, 
645     ConstantInt::get(C->getType(), 1));
646 }
647 /// SubOne - Subtract one from a ConstantInt
648 static Constant *SubOne(ConstantInt *C) {
649   return ConstantExpr::getSub(C, 
650     ConstantInt::get(C->getType(), 1));
651 }
652 /// MultiplyOverflows - True if the multiply can not be expressed in an int
653 /// this size.
654 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
655   uint32_t W = C1->getBitWidth();
656   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
657   if (sign) {
658     LHSExt.sext(W * 2);
659     RHSExt.sext(W * 2);
660   } else {
661     LHSExt.zext(W * 2);
662     RHSExt.zext(W * 2);
663   }
664
665   APInt MulExt = LHSExt * RHSExt;
666
667   if (sign) {
668     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
669     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
670     return MulExt.slt(Min) || MulExt.sgt(Max);
671   } else 
672     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
673 }
674
675
676 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
677 /// specified instruction is a constant integer.  If so, check to see if there
678 /// are any bits set in the constant that are not demanded.  If so, shrink the
679 /// constant and return true.
680 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
681                                    APInt Demanded) {
682   assert(I && "No instruction?");
683   assert(OpNo < I->getNumOperands() && "Operand index too large");
684
685   // If the operand is not a constant integer, nothing to do.
686   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
687   if (!OpC) return false;
688
689   // If there are no bits set that aren't demanded, nothing to do.
690   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
691   if ((~Demanded & OpC->getValue()) == 0)
692     return false;
693
694   // This instruction is producing bits that are not demanded. Shrink the RHS.
695   Demanded &= OpC->getValue();
696   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
697   return true;
698 }
699
700 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
701 // set of known zero and one bits, compute the maximum and minimum values that
702 // could have the specified known zero and known one bits, returning them in
703 // min/max.
704 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
705                                                    const APInt& KnownOne,
706                                                    APInt& Min, APInt& Max) {
707   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
708          KnownZero.getBitWidth() == Min.getBitWidth() &&
709          KnownZero.getBitWidth() == Max.getBitWidth() &&
710          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
711   APInt UnknownBits = ~(KnownZero|KnownOne);
712
713   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
714   // bit if it is unknown.
715   Min = KnownOne;
716   Max = KnownOne|UnknownBits;
717   
718   if (UnknownBits.isNegative()) { // Sign bit is unknown
719     Min.set(Min.getBitWidth()-1);
720     Max.clear(Max.getBitWidth()-1);
721   }
722 }
723
724 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
725 // a set of known zero and one bits, compute the maximum and minimum values that
726 // could have the specified known zero and known one bits, returning them in
727 // min/max.
728 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
729                                                      const APInt &KnownOne,
730                                                      APInt &Min, APInt &Max) {
731   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
732          KnownZero.getBitWidth() == Min.getBitWidth() &&
733          KnownZero.getBitWidth() == Max.getBitWidth() &&
734          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
735   APInt UnknownBits = ~(KnownZero|KnownOne);
736   
737   // The minimum value is when the unknown bits are all zeros.
738   Min = KnownOne;
739   // The maximum value is when the unknown bits are all ones.
740   Max = KnownOne|UnknownBits;
741 }
742
743 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
744 /// SimplifyDemandedBits knows about.  See if the instruction has any
745 /// properties that allow us to simplify its operands.
746 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
747   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
748   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
749   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
750   
751   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
752                                      KnownZero, KnownOne, 0);
753   if (V == 0) return false;
754   if (V == &Inst) return true;
755   ReplaceInstUsesWith(Inst, V);
756   return true;
757 }
758
759 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
760 /// specified instruction operand if possible, updating it in place.  It returns
761 /// true if it made any change and false otherwise.
762 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
763                                         APInt &KnownZero, APInt &KnownOne,
764                                         unsigned Depth) {
765   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
766                                           KnownZero, KnownOne, Depth);
767   if (NewVal == 0) return false;
768   U.set(NewVal);
769   return true;
770 }
771
772
773 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
774 /// value based on the demanded bits.  When this function is called, it is known
775 /// that only the bits set in DemandedMask of the result of V are ever used
776 /// downstream. Consequently, depending on the mask and V, it may be possible
777 /// to replace V with a constant or one of its operands. In such cases, this
778 /// function does the replacement and returns true. In all other cases, it
779 /// returns false after analyzing the expression and setting KnownOne and known
780 /// to be one in the expression.  KnownZero contains all the bits that are known
781 /// to be zero in the expression. These are provided to potentially allow the
782 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
783 /// the expression. KnownOne and KnownZero always follow the invariant that 
784 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
785 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
786 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
787 /// and KnownOne must all be the same.
788 ///
789 /// This returns null if it did not change anything and it permits no
790 /// simplification.  This returns V itself if it did some simplification of V's
791 /// operands based on the information about what bits are demanded. This returns
792 /// some other non-null value if it found out that V is equal to another value
793 /// in the context where the specified bits are demanded, but not for all users.
794 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
795                                              APInt &KnownZero, APInt &KnownOne,
796                                              unsigned Depth) {
797   assert(V != 0 && "Null pointer of Value???");
798   assert(Depth <= 6 && "Limit Search Depth");
799   uint32_t BitWidth = DemandedMask.getBitWidth();
800   const Type *VTy = V->getType();
801   assert((TD || !isa<PointerType>(VTy)) &&
802          "SimplifyDemandedBits needs to know bit widths!");
803   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
804          (!VTy->isIntOrIntVector() ||
805           VTy->getScalarSizeInBits() == BitWidth) &&
806          KnownZero.getBitWidth() == BitWidth &&
807          KnownOne.getBitWidth() == BitWidth &&
808          "Value *V, DemandedMask, KnownZero and KnownOne "
809          "must have same BitWidth");
810   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
811     // We know all of the bits for a constant!
812     KnownOne = CI->getValue() & DemandedMask;
813     KnownZero = ~KnownOne & DemandedMask;
814     return 0;
815   }
816   if (isa<ConstantPointerNull>(V)) {
817     // We know all of the bits for a constant!
818     KnownOne.clear();
819     KnownZero = DemandedMask;
820     return 0;
821   }
822
823   KnownZero.clear();
824   KnownOne.clear();
825   if (DemandedMask == 0) {   // Not demanding any bits from V.
826     if (isa<UndefValue>(V))
827       return 0;
828     return UndefValue::get(VTy);
829   }
830   
831   if (Depth == 6)        // Limit search depth.
832     return 0;
833   
834   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
835   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
836
837   Instruction *I = dyn_cast<Instruction>(V);
838   if (!I) {
839     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
840     return 0;        // Only analyze instructions.
841   }
842
843   // If there are multiple uses of this value and we aren't at the root, then
844   // we can't do any simplifications of the operands, because DemandedMask
845   // only reflects the bits demanded by *one* of the users.
846   if (Depth != 0 && !I->hasOneUse()) {
847     // Despite the fact that we can't simplify this instruction in all User's
848     // context, we can at least compute the knownzero/knownone bits, and we can
849     // do simplifications that apply to *just* the one user if we know that
850     // this instruction has a simpler value in that context.
851     if (I->getOpcode() == Instruction::And) {
852       // If either the LHS or the RHS are Zero, the result is zero.
853       ComputeMaskedBits(I->getOperand(1), DemandedMask,
854                         RHSKnownZero, RHSKnownOne, Depth+1);
855       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
856                         LHSKnownZero, LHSKnownOne, Depth+1);
857       
858       // If all of the demanded bits are known 1 on one side, return the other.
859       // These bits cannot contribute to the result of the 'and' in this
860       // context.
861       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
862           (DemandedMask & ~LHSKnownZero))
863         return I->getOperand(0);
864       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
865           (DemandedMask & ~RHSKnownZero))
866         return I->getOperand(1);
867       
868       // If all of the demanded bits in the inputs are known zeros, return zero.
869       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
870         return Constant::getNullValue(VTy);
871       
872     } else if (I->getOpcode() == Instruction::Or) {
873       // We can simplify (X|Y) -> X or Y in the user's context if we know that
874       // only bits from X or Y are demanded.
875       
876       // If either the LHS or the RHS are One, the result is One.
877       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
878                         RHSKnownZero, RHSKnownOne, Depth+1);
879       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
880                         LHSKnownZero, LHSKnownOne, Depth+1);
881       
882       // If all of the demanded bits are known zero on one side, return the
883       // other.  These bits cannot contribute to the result of the 'or' in this
884       // context.
885       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
886           (DemandedMask & ~LHSKnownOne))
887         return I->getOperand(0);
888       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
889           (DemandedMask & ~RHSKnownOne))
890         return I->getOperand(1);
891       
892       // If all of the potentially set bits on one side are known to be set on
893       // the other side, just use the 'other' side.
894       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
895           (DemandedMask & (~RHSKnownZero)))
896         return I->getOperand(0);
897       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
898           (DemandedMask & (~LHSKnownZero)))
899         return I->getOperand(1);
900     }
901     
902     // Compute the KnownZero/KnownOne bits to simplify things downstream.
903     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
904     return 0;
905   }
906   
907   // If this is the root being simplified, allow it to have multiple uses,
908   // just set the DemandedMask to all bits so that we can try to simplify the
909   // operands.  This allows visitTruncInst (for example) to simplify the
910   // operand of a trunc without duplicating all the logic below.
911   if (Depth == 0 && !V->hasOneUse())
912     DemandedMask = APInt::getAllOnesValue(BitWidth);
913   
914   switch (I->getOpcode()) {
915   default:
916     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
917     break;
918   case Instruction::And:
919     // If either the LHS or the RHS are Zero, the result is zero.
920     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
921                              RHSKnownZero, RHSKnownOne, Depth+1) ||
922         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
923                              LHSKnownZero, LHSKnownOne, Depth+1))
924       return I;
925     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
926     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
927
928     // If all of the demanded bits are known 1 on one side, return the other.
929     // These bits cannot contribute to the result of the 'and'.
930     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
931         (DemandedMask & ~LHSKnownZero))
932       return I->getOperand(0);
933     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
934         (DemandedMask & ~RHSKnownZero))
935       return I->getOperand(1);
936     
937     // If all of the demanded bits in the inputs are known zeros, return zero.
938     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
939       return Constant::getNullValue(VTy);
940       
941     // If the RHS is a constant, see if we can simplify it.
942     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
943       return I;
944       
945     // Output known-1 bits are only known if set in both the LHS & RHS.
946     RHSKnownOne &= LHSKnownOne;
947     // Output known-0 are known to be clear if zero in either the LHS | RHS.
948     RHSKnownZero |= LHSKnownZero;
949     break;
950   case Instruction::Or:
951     // If either the LHS or the RHS are One, the result is One.
952     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
953                              RHSKnownZero, RHSKnownOne, Depth+1) ||
954         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
955                              LHSKnownZero, LHSKnownOne, Depth+1))
956       return I;
957     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
958     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
959     
960     // If all of the demanded bits are known zero on one side, return the other.
961     // These bits cannot contribute to the result of the 'or'.
962     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
963         (DemandedMask & ~LHSKnownOne))
964       return I->getOperand(0);
965     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
966         (DemandedMask & ~RHSKnownOne))
967       return I->getOperand(1);
968
969     // If all of the potentially set bits on one side are known to be set on
970     // the other side, just use the 'other' side.
971     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
972         (DemandedMask & (~RHSKnownZero)))
973       return I->getOperand(0);
974     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
975         (DemandedMask & (~LHSKnownZero)))
976       return I->getOperand(1);
977         
978     // If the RHS is a constant, see if we can simplify it.
979     if (ShrinkDemandedConstant(I, 1, DemandedMask))
980       return I;
981           
982     // Output known-0 bits are only known if clear in both the LHS & RHS.
983     RHSKnownZero &= LHSKnownZero;
984     // Output known-1 are known to be set if set in either the LHS | RHS.
985     RHSKnownOne |= LHSKnownOne;
986     break;
987   case Instruction::Xor: {
988     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
989                              RHSKnownZero, RHSKnownOne, Depth+1) ||
990         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
991                              LHSKnownZero, LHSKnownOne, Depth+1))
992       return I;
993     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
994     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
995     
996     // If all of the demanded bits are known zero on one side, return the other.
997     // These bits cannot contribute to the result of the 'xor'.
998     if ((DemandedMask & RHSKnownZero) == DemandedMask)
999       return I->getOperand(0);
1000     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1001       return I->getOperand(1);
1002     
1003     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1004     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1005                          (RHSKnownOne & LHSKnownOne);
1006     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1007     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1008                         (RHSKnownOne & LHSKnownZero);
1009     
1010     // If all of the demanded bits are known to be zero on one side or the
1011     // other, turn this into an *inclusive* or.
1012     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1013     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1014       Instruction *Or = 
1015         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1016                                  I->getName());
1017       return InsertNewInstBefore(Or, *I);
1018     }
1019     
1020     // If all of the demanded bits on one side are known, and all of the set
1021     // bits on that side are also known to be set on the other side, turn this
1022     // into an AND, as we know the bits will be cleared.
1023     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1024     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1025       // all known
1026       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1027         Constant *AndC = Constant::getIntegerValue(VTy,
1028                                                    ~RHSKnownOne & DemandedMask);
1029         Instruction *And = 
1030           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1031         return InsertNewInstBefore(And, *I);
1032       }
1033     }
1034     
1035     // If the RHS is a constant, see if we can simplify it.
1036     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1037     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1038       return I;
1039     
1040     RHSKnownZero = KnownZeroOut;
1041     RHSKnownOne  = KnownOneOut;
1042     break;
1043   }
1044   case Instruction::Select:
1045     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1046                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1047         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1048                              LHSKnownZero, LHSKnownOne, Depth+1))
1049       return I;
1050     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1051     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1052     
1053     // If the operands are constants, see if we can simplify them.
1054     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1055         ShrinkDemandedConstant(I, 2, DemandedMask))
1056       return I;
1057     
1058     // Only known if known in both the LHS and RHS.
1059     RHSKnownOne &= LHSKnownOne;
1060     RHSKnownZero &= LHSKnownZero;
1061     break;
1062   case Instruction::Trunc: {
1063     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1064     DemandedMask.zext(truncBf);
1065     RHSKnownZero.zext(truncBf);
1066     RHSKnownOne.zext(truncBf);
1067     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1068                              RHSKnownZero, RHSKnownOne, Depth+1))
1069       return I;
1070     DemandedMask.trunc(BitWidth);
1071     RHSKnownZero.trunc(BitWidth);
1072     RHSKnownOne.trunc(BitWidth);
1073     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1074     break;
1075   }
1076   case Instruction::BitCast:
1077     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1078       return false;  // vector->int or fp->int?
1079
1080     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1081       if (const VectorType *SrcVTy =
1082             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1083         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1084           // Don't touch a bitcast between vectors of different element counts.
1085           return false;
1086       } else
1087         // Don't touch a scalar-to-vector bitcast.
1088         return false;
1089     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1090       // Don't touch a vector-to-scalar bitcast.
1091       return false;
1092
1093     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1094                              RHSKnownZero, RHSKnownOne, Depth+1))
1095       return I;
1096     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1097     break;
1098   case Instruction::ZExt: {
1099     // Compute the bits in the result that are not present in the input.
1100     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1101     
1102     DemandedMask.trunc(SrcBitWidth);
1103     RHSKnownZero.trunc(SrcBitWidth);
1104     RHSKnownOne.trunc(SrcBitWidth);
1105     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1106                              RHSKnownZero, RHSKnownOne, Depth+1))
1107       return I;
1108     DemandedMask.zext(BitWidth);
1109     RHSKnownZero.zext(BitWidth);
1110     RHSKnownOne.zext(BitWidth);
1111     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1112     // The top bits are known to be zero.
1113     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1114     break;
1115   }
1116   case Instruction::SExt: {
1117     // Compute the bits in the result that are not present in the input.
1118     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1119     
1120     APInt InputDemandedBits = DemandedMask & 
1121                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1122
1123     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1124     // If any of the sign extended bits are demanded, we know that the sign
1125     // bit is demanded.
1126     if ((NewBits & DemandedMask) != 0)
1127       InputDemandedBits.set(SrcBitWidth-1);
1128       
1129     InputDemandedBits.trunc(SrcBitWidth);
1130     RHSKnownZero.trunc(SrcBitWidth);
1131     RHSKnownOne.trunc(SrcBitWidth);
1132     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1133                              RHSKnownZero, RHSKnownOne, Depth+1))
1134       return I;
1135     InputDemandedBits.zext(BitWidth);
1136     RHSKnownZero.zext(BitWidth);
1137     RHSKnownOne.zext(BitWidth);
1138     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1139       
1140     // If the sign bit of the input is known set or clear, then we know the
1141     // top bits of the result.
1142
1143     // If the input sign bit is known zero, or if the NewBits are not demanded
1144     // convert this into a zero extension.
1145     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1146       // Convert to ZExt cast
1147       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1148       return InsertNewInstBefore(NewCast, *I);
1149     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1150       RHSKnownOne |= NewBits;
1151     }
1152     break;
1153   }
1154   case Instruction::Add: {
1155     // Figure out what the input bits are.  If the top bits of the and result
1156     // are not demanded, then the add doesn't demand them from its input
1157     // either.
1158     unsigned NLZ = DemandedMask.countLeadingZeros();
1159       
1160     // If there is a constant on the RHS, there are a variety of xformations
1161     // we can do.
1162     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1163       // If null, this should be simplified elsewhere.  Some of the xforms here
1164       // won't work if the RHS is zero.
1165       if (RHS->isZero())
1166         break;
1167       
1168       // If the top bit of the output is demanded, demand everything from the
1169       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1170       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1171
1172       // Find information about known zero/one bits in the input.
1173       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1174                                LHSKnownZero, LHSKnownOne, Depth+1))
1175         return I;
1176
1177       // If the RHS of the add has bits set that can't affect the input, reduce
1178       // the constant.
1179       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1180         return I;
1181       
1182       // Avoid excess work.
1183       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1184         break;
1185       
1186       // Turn it into OR if input bits are zero.
1187       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1188         Instruction *Or =
1189           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1190                                    I->getName());
1191         return InsertNewInstBefore(Or, *I);
1192       }
1193       
1194       // We can say something about the output known-zero and known-one bits,
1195       // depending on potential carries from the input constant and the
1196       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1197       // bits set and the RHS constant is 0x01001, then we know we have a known
1198       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1199       
1200       // To compute this, we first compute the potential carry bits.  These are
1201       // the bits which may be modified.  I'm not aware of a better way to do
1202       // this scan.
1203       const APInt &RHSVal = RHS->getValue();
1204       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1205       
1206       // Now that we know which bits have carries, compute the known-1/0 sets.
1207       
1208       // Bits are known one if they are known zero in one operand and one in the
1209       // other, and there is no input carry.
1210       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1211                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1212       
1213       // Bits are known zero if they are known zero in both operands and there
1214       // is no input carry.
1215       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1216     } else {
1217       // If the high-bits of this ADD are not demanded, then it does not demand
1218       // the high bits of its LHS or RHS.
1219       if (DemandedMask[BitWidth-1] == 0) {
1220         // Right fill the mask of bits for this ADD to demand the most
1221         // significant bit and all those below it.
1222         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1223         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1224                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1225             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1226                                  LHSKnownZero, LHSKnownOne, Depth+1))
1227           return I;
1228       }
1229     }
1230     break;
1231   }
1232   case Instruction::Sub:
1233     // If the high-bits of this SUB are not demanded, then it does not demand
1234     // the high bits of its LHS or RHS.
1235     if (DemandedMask[BitWidth-1] == 0) {
1236       // Right fill the mask of bits for this SUB to demand the most
1237       // significant bit and all those below it.
1238       uint32_t NLZ = DemandedMask.countLeadingZeros();
1239       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1240       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1241                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1242           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1243                                LHSKnownZero, LHSKnownOne, Depth+1))
1244         return I;
1245     }
1246     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1247     // the known zeros and ones.
1248     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1249     break;
1250   case Instruction::Shl:
1251     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1252       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1253       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1254       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1255                                RHSKnownZero, RHSKnownOne, Depth+1))
1256         return I;
1257       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1258       RHSKnownZero <<= ShiftAmt;
1259       RHSKnownOne  <<= ShiftAmt;
1260       // low bits known zero.
1261       if (ShiftAmt)
1262         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1263     }
1264     break;
1265   case Instruction::LShr:
1266     // For a logical shift right
1267     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1268       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1269       
1270       // Unsigned shift right.
1271       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1272       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1273                                RHSKnownZero, RHSKnownOne, Depth+1))
1274         return I;
1275       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1276       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1277       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1278       if (ShiftAmt) {
1279         // Compute the new bits that are at the top now.
1280         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1281         RHSKnownZero |= HighBits;  // high bits known zero.
1282       }
1283     }
1284     break;
1285   case Instruction::AShr:
1286     // If this is an arithmetic shift right and only the low-bit is set, we can
1287     // always convert this into a logical shr, even if the shift amount is
1288     // variable.  The low bit of the shift cannot be an input sign bit unless
1289     // the shift amount is >= the size of the datatype, which is undefined.
1290     if (DemandedMask == 1) {
1291       // Perform the logical shift right.
1292       Instruction *NewVal = BinaryOperator::CreateLShr(
1293                         I->getOperand(0), I->getOperand(1), I->getName());
1294       return InsertNewInstBefore(NewVal, *I);
1295     }    
1296
1297     // If the sign bit is the only bit demanded by this ashr, then there is no
1298     // need to do it, the shift doesn't change the high bit.
1299     if (DemandedMask.isSignBit())
1300       return I->getOperand(0);
1301     
1302     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1303       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1304       
1305       // Signed shift right.
1306       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1307       // If any of the "high bits" are demanded, we should set the sign bit as
1308       // demanded.
1309       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1310         DemandedMaskIn.set(BitWidth-1);
1311       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1312                                RHSKnownZero, RHSKnownOne, Depth+1))
1313         return I;
1314       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1315       // Compute the new bits that are at the top now.
1316       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1317       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1318       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1319         
1320       // Handle the sign bits.
1321       APInt SignBit(APInt::getSignBit(BitWidth));
1322       // Adjust to where it is now in the mask.
1323       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1324         
1325       // If the input sign bit is known to be zero, or if none of the top bits
1326       // are demanded, turn this into an unsigned shift right.
1327       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1328           (HighBits & ~DemandedMask) == HighBits) {
1329         // Perform the logical shift right.
1330         Instruction *NewVal = BinaryOperator::CreateLShr(
1331                           I->getOperand(0), SA, I->getName());
1332         return InsertNewInstBefore(NewVal, *I);
1333       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1334         RHSKnownOne |= HighBits;
1335       }
1336     }
1337     break;
1338   case Instruction::SRem:
1339     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1340       APInt RA = Rem->getValue().abs();
1341       if (RA.isPowerOf2()) {
1342         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1343           return I->getOperand(0);
1344
1345         APInt LowBits = RA - 1;
1346         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1347         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1348                                  LHSKnownZero, LHSKnownOne, Depth+1))
1349           return I;
1350
1351         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1352           LHSKnownZero |= ~LowBits;
1353
1354         KnownZero |= LHSKnownZero & DemandedMask;
1355
1356         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1357       }
1358     }
1359     break;
1360   case Instruction::URem: {
1361     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1362     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1363     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1364                              KnownZero2, KnownOne2, Depth+1) ||
1365         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1366                              KnownZero2, KnownOne2, Depth+1))
1367       return I;
1368
1369     unsigned Leaders = KnownZero2.countLeadingOnes();
1370     Leaders = std::max(Leaders,
1371                        KnownZero2.countLeadingOnes());
1372     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1373     break;
1374   }
1375   case Instruction::Call:
1376     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1377       switch (II->getIntrinsicID()) {
1378       default: break;
1379       case Intrinsic::bswap: {
1380         // If the only bits demanded come from one byte of the bswap result,
1381         // just shift the input byte into position to eliminate the bswap.
1382         unsigned NLZ = DemandedMask.countLeadingZeros();
1383         unsigned NTZ = DemandedMask.countTrailingZeros();
1384           
1385         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1386         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1387         // have 14 leading zeros, round to 8.
1388         NLZ &= ~7;
1389         NTZ &= ~7;
1390         // If we need exactly one byte, we can do this transformation.
1391         if (BitWidth-NLZ-NTZ == 8) {
1392           unsigned ResultBit = NTZ;
1393           unsigned InputBit = BitWidth-NTZ-8;
1394           
1395           // Replace this with either a left or right shift to get the byte into
1396           // the right place.
1397           Instruction *NewVal;
1398           if (InputBit > ResultBit)
1399             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1400                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1401           else
1402             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1403                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1404           NewVal->takeName(I);
1405           return InsertNewInstBefore(NewVal, *I);
1406         }
1407           
1408         // TODO: Could compute known zero/one bits based on the input.
1409         break;
1410       }
1411       }
1412     }
1413     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1414     break;
1415   }
1416   
1417   // If the client is only demanding bits that we know, return the known
1418   // constant.
1419   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1420     return Constant::getIntegerValue(VTy, RHSKnownOne);
1421   return false;
1422 }
1423
1424
1425 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1426 /// any number of elements. DemandedElts contains the set of elements that are
1427 /// actually used by the caller.  This method analyzes which elements of the
1428 /// operand are undef and returns that information in UndefElts.
1429 ///
1430 /// If the information about demanded elements can be used to simplify the
1431 /// operation, the operation is simplified, then the resultant value is
1432 /// returned.  This returns null if no change was made.
1433 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1434                                                 APInt& UndefElts,
1435                                                 unsigned Depth) {
1436   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1437   APInt EltMask(APInt::getAllOnesValue(VWidth));
1438   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1439
1440   if (isa<UndefValue>(V)) {
1441     // If the entire vector is undefined, just return this info.
1442     UndefElts = EltMask;
1443     return 0;
1444   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1445     UndefElts = EltMask;
1446     return UndefValue::get(V->getType());
1447   }
1448
1449   UndefElts = 0;
1450   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1451     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1452     Constant *Undef = UndefValue::get(EltTy);
1453
1454     std::vector<Constant*> Elts;
1455     for (unsigned i = 0; i != VWidth; ++i)
1456       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1457         Elts.push_back(Undef);
1458         UndefElts.set(i);
1459       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1460         Elts.push_back(Undef);
1461         UndefElts.set(i);
1462       } else {                               // Otherwise, defined.
1463         Elts.push_back(CP->getOperand(i));
1464       }
1465
1466     // If we changed the constant, return it.
1467     Constant *NewCP = ConstantVector::get(Elts);
1468     return NewCP != CP ? NewCP : 0;
1469   } else if (isa<ConstantAggregateZero>(V)) {
1470     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1471     // set to undef.
1472     
1473     // Check if this is identity. If so, return 0 since we are not simplifying
1474     // anything.
1475     if (DemandedElts == ((1ULL << VWidth) -1))
1476       return 0;
1477     
1478     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1479     Constant *Zero = Constant::getNullValue(EltTy);
1480     Constant *Undef = UndefValue::get(EltTy);
1481     std::vector<Constant*> Elts;
1482     for (unsigned i = 0; i != VWidth; ++i) {
1483       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1484       Elts.push_back(Elt);
1485     }
1486     UndefElts = DemandedElts ^ EltMask;
1487     return ConstantVector::get(Elts);
1488   }
1489   
1490   // Limit search depth.
1491   if (Depth == 10)
1492     return 0;
1493
1494   // If multiple users are using the root value, procede with
1495   // simplification conservatively assuming that all elements
1496   // are needed.
1497   if (!V->hasOneUse()) {
1498     // Quit if we find multiple users of a non-root value though.
1499     // They'll be handled when it's their turn to be visited by
1500     // the main instcombine process.
1501     if (Depth != 0)
1502       // TODO: Just compute the UndefElts information recursively.
1503       return 0;
1504
1505     // Conservatively assume that all elements are needed.
1506     DemandedElts = EltMask;
1507   }
1508   
1509   Instruction *I = dyn_cast<Instruction>(V);
1510   if (!I) return 0;        // Only analyze instructions.
1511   
1512   bool MadeChange = false;
1513   APInt UndefElts2(VWidth, 0);
1514   Value *TmpV;
1515   switch (I->getOpcode()) {
1516   default: break;
1517     
1518   case Instruction::InsertElement: {
1519     // If this is a variable index, we don't know which element it overwrites.
1520     // demand exactly the same input as we produce.
1521     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1522     if (Idx == 0) {
1523       // Note that we can't propagate undef elt info, because we don't know
1524       // which elt is getting updated.
1525       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1526                                         UndefElts2, Depth+1);
1527       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1528       break;
1529     }
1530     
1531     // If this is inserting an element that isn't demanded, remove this
1532     // insertelement.
1533     unsigned IdxNo = Idx->getZExtValue();
1534     if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1535       Worklist.Add(I);
1536       return I->getOperand(0);
1537     }
1538     
1539     // Otherwise, the element inserted overwrites whatever was there, so the
1540     // input demanded set is simpler than the output set.
1541     APInt DemandedElts2 = DemandedElts;
1542     DemandedElts2.clear(IdxNo);
1543     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1544                                       UndefElts, Depth+1);
1545     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1546
1547     // The inserted element is defined.
1548     UndefElts.clear(IdxNo);
1549     break;
1550   }
1551   case Instruction::ShuffleVector: {
1552     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1553     uint64_t LHSVWidth =
1554       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1555     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1556     for (unsigned i = 0; i < VWidth; i++) {
1557       if (DemandedElts[i]) {
1558         unsigned MaskVal = Shuffle->getMaskValue(i);
1559         if (MaskVal != -1u) {
1560           assert(MaskVal < LHSVWidth * 2 &&
1561                  "shufflevector mask index out of range!");
1562           if (MaskVal < LHSVWidth)
1563             LeftDemanded.set(MaskVal);
1564           else
1565             RightDemanded.set(MaskVal - LHSVWidth);
1566         }
1567       }
1568     }
1569
1570     APInt UndefElts4(LHSVWidth, 0);
1571     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1572                                       UndefElts4, Depth+1);
1573     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1574
1575     APInt UndefElts3(LHSVWidth, 0);
1576     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1577                                       UndefElts3, Depth+1);
1578     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1579
1580     bool NewUndefElts = false;
1581     for (unsigned i = 0; i < VWidth; i++) {
1582       unsigned MaskVal = Shuffle->getMaskValue(i);
1583       if (MaskVal == -1u) {
1584         UndefElts.set(i);
1585       } else if (MaskVal < LHSVWidth) {
1586         if (UndefElts4[MaskVal]) {
1587           NewUndefElts = true;
1588           UndefElts.set(i);
1589         }
1590       } else {
1591         if (UndefElts3[MaskVal - LHSVWidth]) {
1592           NewUndefElts = true;
1593           UndefElts.set(i);
1594         }
1595       }
1596     }
1597
1598     if (NewUndefElts) {
1599       // Add additional discovered undefs.
1600       std::vector<Constant*> Elts;
1601       for (unsigned i = 0; i < VWidth; ++i) {
1602         if (UndefElts[i])
1603           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
1604         else
1605           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
1606                                           Shuffle->getMaskValue(i)));
1607       }
1608       I->setOperand(2, ConstantVector::get(Elts));
1609       MadeChange = true;
1610     }
1611     break;
1612   }
1613   case Instruction::BitCast: {
1614     // Vector->vector casts only.
1615     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1616     if (!VTy) break;
1617     unsigned InVWidth = VTy->getNumElements();
1618     APInt InputDemandedElts(InVWidth, 0);
1619     unsigned Ratio;
1620
1621     if (VWidth == InVWidth) {
1622       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1623       // elements as are demanded of us.
1624       Ratio = 1;
1625       InputDemandedElts = DemandedElts;
1626     } else if (VWidth > InVWidth) {
1627       // Untested so far.
1628       break;
1629       
1630       // If there are more elements in the result than there are in the source,
1631       // then an input element is live if any of the corresponding output
1632       // elements are live.
1633       Ratio = VWidth/InVWidth;
1634       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1635         if (DemandedElts[OutIdx])
1636           InputDemandedElts.set(OutIdx/Ratio);
1637       }
1638     } else {
1639       // Untested so far.
1640       break;
1641       
1642       // If there are more elements in the source than there are in the result,
1643       // then an input element is live if the corresponding output element is
1644       // live.
1645       Ratio = InVWidth/VWidth;
1646       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1647         if (DemandedElts[InIdx/Ratio])
1648           InputDemandedElts.set(InIdx);
1649     }
1650     
1651     // div/rem demand all inputs, because they don't want divide by zero.
1652     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1653                                       UndefElts2, Depth+1);
1654     if (TmpV) {
1655       I->setOperand(0, TmpV);
1656       MadeChange = true;
1657     }
1658     
1659     UndefElts = UndefElts2;
1660     if (VWidth > InVWidth) {
1661       llvm_unreachable("Unimp");
1662       // If there are more elements in the result than there are in the source,
1663       // then an output element is undef if the corresponding input element is
1664       // undef.
1665       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1666         if (UndefElts2[OutIdx/Ratio])
1667           UndefElts.set(OutIdx);
1668     } else if (VWidth < InVWidth) {
1669       llvm_unreachable("Unimp");
1670       // If there are more elements in the source than there are in the result,
1671       // then a result element is undef if all of the corresponding input
1672       // elements are undef.
1673       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1674       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1675         if (!UndefElts2[InIdx])            // Not undef?
1676           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1677     }
1678     break;
1679   }
1680   case Instruction::And:
1681   case Instruction::Or:
1682   case Instruction::Xor:
1683   case Instruction::Add:
1684   case Instruction::Sub:
1685   case Instruction::Mul:
1686     // div/rem demand all inputs, because they don't want divide by zero.
1687     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1688                                       UndefElts, Depth+1);
1689     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1690     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1691                                       UndefElts2, Depth+1);
1692     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1693       
1694     // Output elements are undefined if both are undefined.  Consider things
1695     // like undef&0.  The result is known zero, not undef.
1696     UndefElts &= UndefElts2;
1697     break;
1698     
1699   case Instruction::Call: {
1700     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1701     if (!II) break;
1702     switch (II->getIntrinsicID()) {
1703     default: break;
1704       
1705     // Binary vector operations that work column-wise.  A dest element is a
1706     // function of the corresponding input elements from the two inputs.
1707     case Intrinsic::x86_sse_sub_ss:
1708     case Intrinsic::x86_sse_mul_ss:
1709     case Intrinsic::x86_sse_min_ss:
1710     case Intrinsic::x86_sse_max_ss:
1711     case Intrinsic::x86_sse2_sub_sd:
1712     case Intrinsic::x86_sse2_mul_sd:
1713     case Intrinsic::x86_sse2_min_sd:
1714     case Intrinsic::x86_sse2_max_sd:
1715       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1716                                         UndefElts, Depth+1);
1717       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1718       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1719                                         UndefElts2, Depth+1);
1720       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1721
1722       // If only the low elt is demanded and this is a scalarizable intrinsic,
1723       // scalarize it now.
1724       if (DemandedElts == 1) {
1725         switch (II->getIntrinsicID()) {
1726         default: break;
1727         case Intrinsic::x86_sse_sub_ss:
1728         case Intrinsic::x86_sse_mul_ss:
1729         case Intrinsic::x86_sse2_sub_sd:
1730         case Intrinsic::x86_sse2_mul_sd:
1731           // TODO: Lower MIN/MAX/ABS/etc
1732           Value *LHS = II->getOperand(1);
1733           Value *RHS = II->getOperand(2);
1734           // Extract the element as scalars.
1735           LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS, 
1736             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1737           RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1738             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1739           
1740           switch (II->getIntrinsicID()) {
1741           default: llvm_unreachable("Case stmts out of sync!");
1742           case Intrinsic::x86_sse_sub_ss:
1743           case Intrinsic::x86_sse2_sub_sd:
1744             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1745                                                         II->getName()), *II);
1746             break;
1747           case Intrinsic::x86_sse_mul_ss:
1748           case Intrinsic::x86_sse2_mul_sd:
1749             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1750                                                          II->getName()), *II);
1751             break;
1752           }
1753           
1754           Instruction *New =
1755             InsertElementInst::Create(
1756               UndefValue::get(II->getType()), TmpV,
1757               ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
1758           InsertNewInstBefore(New, *II);
1759           return New;
1760         }            
1761       }
1762         
1763       // Output elements are undefined if both are undefined.  Consider things
1764       // like undef&0.  The result is known zero, not undef.
1765       UndefElts &= UndefElts2;
1766       break;
1767     }
1768     break;
1769   }
1770   }
1771   return MadeChange ? I : 0;
1772 }
1773
1774
1775 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1776 /// function is designed to check a chain of associative operators for a
1777 /// potential to apply a certain optimization.  Since the optimization may be
1778 /// applicable if the expression was reassociated, this checks the chain, then
1779 /// reassociates the expression as necessary to expose the optimization
1780 /// opportunity.  This makes use of a special Functor, which must define
1781 /// 'shouldApply' and 'apply' methods.
1782 ///
1783 template<typename Functor>
1784 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1785   unsigned Opcode = Root.getOpcode();
1786   Value *LHS = Root.getOperand(0);
1787
1788   // Quick check, see if the immediate LHS matches...
1789   if (F.shouldApply(LHS))
1790     return F.apply(Root);
1791
1792   // Otherwise, if the LHS is not of the same opcode as the root, return.
1793   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1794   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1795     // Should we apply this transform to the RHS?
1796     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1797
1798     // If not to the RHS, check to see if we should apply to the LHS...
1799     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1800       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1801       ShouldApply = true;
1802     }
1803
1804     // If the functor wants to apply the optimization to the RHS of LHSI,
1805     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1806     if (ShouldApply) {
1807       // Now all of the instructions are in the current basic block, go ahead
1808       // and perform the reassociation.
1809       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1810
1811       // First move the selected RHS to the LHS of the root...
1812       Root.setOperand(0, LHSI->getOperand(1));
1813
1814       // Make what used to be the LHS of the root be the user of the root...
1815       Value *ExtraOperand = TmpLHSI->getOperand(1);
1816       if (&Root == TmpLHSI) {
1817         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1818         return 0;
1819       }
1820       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1821       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1822       BasicBlock::iterator ARI = &Root; ++ARI;
1823       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1824       ARI = Root;
1825
1826       // Now propagate the ExtraOperand down the chain of instructions until we
1827       // get to LHSI.
1828       while (TmpLHSI != LHSI) {
1829         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1830         // Move the instruction to immediately before the chain we are
1831         // constructing to avoid breaking dominance properties.
1832         NextLHSI->moveBefore(ARI);
1833         ARI = NextLHSI;
1834
1835         Value *NextOp = NextLHSI->getOperand(1);
1836         NextLHSI->setOperand(1, ExtraOperand);
1837         TmpLHSI = NextLHSI;
1838         ExtraOperand = NextOp;
1839       }
1840
1841       // Now that the instructions are reassociated, have the functor perform
1842       // the transformation...
1843       return F.apply(Root);
1844     }
1845
1846     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1847   }
1848   return 0;
1849 }
1850
1851 namespace {
1852
1853 // AddRHS - Implements: X + X --> X << 1
1854 struct AddRHS {
1855   Value *RHS;
1856   explicit AddRHS(Value *rhs) : RHS(rhs) {}
1857   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1858   Instruction *apply(BinaryOperator &Add) const {
1859     return BinaryOperator::CreateShl(Add.getOperand(0),
1860                                      ConstantInt::get(Add.getType(), 1));
1861   }
1862 };
1863
1864 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1865 //                 iff C1&C2 == 0
1866 struct AddMaskingAnd {
1867   Constant *C2;
1868   explicit AddMaskingAnd(Constant *c) : C2(c) {}
1869   bool shouldApply(Value *LHS) const {
1870     ConstantInt *C1;
1871     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1872            ConstantExpr::getAnd(C1, C2)->isNullValue();
1873   }
1874   Instruction *apply(BinaryOperator &Add) const {
1875     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1876   }
1877 };
1878
1879 }
1880
1881 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1882                                              InstCombiner *IC) {
1883   if (CastInst *CI = dyn_cast<CastInst>(&I))
1884     return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
1885
1886   // Figure out if the constant is the left or the right argument.
1887   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1888   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1889
1890   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1891     if (ConstIsRHS)
1892       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1893     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1894   }
1895
1896   Value *Op0 = SO, *Op1 = ConstOperand;
1897   if (!ConstIsRHS)
1898     std::swap(Op0, Op1);
1899   
1900   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1901     return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1902                                     SO->getName()+".op");
1903   if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1904     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1905                                    SO->getName()+".cmp");
1906   if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1907     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1908                                    SO->getName()+".cmp");
1909   llvm_unreachable("Unknown binary instruction type!");
1910 }
1911
1912 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1913 // constant as the other operand, try to fold the binary operator into the
1914 // select arguments.  This also works for Cast instructions, which obviously do
1915 // not have a second operand.
1916 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1917                                      InstCombiner *IC) {
1918   // Don't modify shared select instructions
1919   if (!SI->hasOneUse()) return 0;
1920   Value *TV = SI->getOperand(1);
1921   Value *FV = SI->getOperand(2);
1922
1923   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1924     // Bool selects with constant operands can be folded to logical ops.
1925     if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
1926
1927     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1928     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1929
1930     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1931                               SelectFalseVal);
1932   }
1933   return 0;
1934 }
1935
1936
1937 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1938 /// node as operand #0, see if we can fold the instruction into the PHI (which
1939 /// is only possible if all operands to the PHI are constants).
1940 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1941   PHINode *PN = cast<PHINode>(I.getOperand(0));
1942   unsigned NumPHIValues = PN->getNumIncomingValues();
1943   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1944
1945   // Check to see if all of the operands of the PHI are constants.  If there is
1946   // one non-constant value, remember the BB it is.  If there is more than one
1947   // or if *it* is a PHI, bail out.
1948   BasicBlock *NonConstBB = 0;
1949   for (unsigned i = 0; i != NumPHIValues; ++i)
1950     if (!isa<Constant>(PN->getIncomingValue(i))) {
1951       if (NonConstBB) return 0;  // More than one non-const value.
1952       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1953       NonConstBB = PN->getIncomingBlock(i);
1954       
1955       // If the incoming non-constant value is in I's block, we have an infinite
1956       // loop.
1957       if (NonConstBB == I.getParent())
1958         return 0;
1959     }
1960   
1961   // If there is exactly one non-constant value, we can insert a copy of the
1962   // operation in that block.  However, if this is a critical edge, we would be
1963   // inserting the computation one some other paths (e.g. inside a loop).  Only
1964   // do this if the pred block is unconditionally branching into the phi block.
1965   if (NonConstBB) {
1966     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1967     if (!BI || !BI->isUnconditional()) return 0;
1968   }
1969
1970   // Okay, we can do the transformation: create the new PHI node.
1971   PHINode *NewPN = PHINode::Create(I.getType(), "");
1972   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1973   InsertNewInstBefore(NewPN, *PN);
1974   NewPN->takeName(PN);
1975
1976   // Next, add all of the operands to the PHI.
1977   if (I.getNumOperands() == 2) {
1978     Constant *C = cast<Constant>(I.getOperand(1));
1979     for (unsigned i = 0; i != NumPHIValues; ++i) {
1980       Value *InV = 0;
1981       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1982         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1983           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1984         else
1985           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1986       } else {
1987         assert(PN->getIncomingBlock(i) == NonConstBB);
1988         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1989           InV = BinaryOperator::Create(BO->getOpcode(),
1990                                        PN->getIncomingValue(i), C, "phitmp",
1991                                        NonConstBB->getTerminator());
1992         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1993           InV = CmpInst::Create(CI->getOpcode(),
1994                                 CI->getPredicate(),
1995                                 PN->getIncomingValue(i), C, "phitmp",
1996                                 NonConstBB->getTerminator());
1997         else
1998           llvm_unreachable("Unknown binop!");
1999         
2000         Worklist.Add(cast<Instruction>(InV));
2001       }
2002       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2003     }
2004   } else { 
2005     CastInst *CI = cast<CastInst>(&I);
2006     const Type *RetTy = CI->getType();
2007     for (unsigned i = 0; i != NumPHIValues; ++i) {
2008       Value *InV;
2009       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2010         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2011       } else {
2012         assert(PN->getIncomingBlock(i) == NonConstBB);
2013         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2014                                I.getType(), "phitmp", 
2015                                NonConstBB->getTerminator());
2016         Worklist.Add(cast<Instruction>(InV));
2017       }
2018       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2019     }
2020   }
2021   return ReplaceInstUsesWith(I, NewPN);
2022 }
2023
2024
2025 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2026 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2027 /// This basically requires proving that the add in the original type would not
2028 /// overflow to change the sign bit or have a carry out.
2029 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2030   // There are different heuristics we can use for this.  Here are some simple
2031   // ones.
2032   
2033   // Add has the property that adding any two 2's complement numbers can only 
2034   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2035   // have at least two sign bits, we know that the addition of the two values will
2036   // sign extend fine.
2037   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2038     return true;
2039   
2040   
2041   // If one of the operands only has one non-zero bit, and if the other operand
2042   // has a known-zero bit in a more significant place than it (not including the
2043   // sign bit) the ripple may go up to and fill the zero, but won't change the
2044   // sign.  For example, (X & ~4) + 1.
2045   
2046   // TODO: Implement.
2047   
2048   return false;
2049 }
2050
2051
2052 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2053   bool Changed = SimplifyCommutative(I);
2054   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2055
2056   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2057     // X + undef -> undef
2058     if (isa<UndefValue>(RHS))
2059       return ReplaceInstUsesWith(I, RHS);
2060
2061     // X + 0 --> X
2062     if (RHSC->isNullValue())
2063       return ReplaceInstUsesWith(I, LHS);
2064
2065     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2066       // X + (signbit) --> X ^ signbit
2067       const APInt& Val = CI->getValue();
2068       uint32_t BitWidth = Val.getBitWidth();
2069       if (Val == APInt::getSignBit(BitWidth))
2070         return BinaryOperator::CreateXor(LHS, RHS);
2071       
2072       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2073       // (X & 254)+1 -> (X&254)|1
2074       if (SimplifyDemandedInstructionBits(I))
2075         return &I;
2076
2077       // zext(bool) + C -> bool ? C + 1 : C
2078       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2079         if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2080           return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
2081     }
2082
2083     if (isa<PHINode>(LHS))
2084       if (Instruction *NV = FoldOpIntoPhi(I))
2085         return NV;
2086     
2087     ConstantInt *XorRHS = 0;
2088     Value *XorLHS = 0;
2089     if (isa<ConstantInt>(RHSC) &&
2090         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2091       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2092       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2093       
2094       uint32_t Size = TySizeBits / 2;
2095       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2096       APInt CFF80Val(-C0080Val);
2097       do {
2098         if (TySizeBits > Size) {
2099           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2100           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2101           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2102               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2103             // This is a sign extend if the top bits are known zero.
2104             if (!MaskedValueIsZero(XorLHS, 
2105                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2106               Size = 0;  // Not a sign ext, but can't be any others either.
2107             break;
2108           }
2109         }
2110         Size >>= 1;
2111         C0080Val = APIntOps::lshr(C0080Val, Size);
2112         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2113       } while (Size >= 1);
2114       
2115       // FIXME: This shouldn't be necessary. When the backends can handle types
2116       // with funny bit widths then this switch statement should be removed. It
2117       // is just here to get the size of the "middle" type back up to something
2118       // that the back ends can handle.
2119       const Type *MiddleType = 0;
2120       switch (Size) {
2121         default: break;
2122         case 32: MiddleType = Type::getInt32Ty(*Context); break;
2123         case 16: MiddleType = Type::getInt16Ty(*Context); break;
2124         case  8: MiddleType = Type::getInt8Ty(*Context); break;
2125       }
2126       if (MiddleType) {
2127         Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
2128         return new SExtInst(NewTrunc, I.getType(), I.getName());
2129       }
2130     }
2131   }
2132
2133   if (I.getType() == Type::getInt1Ty(*Context))
2134     return BinaryOperator::CreateXor(LHS, RHS);
2135
2136   // X + X --> X << 1
2137   if (I.getType()->isInteger()) {
2138     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
2139       return Result;
2140
2141     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2142       if (RHSI->getOpcode() == Instruction::Sub)
2143         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2144           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2145     }
2146     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2147       if (LHSI->getOpcode() == Instruction::Sub)
2148         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2149           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2150     }
2151   }
2152
2153   // -A + B  -->  B - A
2154   // -A + -B  -->  -(A + B)
2155   if (Value *LHSV = dyn_castNegVal(LHS)) {
2156     if (LHS->getType()->isIntOrIntVector()) {
2157       if (Value *RHSV = dyn_castNegVal(RHS)) {
2158         Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
2159         return BinaryOperator::CreateNeg(NewAdd);
2160       }
2161     }
2162     
2163     return BinaryOperator::CreateSub(RHS, LHSV);
2164   }
2165
2166   // A + -B  -->  A - B
2167   if (!isa<Constant>(RHS))
2168     if (Value *V = dyn_castNegVal(RHS))
2169       return BinaryOperator::CreateSub(LHS, V);
2170
2171
2172   ConstantInt *C2;
2173   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2174     if (X == RHS)   // X*C + X --> X * (C+1)
2175       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2176
2177     // X*C1 + X*C2 --> X * (C1+C2)
2178     ConstantInt *C1;
2179     if (X == dyn_castFoldableMul(RHS, C1))
2180       return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2181   }
2182
2183   // X + X*C --> X * (C+1)
2184   if (dyn_castFoldableMul(RHS, C2) == LHS)
2185     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2186
2187   // X + ~X --> -1   since   ~X = -X-1
2188   if (dyn_castNotVal(LHS) == RHS ||
2189       dyn_castNotVal(RHS) == LHS)
2190     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2191   
2192
2193   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2194   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2195     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2196       return R;
2197   
2198   // A+B --> A|B iff A and B have no bits set in common.
2199   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2200     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2201     APInt LHSKnownOne(IT->getBitWidth(), 0);
2202     APInt LHSKnownZero(IT->getBitWidth(), 0);
2203     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2204     if (LHSKnownZero != 0) {
2205       APInt RHSKnownOne(IT->getBitWidth(), 0);
2206       APInt RHSKnownZero(IT->getBitWidth(), 0);
2207       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2208       
2209       // No bits in common -> bitwise or.
2210       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2211         return BinaryOperator::CreateOr(LHS, RHS);
2212     }
2213   }
2214
2215   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2216   if (I.getType()->isIntOrIntVector()) {
2217     Value *W, *X, *Y, *Z;
2218     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2219         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2220       if (W != Y) {
2221         if (W == Z) {
2222           std::swap(Y, Z);
2223         } else if (Y == X) {
2224           std::swap(W, X);
2225         } else if (X == Z) {
2226           std::swap(Y, Z);
2227           std::swap(W, X);
2228         }
2229       }
2230
2231       if (W == Y) {
2232         Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
2233         return BinaryOperator::CreateMul(W, NewAdd);
2234       }
2235     }
2236   }
2237
2238   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2239     Value *X = 0;
2240     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2241       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2242
2243     // (X & FF00) + xx00  -> (X+xx00) & FF00
2244     if (LHS->hasOneUse() &&
2245         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2246       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2247       if (Anded == CRHS) {
2248         // See if all bits from the first bit set in the Add RHS up are included
2249         // in the mask.  First, get the rightmost bit.
2250         const APInt& AddRHSV = CRHS->getValue();
2251
2252         // Form a mask of all bits from the lowest bit added through the top.
2253         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2254
2255         // See if the and mask includes all of these bits.
2256         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2257
2258         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2259           // Okay, the xform is safe.  Insert the new add pronto.
2260           Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
2261           return BinaryOperator::CreateAnd(NewAdd, C2);
2262         }
2263       }
2264     }
2265
2266     // Try to fold constant add into select arguments.
2267     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2268       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2269         return R;
2270   }
2271
2272   // add (select X 0 (sub n A)) A  -->  select X A n
2273   {
2274     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2275     Value *A = RHS;
2276     if (!SI) {
2277       SI = dyn_cast<SelectInst>(RHS);
2278       A = LHS;
2279     }
2280     if (SI && SI->hasOneUse()) {
2281       Value *TV = SI->getTrueValue();
2282       Value *FV = SI->getFalseValue();
2283       Value *N;
2284
2285       // Can we fold the add into the argument of the select?
2286       // We check both true and false select arguments for a matching subtract.
2287       if (match(FV, m_Zero()) &&
2288           match(TV, m_Sub(m_Value(N), m_Specific(A))))
2289         // Fold the add into the true select value.
2290         return SelectInst::Create(SI->getCondition(), N, A);
2291       if (match(TV, m_Zero()) &&
2292           match(FV, m_Sub(m_Value(N), m_Specific(A))))
2293         // Fold the add into the false select value.
2294         return SelectInst::Create(SI->getCondition(), A, N);
2295     }
2296   }
2297
2298   // Check for (add (sext x), y), see if we can merge this into an
2299   // integer add followed by a sext.
2300   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2301     // (add (sext x), cst) --> (sext (add x, cst'))
2302     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2303       Constant *CI = 
2304         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2305       if (LHSConv->hasOneUse() &&
2306           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2307           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2308         // Insert the new, smaller add.
2309         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0), 
2310                                            CI, "addconv");
2311         return new SExtInst(NewAdd, I.getType());
2312       }
2313     }
2314     
2315     // (add (sext x), (sext y)) --> (sext (add int x, y))
2316     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2317       // Only do this if x/y have the same type, if at last one of them has a
2318       // single use (so we don't increase the number of sexts), and if the
2319       // integer add will not overflow.
2320       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2321           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2322           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2323                                    RHSConv->getOperand(0))) {
2324         // Insert the new integer add.
2325         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0), 
2326                                            RHSConv->getOperand(0), "addconv");
2327         return new SExtInst(NewAdd, I.getType());
2328       }
2329     }
2330   }
2331
2332   return Changed ? &I : 0;
2333 }
2334
2335 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2336   bool Changed = SimplifyCommutative(I);
2337   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2338
2339   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2340     // X + 0 --> X
2341     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2342       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2343                               (I.getType())->getValueAPF()))
2344         return ReplaceInstUsesWith(I, LHS);
2345     }
2346
2347     if (isa<PHINode>(LHS))
2348       if (Instruction *NV = FoldOpIntoPhi(I))
2349         return NV;
2350   }
2351
2352   // -A + B  -->  B - A
2353   // -A + -B  -->  -(A + B)
2354   if (Value *LHSV = dyn_castFNegVal(LHS))
2355     return BinaryOperator::CreateFSub(RHS, LHSV);
2356
2357   // A + -B  -->  A - B
2358   if (!isa<Constant>(RHS))
2359     if (Value *V = dyn_castFNegVal(RHS))
2360       return BinaryOperator::CreateFSub(LHS, V);
2361
2362   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2363   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2364     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2365       return ReplaceInstUsesWith(I, LHS);
2366
2367   // Check for (add double (sitofp x), y), see if we can merge this into an
2368   // integer add followed by a promotion.
2369   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2370     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2371     // ... if the constant fits in the integer value.  This is useful for things
2372     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2373     // requires a constant pool load, and generally allows the add to be better
2374     // instcombined.
2375     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2376       Constant *CI = 
2377       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2378       if (LHSConv->hasOneUse() &&
2379           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2380           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2381         // Insert the new integer add.
2382         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2383                                            CI, "addconv");
2384         return new SIToFPInst(NewAdd, I.getType());
2385       }
2386     }
2387     
2388     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2389     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2390       // Only do this if x/y have the same type, if at last one of them has a
2391       // single use (so we don't increase the number of int->fp conversions),
2392       // and if the integer add will not overflow.
2393       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2394           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2395           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2396                                    RHSConv->getOperand(0))) {
2397         // Insert the new integer add.
2398         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0), 
2399                                            RHSConv->getOperand(0), "addconv");
2400         return new SIToFPInst(NewAdd, I.getType());
2401       }
2402     }
2403   }
2404   
2405   return Changed ? &I : 0;
2406 }
2407
2408 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2409   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2410
2411   if (Op0 == Op1)                        // sub X, X  -> 0
2412     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2413
2414   // If this is a 'B = x-(-A)', change to B = x+A...
2415   if (Value *V = dyn_castNegVal(Op1))
2416     return BinaryOperator::CreateAdd(Op0, V);
2417
2418   if (isa<UndefValue>(Op0))
2419     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2420   if (isa<UndefValue>(Op1))
2421     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2422
2423   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2424     // Replace (-1 - A) with (~A)...
2425     if (C->isAllOnesValue())
2426       return BinaryOperator::CreateNot(Op1);
2427
2428     // C - ~X == X + (1+C)
2429     Value *X = 0;
2430     if (match(Op1, m_Not(m_Value(X))))
2431       return BinaryOperator::CreateAdd(X, AddOne(C));
2432
2433     // -(X >>u 31) -> (X >>s 31)
2434     // -(X >>s 31) -> (X >>u 31)
2435     if (C->isZero()) {
2436       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2437         if (SI->getOpcode() == Instruction::LShr) {
2438           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2439             // Check to see if we are shifting out everything but the sign bit.
2440             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2441                 SI->getType()->getPrimitiveSizeInBits()-1) {
2442               // Ok, the transformation is safe.  Insert AShr.
2443               return BinaryOperator::Create(Instruction::AShr, 
2444                                           SI->getOperand(0), CU, SI->getName());
2445             }
2446           }
2447         }
2448         else if (SI->getOpcode() == Instruction::AShr) {
2449           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2450             // Check to see if we are shifting out everything but the sign bit.
2451             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2452                 SI->getType()->getPrimitiveSizeInBits()-1) {
2453               // Ok, the transformation is safe.  Insert LShr. 
2454               return BinaryOperator::CreateLShr(
2455                                           SI->getOperand(0), CU, SI->getName());
2456             }
2457           }
2458         }
2459       }
2460     }
2461
2462     // Try to fold constant sub into select arguments.
2463     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2464       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2465         return R;
2466
2467     // C - zext(bool) -> bool ? C - 1 : C
2468     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2469       if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2470         return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
2471   }
2472
2473   if (I.getType() == Type::getInt1Ty(*Context))
2474     return BinaryOperator::CreateXor(Op0, Op1);
2475
2476   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2477     if (Op1I->getOpcode() == Instruction::Add) {
2478       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2479         return BinaryOperator::CreateNeg(Op1I->getOperand(1),
2480                                          I.getName());
2481       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2482         return BinaryOperator::CreateNeg(Op1I->getOperand(0),
2483                                          I.getName());
2484       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2485         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2486           // C1-(X+C2) --> (C1-C2)-X
2487           return BinaryOperator::CreateSub(
2488             ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
2489       }
2490     }
2491
2492     if (Op1I->hasOneUse()) {
2493       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2494       // is not used by anyone else...
2495       //
2496       if (Op1I->getOpcode() == Instruction::Sub) {
2497         // Swap the two operands of the subexpr...
2498         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2499         Op1I->setOperand(0, IIOp1);
2500         Op1I->setOperand(1, IIOp0);
2501
2502         // Create the new top level add instruction...
2503         return BinaryOperator::CreateAdd(Op0, Op1);
2504       }
2505
2506       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2507       //
2508       if (Op1I->getOpcode() == Instruction::And &&
2509           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2510         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2511
2512         Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
2513         return BinaryOperator::CreateAnd(Op0, NewNot);
2514       }
2515
2516       // 0 - (X sdiv C)  -> (X sdiv -C)
2517       if (Op1I->getOpcode() == Instruction::SDiv)
2518         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2519           if (CSI->isZero())
2520             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2521               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2522                                           ConstantExpr::getNeg(DivRHS));
2523
2524       // X - X*C --> X * (1-C)
2525       ConstantInt *C2 = 0;
2526       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2527         Constant *CP1 = 
2528           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2529                                              C2);
2530         return BinaryOperator::CreateMul(Op0, CP1);
2531       }
2532     }
2533   }
2534
2535   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2536     if (Op0I->getOpcode() == Instruction::Add) {
2537       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2538         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2539       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2540         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2541     } else if (Op0I->getOpcode() == Instruction::Sub) {
2542       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2543         return BinaryOperator::CreateNeg(Op0I->getOperand(1),
2544                                          I.getName());
2545     }
2546   }
2547
2548   ConstantInt *C1;
2549   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2550     if (X == Op1)  // X*C - X --> X * (C-1)
2551       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2552
2553     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2554     if (X == dyn_castFoldableMul(Op1, C2))
2555       return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2556   }
2557   return 0;
2558 }
2559
2560 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2561   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2562
2563   // If this is a 'B = x-(-A)', change to B = x+A...
2564   if (Value *V = dyn_castFNegVal(Op1))
2565     return BinaryOperator::CreateFAdd(Op0, V);
2566
2567   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2568     if (Op1I->getOpcode() == Instruction::FAdd) {
2569       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2570         return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
2571                                           I.getName());
2572       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2573         return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
2574                                           I.getName());
2575     }
2576   }
2577
2578   return 0;
2579 }
2580
2581 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2582 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2583 /// TrueIfSigned if the result of the comparison is true when the input value is
2584 /// signed.
2585 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2586                            bool &TrueIfSigned) {
2587   switch (pred) {
2588   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2589     TrueIfSigned = true;
2590     return RHS->isZero();
2591   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2592     TrueIfSigned = true;
2593     return RHS->isAllOnesValue();
2594   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2595     TrueIfSigned = false;
2596     return RHS->isAllOnesValue();
2597   case ICmpInst::ICMP_UGT:
2598     // True if LHS u> RHS and RHS == high-bit-mask - 1
2599     TrueIfSigned = true;
2600     return RHS->getValue() ==
2601       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2602   case ICmpInst::ICMP_UGE: 
2603     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2604     TrueIfSigned = true;
2605     return RHS->getValue().isSignBit();
2606   default:
2607     return false;
2608   }
2609 }
2610
2611 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2612   bool Changed = SimplifyCommutative(I);
2613   Value *Op0 = I.getOperand(0);
2614
2615   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2616     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2617
2618   // Simplify mul instructions with a constant RHS...
2619   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2620     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2621
2622       // ((X << C1)*C2) == (X * (C2 << C1))
2623       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2624         if (SI->getOpcode() == Instruction::Shl)
2625           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2626             return BinaryOperator::CreateMul(SI->getOperand(0),
2627                                         ConstantExpr::getShl(CI, ShOp));
2628
2629       if (CI->isZero())
2630         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2631       if (CI->equalsInt(1))                  // X * 1  == X
2632         return ReplaceInstUsesWith(I, Op0);
2633       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2634         return BinaryOperator::CreateNeg(Op0, I.getName());
2635
2636       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2637       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2638         return BinaryOperator::CreateShl(Op0,
2639                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2640       }
2641     } else if (isa<VectorType>(Op1->getType())) {
2642       if (Op1->isNullValue())
2643         return ReplaceInstUsesWith(I, Op1);
2644
2645       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2646         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2647           return BinaryOperator::CreateNeg(Op0, I.getName());
2648
2649         // As above, vector X*splat(1.0) -> X in all defined cases.
2650         if (Constant *Splat = Op1V->getSplatValue()) {
2651           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2652             if (CI->equalsInt(1))
2653               return ReplaceInstUsesWith(I, Op0);
2654         }
2655       }
2656     }
2657     
2658     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2659       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2660           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2661         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2662         Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1, "tmp");
2663         Value *C1C2 = Builder->CreateMul(Op1, Op0I->getOperand(1));
2664         return BinaryOperator::CreateAdd(Add, C1C2);
2665         
2666       }
2667
2668     // Try to fold constant mul into select arguments.
2669     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2670       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2671         return R;
2672
2673     if (isa<PHINode>(Op0))
2674       if (Instruction *NV = FoldOpIntoPhi(I))
2675         return NV;
2676   }
2677
2678   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2679     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2680       return BinaryOperator::CreateMul(Op0v, Op1v);
2681
2682   // (X / Y) *  Y = X - (X % Y)
2683   // (X / Y) * -Y = (X % Y) - X
2684   {
2685     Value *Op1 = I.getOperand(1);
2686     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2687     if (!BO ||
2688         (BO->getOpcode() != Instruction::UDiv && 
2689          BO->getOpcode() != Instruction::SDiv)) {
2690       Op1 = Op0;
2691       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2692     }
2693     Value *Neg = dyn_castNegVal(Op1);
2694     if (BO && BO->hasOneUse() &&
2695         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2696         (BO->getOpcode() == Instruction::UDiv ||
2697          BO->getOpcode() == Instruction::SDiv)) {
2698       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2699
2700       // If the division is exact, X % Y is zero.
2701       if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2702         if (SDiv->isExact()) {
2703           if (Op1BO == Op1)
2704             return ReplaceInstUsesWith(I, Op0BO);
2705           else
2706             return BinaryOperator::CreateNeg(Op0BO);
2707         }
2708
2709       Value *Rem;
2710       if (BO->getOpcode() == Instruction::UDiv)
2711         Rem = Builder->CreateURem(Op0BO, Op1BO);
2712       else
2713         Rem = Builder->CreateSRem(Op0BO, Op1BO);
2714       Rem->takeName(BO);
2715
2716       if (Op1BO == Op1)
2717         return BinaryOperator::CreateSub(Op0BO, Rem);
2718       return BinaryOperator::CreateSub(Rem, Op0BO);
2719     }
2720   }
2721
2722   if (I.getType() == Type::getInt1Ty(*Context))
2723     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2724
2725   // If one of the operands of the multiply is a cast from a boolean value, then
2726   // we know the bool is either zero or one, so this is a 'masking' multiply.
2727   // See if we can simplify things based on how the boolean was originally
2728   // formed.
2729   CastInst *BoolCast = 0;
2730   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2731     if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
2732       BoolCast = CI;
2733   if (!BoolCast)
2734     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2735       if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
2736         BoolCast = CI;
2737   if (BoolCast) {
2738     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2739       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2740       const Type *SCOpTy = SCIOp0->getType();
2741       bool TIS = false;
2742       
2743       // If the icmp is true iff the sign bit of X is set, then convert this
2744       // multiply into a shift/and combination.
2745       if (isa<ConstantInt>(SCIOp1) &&
2746           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2747           TIS) {
2748         // Shift the X value right to turn it into "all signbits".
2749         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2750                                           SCOpTy->getPrimitiveSizeInBits()-1);
2751         Value *V = Builder->CreateAShr(SCIOp0, Amt,
2752                                     BoolCast->getOperand(0)->getName()+".mask");
2753
2754         // If the multiply type is not the same as the source type, sign extend
2755         // or truncate to the multiply type.
2756         if (I.getType() != V->getType())
2757           V = Builder->CreateIntCast(V, I.getType(), true);
2758
2759         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2760         return BinaryOperator::CreateAnd(V, OtherOp);
2761       }
2762     }
2763   }
2764
2765   return Changed ? &I : 0;
2766 }
2767
2768 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2769   bool Changed = SimplifyCommutative(I);
2770   Value *Op0 = I.getOperand(0);
2771
2772   // Simplify mul instructions with a constant RHS...
2773   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2774     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2775       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2776       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2777       if (Op1F->isExactlyValue(1.0))
2778         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2779     } else if (isa<VectorType>(Op1->getType())) {
2780       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2781         // As above, vector X*splat(1.0) -> X in all defined cases.
2782         if (Constant *Splat = Op1V->getSplatValue()) {
2783           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2784             if (F->isExactlyValue(1.0))
2785               return ReplaceInstUsesWith(I, Op0);
2786         }
2787       }
2788     }
2789
2790     // Try to fold constant mul into select arguments.
2791     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2792       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2793         return R;
2794
2795     if (isa<PHINode>(Op0))
2796       if (Instruction *NV = FoldOpIntoPhi(I))
2797         return NV;
2798   }
2799
2800   if (Value *Op0v = dyn_castFNegVal(Op0))     // -X * -Y = X*Y
2801     if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
2802       return BinaryOperator::CreateFMul(Op0v, Op1v);
2803
2804   return Changed ? &I : 0;
2805 }
2806
2807 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2808 /// instruction.
2809 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2810   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2811   
2812   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2813   int NonNullOperand = -1;
2814   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2815     if (ST->isNullValue())
2816       NonNullOperand = 2;
2817   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2818   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2819     if (ST->isNullValue())
2820       NonNullOperand = 1;
2821   
2822   if (NonNullOperand == -1)
2823     return false;
2824   
2825   Value *SelectCond = SI->getOperand(0);
2826   
2827   // Change the div/rem to use 'Y' instead of the select.
2828   I.setOperand(1, SI->getOperand(NonNullOperand));
2829   
2830   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2831   // problem.  However, the select, or the condition of the select may have
2832   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2833   // propagate the known value for the select into other uses of it, and
2834   // propagate a known value of the condition into its other users.
2835   
2836   // If the select and condition only have a single use, don't bother with this,
2837   // early exit.
2838   if (SI->use_empty() && SelectCond->hasOneUse())
2839     return true;
2840   
2841   // Scan the current block backward, looking for other uses of SI.
2842   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2843   
2844   while (BBI != BBFront) {
2845     --BBI;
2846     // If we found a call to a function, we can't assume it will return, so
2847     // information from below it cannot be propagated above it.
2848     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2849       break;
2850     
2851     // Replace uses of the select or its condition with the known values.
2852     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2853          I != E; ++I) {
2854       if (*I == SI) {
2855         *I = SI->getOperand(NonNullOperand);
2856         Worklist.Add(BBI);
2857       } else if (*I == SelectCond) {
2858         *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2859                                    ConstantInt::getFalse(*Context);
2860         Worklist.Add(BBI);
2861       }
2862     }
2863     
2864     // If we past the instruction, quit looking for it.
2865     if (&*BBI == SI)
2866       SI = 0;
2867     if (&*BBI == SelectCond)
2868       SelectCond = 0;
2869     
2870     // If we ran out of things to eliminate, break out of the loop.
2871     if (SelectCond == 0 && SI == 0)
2872       break;
2873     
2874   }
2875   return true;
2876 }
2877
2878
2879 /// This function implements the transforms on div instructions that work
2880 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2881 /// used by the visitors to those instructions.
2882 /// @brief Transforms common to all three div instructions
2883 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2884   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2885
2886   // undef / X -> 0        for integer.
2887   // undef / X -> undef    for FP (the undef could be a snan).
2888   if (isa<UndefValue>(Op0)) {
2889     if (Op0->getType()->isFPOrFPVector())
2890       return ReplaceInstUsesWith(I, Op0);
2891     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2892   }
2893
2894   // X / undef -> undef
2895   if (isa<UndefValue>(Op1))
2896     return ReplaceInstUsesWith(I, Op1);
2897
2898   return 0;
2899 }
2900
2901 /// This function implements the transforms common to both integer division
2902 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2903 /// division instructions.
2904 /// @brief Common integer divide transforms
2905 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2906   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2907
2908   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2909   if (Op0 == Op1) {
2910     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2911       Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
2912       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2913       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2914     }
2915
2916     Constant *CI = ConstantInt::get(I.getType(), 1);
2917     return ReplaceInstUsesWith(I, CI);
2918   }
2919   
2920   if (Instruction *Common = commonDivTransforms(I))
2921     return Common;
2922   
2923   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2924   // This does not apply for fdiv.
2925   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2926     return &I;
2927
2928   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2929     // div X, 1 == X
2930     if (RHS->equalsInt(1))
2931       return ReplaceInstUsesWith(I, Op0);
2932
2933     // (X / C1) / C2  -> X / (C1*C2)
2934     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2935       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2936         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2937           if (MultiplyOverflows(RHS, LHSRHS,
2938                                 I.getOpcode()==Instruction::SDiv))
2939             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2940           else 
2941             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2942                                       ConstantExpr::getMul(RHS, LHSRHS));
2943         }
2944
2945     if (!RHS->isZero()) { // avoid X udiv 0
2946       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2947         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2948           return R;
2949       if (isa<PHINode>(Op0))
2950         if (Instruction *NV = FoldOpIntoPhi(I))
2951           return NV;
2952     }
2953   }
2954
2955   // 0 / X == 0, we don't need to preserve faults!
2956   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2957     if (LHS->equalsInt(0))
2958       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2959
2960   // It can't be division by zero, hence it must be division by one.
2961   if (I.getType() == Type::getInt1Ty(*Context))
2962     return ReplaceInstUsesWith(I, Op0);
2963
2964   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2965     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2966       // div X, 1 == X
2967       if (X->isOne())
2968         return ReplaceInstUsesWith(I, Op0);
2969   }
2970
2971   return 0;
2972 }
2973
2974 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2975   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2976
2977   // Handle the integer div common cases
2978   if (Instruction *Common = commonIDivTransforms(I))
2979     return Common;
2980
2981   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2982     // X udiv C^2 -> X >> C
2983     // Check to see if this is an unsigned division with an exact power of 2,
2984     // if so, convert to a right shift.
2985     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2986       return BinaryOperator::CreateLShr(Op0, 
2987             ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2988
2989     // X udiv C, where C >= signbit
2990     if (C->getValue().isNegative()) {
2991       Value *IC = Builder->CreateICmpULT( Op0, C);
2992       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
2993                                 ConstantInt::get(I.getType(), 1));
2994     }
2995   }
2996
2997   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2998   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2999     if (RHSI->getOpcode() == Instruction::Shl &&
3000         isa<ConstantInt>(RHSI->getOperand(0))) {
3001       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3002       if (C1.isPowerOf2()) {
3003         Value *N = RHSI->getOperand(1);
3004         const Type *NTy = N->getType();
3005         if (uint32_t C2 = C1.logBase2())
3006           N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
3007         return BinaryOperator::CreateLShr(Op0, N);
3008       }
3009     }
3010   }
3011   
3012   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3013   // where C1&C2 are powers of two.
3014   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3015     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3016       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3017         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3018         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3019           // Compute the shift amounts
3020           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3021           // Construct the "on true" case of the select
3022           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3023           Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
3024   
3025           // Construct the "on false" case of the select
3026           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3027           Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
3028
3029           // construct the select instruction and return it.
3030           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3031         }
3032       }
3033   return 0;
3034 }
3035
3036 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3037   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3038
3039   // Handle the integer div common cases
3040   if (Instruction *Common = commonIDivTransforms(I))
3041     return Common;
3042
3043   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3044     // sdiv X, -1 == -X
3045     if (RHS->isAllOnesValue())
3046       return BinaryOperator::CreateNeg(Op0);
3047
3048     // sdiv X, C  -->  ashr X, log2(C)
3049     if (cast<SDivOperator>(&I)->isExact() &&
3050         RHS->getValue().isNonNegative() &&
3051         RHS->getValue().isPowerOf2()) {
3052       Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3053                                             RHS->getValue().exactLogBase2());
3054       return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3055     }
3056
3057     // -X/C  -->  X/-C  provided the negation doesn't overflow.
3058     if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3059       if (isa<Constant>(Sub->getOperand(0)) &&
3060           cast<Constant>(Sub->getOperand(0))->isNullValue() &&
3061           Sub->hasNoSignedWrap())
3062         return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3063                                           ConstantExpr::getNeg(RHS));
3064   }
3065
3066   // If the sign bits of both operands are zero (i.e. we can prove they are
3067   // unsigned inputs), turn this into a udiv.
3068   if (I.getType()->isInteger()) {
3069     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3070     if (MaskedValueIsZero(Op0, Mask)) {
3071       if (MaskedValueIsZero(Op1, Mask)) {
3072         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3073         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3074       }
3075       ConstantInt *ShiftedInt;
3076       if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
3077           ShiftedInt->getValue().isPowerOf2()) {
3078         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3079         // Safe because the only negative value (1 << Y) can take on is
3080         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3081         // the sign bit set.
3082         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3083       }
3084     }
3085   }
3086   
3087   return 0;
3088 }
3089
3090 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3091   return commonDivTransforms(I);
3092 }
3093
3094 /// This function implements the transforms on rem instructions that work
3095 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3096 /// is used by the visitors to those instructions.
3097 /// @brief Transforms common to all three rem instructions
3098 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3099   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3100
3101   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3102     if (I.getType()->isFPOrFPVector())
3103       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3104     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3105   }
3106   if (isa<UndefValue>(Op1))
3107     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3108
3109   // Handle cases involving: rem X, (select Cond, Y, Z)
3110   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3111     return &I;
3112
3113   return 0;
3114 }
3115
3116 /// This function implements the transforms common to both integer remainder
3117 /// instructions (urem and srem). It is called by the visitors to those integer
3118 /// remainder instructions.
3119 /// @brief Common integer remainder transforms
3120 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3121   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3122
3123   if (Instruction *common = commonRemTransforms(I))
3124     return common;
3125
3126   // 0 % X == 0 for integer, we don't need to preserve faults!
3127   if (Constant *LHS = dyn_cast<Constant>(Op0))
3128     if (LHS->isNullValue())
3129       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3130
3131   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3132     // X % 0 == undef, we don't need to preserve faults!
3133     if (RHS->equalsInt(0))
3134       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3135     
3136     if (RHS->equalsInt(1))  // X % 1 == 0
3137       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3138
3139     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3140       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3141         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3142           return R;
3143       } else if (isa<PHINode>(Op0I)) {
3144         if (Instruction *NV = FoldOpIntoPhi(I))
3145           return NV;
3146       }
3147
3148       // See if we can fold away this rem instruction.
3149       if (SimplifyDemandedInstructionBits(I))
3150         return &I;
3151     }
3152   }
3153
3154   return 0;
3155 }
3156
3157 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3158   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3159
3160   if (Instruction *common = commonIRemTransforms(I))
3161     return common;
3162   
3163   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3164     // X urem C^2 -> X and C
3165     // Check to see if this is an unsigned remainder with an exact power of 2,
3166     // if so, convert to a bitwise and.
3167     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3168       if (C->getValue().isPowerOf2())
3169         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3170   }
3171
3172   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3173     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3174     if (RHSI->getOpcode() == Instruction::Shl &&
3175         isa<ConstantInt>(RHSI->getOperand(0))) {
3176       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3177         Constant *N1 = Constant::getAllOnesValue(I.getType());
3178         Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
3179         return BinaryOperator::CreateAnd(Op0, Add);
3180       }
3181     }
3182   }
3183
3184   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3185   // where C1&C2 are powers of two.
3186   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3187     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3188       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3189         // STO == 0 and SFO == 0 handled above.
3190         if ((STO->getValue().isPowerOf2()) && 
3191             (SFO->getValue().isPowerOf2())) {
3192           Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3193                                               SI->getName()+".t");
3194           Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3195                                                SI->getName()+".f");
3196           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3197         }
3198       }
3199   }
3200   
3201   return 0;
3202 }
3203
3204 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3205   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3206
3207   // Handle the integer rem common cases
3208   if (Instruction *Common = commonIRemTransforms(I))
3209     return Common;
3210   
3211   if (Value *RHSNeg = dyn_castNegVal(Op1))
3212     if (!isa<Constant>(RHSNeg) ||
3213         (isa<ConstantInt>(RHSNeg) &&
3214          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3215       // X % -Y -> X % Y
3216       Worklist.AddValue(I.getOperand(1));
3217       I.setOperand(1, RHSNeg);
3218       return &I;
3219     }
3220
3221   // If the sign bits of both operands are zero (i.e. we can prove they are
3222   // unsigned inputs), turn this into a urem.
3223   if (I.getType()->isInteger()) {
3224     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3225     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3226       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3227       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3228     }
3229   }
3230
3231   // If it's a constant vector, flip any negative values positive.
3232   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3233     unsigned VWidth = RHSV->getNumOperands();
3234
3235     bool hasNegative = false;
3236     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3237       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3238         if (RHS->getValue().isNegative())
3239           hasNegative = true;
3240
3241     if (hasNegative) {
3242       std::vector<Constant *> Elts(VWidth);
3243       for (unsigned i = 0; i != VWidth; ++i) {
3244         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3245           if (RHS->getValue().isNegative())
3246             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3247           else
3248             Elts[i] = RHS;
3249         }
3250       }
3251
3252       Constant *NewRHSV = ConstantVector::get(Elts);
3253       if (NewRHSV != RHSV) {
3254         Worklist.AddValue(I.getOperand(1));
3255         I.setOperand(1, NewRHSV);
3256         return &I;
3257       }
3258     }
3259   }
3260
3261   return 0;
3262 }
3263
3264 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3265   return commonRemTransforms(I);
3266 }
3267
3268 // isOneBitSet - Return true if there is exactly one bit set in the specified
3269 // constant.
3270 static bool isOneBitSet(const ConstantInt *CI) {
3271   return CI->getValue().isPowerOf2();
3272 }
3273
3274 // isHighOnes - Return true if the constant is of the form 1+0+.
3275 // This is the same as lowones(~X).
3276 static bool isHighOnes(const ConstantInt *CI) {
3277   return (~CI->getValue() + 1).isPowerOf2();
3278 }
3279
3280 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3281 /// are carefully arranged to allow folding of expressions such as:
3282 ///
3283 ///      (A < B) | (A > B) --> (A != B)
3284 ///
3285 /// Note that this is only valid if the first and second predicates have the
3286 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3287 ///
3288 /// Three bits are used to represent the condition, as follows:
3289 ///   0  A > B
3290 ///   1  A == B
3291 ///   2  A < B
3292 ///
3293 /// <=>  Value  Definition
3294 /// 000     0   Always false
3295 /// 001     1   A >  B
3296 /// 010     2   A == B
3297 /// 011     3   A >= B
3298 /// 100     4   A <  B
3299 /// 101     5   A != B
3300 /// 110     6   A <= B
3301 /// 111     7   Always true
3302 ///  
3303 static unsigned getICmpCode(const ICmpInst *ICI) {
3304   switch (ICI->getPredicate()) {
3305     // False -> 0
3306   case ICmpInst::ICMP_UGT: return 1;  // 001
3307   case ICmpInst::ICMP_SGT: return 1;  // 001
3308   case ICmpInst::ICMP_EQ:  return 2;  // 010
3309   case ICmpInst::ICMP_UGE: return 3;  // 011
3310   case ICmpInst::ICMP_SGE: return 3;  // 011
3311   case ICmpInst::ICMP_ULT: return 4;  // 100
3312   case ICmpInst::ICMP_SLT: return 4;  // 100
3313   case ICmpInst::ICMP_NE:  return 5;  // 101
3314   case ICmpInst::ICMP_ULE: return 6;  // 110
3315   case ICmpInst::ICMP_SLE: return 6;  // 110
3316     // True -> 7
3317   default:
3318     llvm_unreachable("Invalid ICmp predicate!");
3319     return 0;
3320   }
3321 }
3322
3323 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3324 /// predicate into a three bit mask. It also returns whether it is an ordered
3325 /// predicate by reference.
3326 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3327   isOrdered = false;
3328   switch (CC) {
3329   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3330   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3331   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3332   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3333   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3334   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3335   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3336   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3337   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3338   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3339   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3340   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3341   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3342   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3343     // True -> 7
3344   default:
3345     // Not expecting FCMP_FALSE and FCMP_TRUE;
3346     llvm_unreachable("Unexpected FCmp predicate!");
3347     return 0;
3348   }
3349 }
3350
3351 /// getICmpValue - This is the complement of getICmpCode, which turns an
3352 /// opcode and two operands into either a constant true or false, or a brand 
3353 /// new ICmp instruction. The sign is passed in to determine which kind
3354 /// of predicate to use in the new icmp instruction.
3355 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3356                            LLVMContext *Context) {
3357   switch (code) {
3358   default: llvm_unreachable("Illegal ICmp code!");
3359   case  0: return ConstantInt::getFalse(*Context);
3360   case  1: 
3361     if (sign)
3362       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3363     else
3364       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3365   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3366   case  3: 
3367     if (sign)
3368       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3369     else
3370       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3371   case  4: 
3372     if (sign)
3373       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3374     else
3375       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3376   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3377   case  6: 
3378     if (sign)
3379       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3380     else
3381       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3382   case  7: return ConstantInt::getTrue(*Context);
3383   }
3384 }
3385
3386 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3387 /// opcode and two operands into either a FCmp instruction. isordered is passed
3388 /// in to determine which kind of predicate to use in the new fcmp instruction.
3389 static Value *getFCmpValue(bool isordered, unsigned code,
3390                            Value *LHS, Value *RHS, LLVMContext *Context) {
3391   switch (code) {
3392   default: llvm_unreachable("Illegal FCmp code!");
3393   case  0:
3394     if (isordered)
3395       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3396     else
3397       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3398   case  1: 
3399     if (isordered)
3400       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3401     else
3402       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3403   case  2: 
3404     if (isordered)
3405       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3406     else
3407       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3408   case  3: 
3409     if (isordered)
3410       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3411     else
3412       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3413   case  4: 
3414     if (isordered)
3415       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3416     else
3417       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3418   case  5: 
3419     if (isordered)
3420       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3421     else
3422       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3423   case  6: 
3424     if (isordered)
3425       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3426     else
3427       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3428   case  7: return ConstantInt::getTrue(*Context);
3429   }
3430 }
3431
3432 /// PredicatesFoldable - Return true if both predicates match sign or if at
3433 /// least one of them is an equality comparison (which is signless).
3434 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3435   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3436          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3437          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3438 }
3439
3440 namespace { 
3441 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3442 struct FoldICmpLogical {
3443   InstCombiner &IC;
3444   Value *LHS, *RHS;
3445   ICmpInst::Predicate pred;
3446   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3447     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3448       pred(ICI->getPredicate()) {}
3449   bool shouldApply(Value *V) const {
3450     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3451       if (PredicatesFoldable(pred, ICI->getPredicate()))
3452         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3453                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3454     return false;
3455   }
3456   Instruction *apply(Instruction &Log) const {
3457     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3458     if (ICI->getOperand(0) != LHS) {
3459       assert(ICI->getOperand(1) == LHS);
3460       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3461     }
3462
3463     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3464     unsigned LHSCode = getICmpCode(ICI);
3465     unsigned RHSCode = getICmpCode(RHSICI);
3466     unsigned Code;
3467     switch (Log.getOpcode()) {
3468     case Instruction::And: Code = LHSCode & RHSCode; break;
3469     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3470     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3471     default: llvm_unreachable("Illegal logical opcode!"); return 0;
3472     }
3473
3474     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3475                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3476       
3477     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3478     if (Instruction *I = dyn_cast<Instruction>(RV))
3479       return I;
3480     // Otherwise, it's a constant boolean value...
3481     return IC.ReplaceInstUsesWith(Log, RV);
3482   }
3483 };
3484 } // end anonymous namespace
3485
3486 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3487 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3488 // guaranteed to be a binary operator.
3489 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3490                                     ConstantInt *OpRHS,
3491                                     ConstantInt *AndRHS,
3492                                     BinaryOperator &TheAnd) {
3493   Value *X = Op->getOperand(0);
3494   Constant *Together = 0;
3495   if (!Op->isShift())
3496     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3497
3498   switch (Op->getOpcode()) {
3499   case Instruction::Xor:
3500     if (Op->hasOneUse()) {
3501       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3502       Value *And = Builder->CreateAnd(X, AndRHS);
3503       And->takeName(Op);
3504       return BinaryOperator::CreateXor(And, Together);
3505     }
3506     break;
3507   case Instruction::Or:
3508     if (Together == AndRHS) // (X | C) & C --> C
3509       return ReplaceInstUsesWith(TheAnd, AndRHS);
3510
3511     if (Op->hasOneUse() && Together != OpRHS) {
3512       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3513       Value *Or = Builder->CreateOr(X, Together);
3514       Or->takeName(Op);
3515       return BinaryOperator::CreateAnd(Or, AndRHS);
3516     }
3517     break;
3518   case Instruction::Add:
3519     if (Op->hasOneUse()) {
3520       // Adding a one to a single bit bit-field should be turned into an XOR
3521       // of the bit.  First thing to check is to see if this AND is with a
3522       // single bit constant.
3523       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3524
3525       // If there is only one bit set...
3526       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3527         // Ok, at this point, we know that we are masking the result of the
3528         // ADD down to exactly one bit.  If the constant we are adding has
3529         // no bits set below this bit, then we can eliminate the ADD.
3530         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3531
3532         // Check to see if any bits below the one bit set in AndRHSV are set.
3533         if ((AddRHS & (AndRHSV-1)) == 0) {
3534           // If not, the only thing that can effect the output of the AND is
3535           // the bit specified by AndRHSV.  If that bit is set, the effect of
3536           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3537           // no effect.
3538           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3539             TheAnd.setOperand(0, X);
3540             return &TheAnd;
3541           } else {
3542             // Pull the XOR out of the AND.
3543             Value *NewAnd = Builder->CreateAnd(X, AndRHS);
3544             NewAnd->takeName(Op);
3545             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3546           }
3547         }
3548       }
3549     }
3550     break;
3551
3552   case Instruction::Shl: {
3553     // We know that the AND will not produce any of the bits shifted in, so if
3554     // the anded constant includes them, clear them now!
3555     //
3556     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3557     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3558     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3559     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3560
3561     if (CI->getValue() == ShlMask) { 
3562     // Masking out bits that the shift already masks
3563       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3564     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3565       TheAnd.setOperand(1, CI);
3566       return &TheAnd;
3567     }
3568     break;
3569   }
3570   case Instruction::LShr:
3571   {
3572     // We know that the AND will not produce any of the bits shifted in, so if
3573     // the anded constant includes them, clear them now!  This only applies to
3574     // unsigned shifts, because a signed shr may bring in set bits!
3575     //
3576     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3577     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3578     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3579     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3580
3581     if (CI->getValue() == ShrMask) {   
3582     // Masking out bits that the shift already masks.
3583       return ReplaceInstUsesWith(TheAnd, Op);
3584     } else if (CI != AndRHS) {
3585       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3586       return &TheAnd;
3587     }
3588     break;
3589   }
3590   case Instruction::AShr:
3591     // Signed shr.
3592     // See if this is shifting in some sign extension, then masking it out
3593     // with an and.
3594     if (Op->hasOneUse()) {
3595       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3596       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3597       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3598       Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3599       if (C == AndRHS) {          // Masking out bits shifted in.
3600         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3601         // Make the argument unsigned.
3602         Value *ShVal = Op->getOperand(0);
3603         ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
3604         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3605       }
3606     }
3607     break;
3608   }
3609   return 0;
3610 }
3611
3612
3613 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3614 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3615 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3616 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3617 /// insert new instructions.
3618 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3619                                            bool isSigned, bool Inside, 
3620                                            Instruction &IB) {
3621   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3622             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3623          "Lo is not <= Hi in range emission code!");
3624     
3625   if (Inside) {
3626     if (Lo == Hi)  // Trivially false.
3627       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3628
3629     // V >= Min && V < Hi --> V < Hi
3630     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3631       ICmpInst::Predicate pred = (isSigned ? 
3632         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3633       return new ICmpInst(pred, V, Hi);
3634     }
3635
3636     // Emit V-Lo <u Hi-Lo
3637     Constant *NegLo = ConstantExpr::getNeg(Lo);
3638     Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3639     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3640     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3641   }
3642
3643   if (Lo == Hi)  // Trivially true.
3644     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3645
3646   // V < Min || V >= Hi -> V > Hi-1
3647   Hi = SubOne(cast<ConstantInt>(Hi));
3648   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3649     ICmpInst::Predicate pred = (isSigned ? 
3650         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3651     return new ICmpInst(pred, V, Hi);
3652   }
3653
3654   // Emit V-Lo >u Hi-1-Lo
3655   // Note that Hi has already had one subtracted from it, above.
3656   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3657   Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3658   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3659   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3660 }
3661
3662 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3663 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3664 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3665 // not, since all 1s are not contiguous.
3666 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3667   const APInt& V = Val->getValue();
3668   uint32_t BitWidth = Val->getType()->getBitWidth();
3669   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3670
3671   // look for the first zero bit after the run of ones
3672   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3673   // look for the first non-zero bit
3674   ME = V.getActiveBits(); 
3675   return true;
3676 }
3677
3678 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3679 /// where isSub determines whether the operator is a sub.  If we can fold one of
3680 /// the following xforms:
3681 /// 
3682 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3683 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3684 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3685 ///
3686 /// return (A +/- B).
3687 ///
3688 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3689                                         ConstantInt *Mask, bool isSub,
3690                                         Instruction &I) {
3691   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3692   if (!LHSI || LHSI->getNumOperands() != 2 ||
3693       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3694
3695   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3696
3697   switch (LHSI->getOpcode()) {
3698   default: return 0;
3699   case Instruction::And:
3700     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3701       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3702       if ((Mask->getValue().countLeadingZeros() + 
3703            Mask->getValue().countPopulation()) == 
3704           Mask->getValue().getBitWidth())
3705         break;
3706
3707       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3708       // part, we don't need any explicit masks to take them out of A.  If that
3709       // is all N is, ignore it.
3710       uint32_t MB = 0, ME = 0;
3711       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3712         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3713         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3714         if (MaskedValueIsZero(RHS, Mask))
3715           break;
3716       }
3717     }
3718     return 0;
3719   case Instruction::Or:
3720   case Instruction::Xor:
3721     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3722     if ((Mask->getValue().countLeadingZeros() + 
3723          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3724         && ConstantExpr::getAnd(N, Mask)->isNullValue())
3725       break;
3726     return 0;
3727   }
3728   
3729   if (isSub)
3730     return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3731   return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
3732 }
3733
3734 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3735 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3736                                           ICmpInst *LHS, ICmpInst *RHS) {
3737   Value *Val, *Val2;
3738   ConstantInt *LHSCst, *RHSCst;
3739   ICmpInst::Predicate LHSCC, RHSCC;
3740   
3741   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3742   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3743                          m_ConstantInt(LHSCst))) ||
3744       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3745                          m_ConstantInt(RHSCst))))
3746     return 0;
3747   
3748   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3749   // where C is a power of 2
3750   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3751       LHSCst->getValue().isPowerOf2()) {
3752     Value *NewOr = Builder->CreateOr(Val, Val2);
3753     return new ICmpInst(LHSCC, NewOr, LHSCst);
3754   }
3755   
3756   // From here on, we only handle:
3757   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3758   if (Val != Val2) return 0;
3759   
3760   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3761   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3762       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3763       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3764       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3765     return 0;
3766   
3767   // We can't fold (ugt x, C) & (sgt x, C2).
3768   if (!PredicatesFoldable(LHSCC, RHSCC))
3769     return 0;
3770     
3771   // Ensure that the larger constant is on the RHS.
3772   bool ShouldSwap;
3773   if (ICmpInst::isSignedPredicate(LHSCC) ||
3774       (ICmpInst::isEquality(LHSCC) && 
3775        ICmpInst::isSignedPredicate(RHSCC)))
3776     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3777   else
3778     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3779     
3780   if (ShouldSwap) {
3781     std::swap(LHS, RHS);
3782     std::swap(LHSCst, RHSCst);
3783     std::swap(LHSCC, RHSCC);
3784   }
3785
3786   // At this point, we know we have have two icmp instructions
3787   // comparing a value against two constants and and'ing the result
3788   // together.  Because of the above check, we know that we only have
3789   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3790   // (from the FoldICmpLogical check above), that the two constants 
3791   // are not equal and that the larger constant is on the RHS
3792   assert(LHSCst != RHSCst && "Compares not folded above?");
3793
3794   switch (LHSCC) {
3795   default: llvm_unreachable("Unknown integer condition code!");
3796   case ICmpInst::ICMP_EQ:
3797     switch (RHSCC) {
3798     default: llvm_unreachable("Unknown integer condition code!");
3799     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3800     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3801     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3802       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3803     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3804     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3805     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3806       return ReplaceInstUsesWith(I, LHS);
3807     }
3808   case ICmpInst::ICMP_NE:
3809     switch (RHSCC) {
3810     default: llvm_unreachable("Unknown integer condition code!");
3811     case ICmpInst::ICMP_ULT:
3812       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3813         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3814       break;                        // (X != 13 & X u< 15) -> no change
3815     case ICmpInst::ICMP_SLT:
3816       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3817         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3818       break;                        // (X != 13 & X s< 15) -> no change
3819     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3820     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3821     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3822       return ReplaceInstUsesWith(I, RHS);
3823     case ICmpInst::ICMP_NE:
3824       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3825         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3826         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
3827         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3828                             ConstantInt::get(Add->getType(), 1));
3829       }
3830       break;                        // (X != 13 & X != 15) -> no change
3831     }
3832     break;
3833   case ICmpInst::ICMP_ULT:
3834     switch (RHSCC) {
3835     default: llvm_unreachable("Unknown integer condition code!");
3836     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3837     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3838       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3839     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3840       break;
3841     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3842     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3843       return ReplaceInstUsesWith(I, LHS);
3844     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3845       break;
3846     }
3847     break;
3848   case ICmpInst::ICMP_SLT:
3849     switch (RHSCC) {
3850     default: llvm_unreachable("Unknown integer condition code!");
3851     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3852     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3853       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3854     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3855       break;
3856     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3857     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3858       return ReplaceInstUsesWith(I, LHS);
3859     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3860       break;
3861     }
3862     break;
3863   case ICmpInst::ICMP_UGT:
3864     switch (RHSCC) {
3865     default: llvm_unreachable("Unknown integer condition code!");
3866     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3867     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3868       return ReplaceInstUsesWith(I, RHS);
3869     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3870       break;
3871     case ICmpInst::ICMP_NE:
3872       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3873         return new ICmpInst(LHSCC, Val, RHSCst);
3874       break;                        // (X u> 13 & X != 15) -> no change
3875     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3876       return InsertRangeTest(Val, AddOne(LHSCst),
3877                              RHSCst, false, true, I);
3878     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3879       break;
3880     }
3881     break;
3882   case ICmpInst::ICMP_SGT:
3883     switch (RHSCC) {
3884     default: llvm_unreachable("Unknown integer condition code!");
3885     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3886     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3887       return ReplaceInstUsesWith(I, RHS);
3888     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3889       break;
3890     case ICmpInst::ICMP_NE:
3891       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3892         return new ICmpInst(LHSCC, Val, RHSCst);
3893       break;                        // (X s> 13 & X != 15) -> no change
3894     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3895       return InsertRangeTest(Val, AddOne(LHSCst),
3896                              RHSCst, true, true, I);
3897     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3898       break;
3899     }
3900     break;
3901   }
3902  
3903   return 0;
3904 }
3905
3906 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3907                                           FCmpInst *RHS) {
3908   
3909   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3910       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3911     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3912     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3913       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3914         // If either of the constants are nans, then the whole thing returns
3915         // false.
3916         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3917           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3918         return new FCmpInst(FCmpInst::FCMP_ORD,
3919                             LHS->getOperand(0), RHS->getOperand(0));
3920       }
3921     
3922     // Handle vector zeros.  This occurs because the canonical form of
3923     // "fcmp ord x,x" is "fcmp ord x, 0".
3924     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3925         isa<ConstantAggregateZero>(RHS->getOperand(1)))
3926       return new FCmpInst(FCmpInst::FCMP_ORD,
3927                           LHS->getOperand(0), RHS->getOperand(0));
3928     return 0;
3929   }
3930   
3931   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3932   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3933   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3934   
3935   
3936   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3937     // Swap RHS operands to match LHS.
3938     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3939     std::swap(Op1LHS, Op1RHS);
3940   }
3941   
3942   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3943     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3944     if (Op0CC == Op1CC)
3945       return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
3946     
3947     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
3948       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3949     if (Op0CC == FCmpInst::FCMP_TRUE)
3950       return ReplaceInstUsesWith(I, RHS);
3951     if (Op1CC == FCmpInst::FCMP_TRUE)
3952       return ReplaceInstUsesWith(I, LHS);
3953     
3954     bool Op0Ordered;
3955     bool Op1Ordered;
3956     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3957     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3958     if (Op1Pred == 0) {
3959       std::swap(LHS, RHS);
3960       std::swap(Op0Pred, Op1Pred);
3961       std::swap(Op0Ordered, Op1Ordered);
3962     }
3963     if (Op0Pred == 0) {
3964       // uno && ueq -> uno && (uno || eq) -> ueq
3965       // ord && olt -> ord && (ord && lt) -> olt
3966       if (Op0Ordered == Op1Ordered)
3967         return ReplaceInstUsesWith(I, RHS);
3968       
3969       // uno && oeq -> uno && (ord && eq) -> false
3970       // uno && ord -> false
3971       if (!Op0Ordered)
3972         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3973       // ord && ueq -> ord && (uno || eq) -> oeq
3974       return cast<Instruction>(getFCmpValue(true, Op1Pred,
3975                                             Op0LHS, Op0RHS, Context));
3976     }
3977   }
3978
3979   return 0;
3980 }
3981
3982
3983 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3984   bool Changed = SimplifyCommutative(I);
3985   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3986
3987   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3988     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3989
3990   // and X, X = X
3991   if (Op0 == Op1)
3992     return ReplaceInstUsesWith(I, Op1);
3993
3994   // See if we can simplify any instructions used by the instruction whose sole 
3995   // purpose is to compute bits we don't care about.
3996   if (SimplifyDemandedInstructionBits(I))
3997     return &I;
3998   if (isa<VectorType>(I.getType())) {
3999     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4000       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
4001         return ReplaceInstUsesWith(I, I.getOperand(0));
4002     } else if (isa<ConstantAggregateZero>(Op1)) {
4003       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
4004     }
4005   }
4006
4007   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4008     const APInt& AndRHSMask = AndRHS->getValue();
4009     APInt NotAndRHS(~AndRHSMask);
4010
4011     // Optimize a variety of ((val OP C1) & C2) combinations...
4012     if (isa<BinaryOperator>(Op0)) {
4013       Instruction *Op0I = cast<Instruction>(Op0);
4014       Value *Op0LHS = Op0I->getOperand(0);
4015       Value *Op0RHS = Op0I->getOperand(1);
4016       switch (Op0I->getOpcode()) {
4017       case Instruction::Xor:
4018       case Instruction::Or:
4019         // If the mask is only needed on one incoming arm, push it up.
4020         if (Op0I->hasOneUse()) {
4021           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4022             // Not masking anything out for the LHS, move to RHS.
4023             Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4024                                                Op0RHS->getName()+".masked");
4025             return BinaryOperator::Create(
4026                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4027           }
4028           if (!isa<Constant>(Op0RHS) &&
4029               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4030             // Not masking anything out for the RHS, move to LHS.
4031             Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4032                                                Op0LHS->getName()+".masked");
4033             return BinaryOperator::Create(
4034                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4035           }
4036         }
4037
4038         break;
4039       case Instruction::Add:
4040         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4041         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4042         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4043         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4044           return BinaryOperator::CreateAnd(V, AndRHS);
4045         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4046           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4047         break;
4048
4049       case Instruction::Sub:
4050         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4051         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4052         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4053         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4054           return BinaryOperator::CreateAnd(V, AndRHS);
4055
4056         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4057         // has 1's for all bits that the subtraction with A might affect.
4058         if (Op0I->hasOneUse()) {
4059           uint32_t BitWidth = AndRHSMask.getBitWidth();
4060           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4061           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4062
4063           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4064           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4065               MaskedValueIsZero(Op0LHS, Mask)) {
4066             Value *NewNeg = Builder->CreateNeg(Op0RHS);
4067             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4068           }
4069         }
4070         break;
4071
4072       case Instruction::Shl:
4073       case Instruction::LShr:
4074         // (1 << x) & 1 --> zext(x == 0)
4075         // (1 >> x) & 1 --> zext(x == 0)
4076         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4077           Value *NewICmp =
4078             Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
4079           return new ZExtInst(NewICmp, I.getType());
4080         }
4081         break;
4082       }
4083
4084       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4085         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4086           return Res;
4087     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4088       // If this is an integer truncation or change from signed-to-unsigned, and
4089       // if the source is an and/or with immediate, transform it.  This
4090       // frequently occurs for bitfield accesses.
4091       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4092         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4093             CastOp->getNumOperands() == 2)
4094           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4095             if (CastOp->getOpcode() == Instruction::And) {
4096               // Change: and (cast (and X, C1) to T), C2
4097               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4098               // This will fold the two constants together, which may allow 
4099               // other simplifications.
4100               Value *NewCast = Builder->CreateTruncOrBitCast(
4101                 CastOp->getOperand(0), I.getType(), 
4102                 CastOp->getName()+".shrunk");
4103               // trunc_or_bitcast(C1)&C2
4104               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4105               C3 = ConstantExpr::getAnd(C3, AndRHS);
4106               return BinaryOperator::CreateAnd(NewCast, C3);
4107             } else if (CastOp->getOpcode() == Instruction::Or) {
4108               // Change: and (cast (or X, C1) to T), C2
4109               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4110               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4111               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
4112                 // trunc(C1)&C2
4113                 return ReplaceInstUsesWith(I, AndRHS);
4114             }
4115           }
4116       }
4117     }
4118
4119     // Try to fold constant and into select arguments.
4120     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4121       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4122         return R;
4123     if (isa<PHINode>(Op0))
4124       if (Instruction *NV = FoldOpIntoPhi(I))
4125         return NV;
4126   }
4127
4128   Value *Op0NotVal = dyn_castNotVal(Op0);
4129   Value *Op1NotVal = dyn_castNotVal(Op1);
4130
4131   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4132     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4133
4134   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4135   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4136     Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4137                                   I.getName()+".demorgan");
4138     return BinaryOperator::CreateNot(Or);
4139   }
4140   
4141   {
4142     Value *A = 0, *B = 0, *C = 0, *D = 0;
4143     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4144       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4145         return ReplaceInstUsesWith(I, Op1);
4146     
4147       // (A|B) & ~(A&B) -> A^B
4148       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4149         if ((A == C && B == D) || (A == D && B == C))
4150           return BinaryOperator::CreateXor(A, B);
4151       }
4152     }
4153     
4154     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4155       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4156         return ReplaceInstUsesWith(I, Op0);
4157
4158       // ~(A&B) & (A|B) -> A^B
4159       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4160         if ((A == C && B == D) || (A == D && B == C))
4161           return BinaryOperator::CreateXor(A, B);
4162       }
4163     }
4164     
4165     if (Op0->hasOneUse() &&
4166         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4167       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4168         I.swapOperands();     // Simplify below
4169         std::swap(Op0, Op1);
4170       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4171         cast<BinaryOperator>(Op0)->swapOperands();
4172         I.swapOperands();     // Simplify below
4173         std::swap(Op0, Op1);
4174       }
4175     }
4176
4177     if (Op1->hasOneUse() &&
4178         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4179       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4180         cast<BinaryOperator>(Op1)->swapOperands();
4181         std::swap(A, B);
4182       }
4183       if (A == Op0)                                // A&(A^B) -> A & ~B
4184         return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
4185     }
4186
4187     // (A&((~A)|B)) -> A&B
4188     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4189         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4190       return BinaryOperator::CreateAnd(A, Op1);
4191     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4192         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4193       return BinaryOperator::CreateAnd(A, Op0);
4194   }
4195   
4196   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4197     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4198     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4199       return R;
4200
4201     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4202       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4203         return Res;
4204   }
4205
4206   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4207   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4208     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4209       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4210         const Type *SrcTy = Op0C->getOperand(0)->getType();
4211         if (SrcTy == Op1C->getOperand(0)->getType() &&
4212             SrcTy->isIntOrIntVector() &&
4213             // Only do this if the casts both really cause code to be generated.
4214             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4215                               I.getType(), TD) &&
4216             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4217                               I.getType(), TD)) {
4218           Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4219                                             Op1C->getOperand(0), I.getName());
4220           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4221         }
4222       }
4223     
4224   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4225   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4226     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4227       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4228           SI0->getOperand(1) == SI1->getOperand(1) &&
4229           (SI0->hasOneUse() || SI1->hasOneUse())) {
4230         Value *NewOp =
4231           Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4232                              SI0->getName());
4233         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4234                                       SI1->getOperand(1));
4235       }
4236   }
4237
4238   // If and'ing two fcmp, try combine them into one.
4239   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4240     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4241       if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4242         return Res;
4243   }
4244
4245   return Changed ? &I : 0;
4246 }
4247
4248 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4249 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4250 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4251 /// the expression came from the corresponding "byte swapped" byte in some other
4252 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4253 /// we know that the expression deposits the low byte of %X into the high byte
4254 /// of the bswap result and that all other bytes are zero.  This expression is
4255 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4256 /// match.
4257 ///
4258 /// This function returns true if the match was unsuccessful and false if so.
4259 /// On entry to the function the "OverallLeftShift" is a signed integer value
4260 /// indicating the number of bytes that the subexpression is later shifted.  For
4261 /// example, if the expression is later right shifted by 16 bits, the
4262 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4263 /// byte of ByteValues is actually being set.
4264 ///
4265 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4266 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4267 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4268 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4269 /// always in the local (OverallLeftShift) coordinate space.
4270 ///
4271 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4272                               SmallVector<Value*, 8> &ByteValues) {
4273   if (Instruction *I = dyn_cast<Instruction>(V)) {
4274     // If this is an or instruction, it may be an inner node of the bswap.
4275     if (I->getOpcode() == Instruction::Or) {
4276       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4277                                ByteValues) ||
4278              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4279                                ByteValues);
4280     }
4281   
4282     // If this is a logical shift by a constant multiple of 8, recurse with
4283     // OverallLeftShift and ByteMask adjusted.
4284     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4285       unsigned ShAmt = 
4286         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4287       // Ensure the shift amount is defined and of a byte value.
4288       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4289         return true;
4290
4291       unsigned ByteShift = ShAmt >> 3;
4292       if (I->getOpcode() == Instruction::Shl) {
4293         // X << 2 -> collect(X, +2)
4294         OverallLeftShift += ByteShift;
4295         ByteMask >>= ByteShift;
4296       } else {
4297         // X >>u 2 -> collect(X, -2)
4298         OverallLeftShift -= ByteShift;
4299         ByteMask <<= ByteShift;
4300         ByteMask &= (~0U >> (32-ByteValues.size()));
4301       }
4302
4303       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4304       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4305
4306       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4307                                ByteValues);
4308     }
4309
4310     // If this is a logical 'and' with a mask that clears bytes, clear the
4311     // corresponding bytes in ByteMask.
4312     if (I->getOpcode() == Instruction::And &&
4313         isa<ConstantInt>(I->getOperand(1))) {
4314       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4315       unsigned NumBytes = ByteValues.size();
4316       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4317       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4318       
4319       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4320         // If this byte is masked out by a later operation, we don't care what
4321         // the and mask is.
4322         if ((ByteMask & (1 << i)) == 0)
4323           continue;
4324         
4325         // If the AndMask is all zeros for this byte, clear the bit.
4326         APInt MaskB = AndMask & Byte;
4327         if (MaskB == 0) {
4328           ByteMask &= ~(1U << i);
4329           continue;
4330         }
4331         
4332         // If the AndMask is not all ones for this byte, it's not a bytezap.
4333         if (MaskB != Byte)
4334           return true;
4335
4336         // Otherwise, this byte is kept.
4337       }
4338
4339       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4340                                ByteValues);
4341     }
4342   }
4343   
4344   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4345   // the input value to the bswap.  Some observations: 1) if more than one byte
4346   // is demanded from this input, then it could not be successfully assembled
4347   // into a byteswap.  At least one of the two bytes would not be aligned with
4348   // their ultimate destination.
4349   if (!isPowerOf2_32(ByteMask)) return true;
4350   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4351   
4352   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4353   // is demanded, it needs to go into byte 0 of the result.  This means that the
4354   // byte needs to be shifted until it lands in the right byte bucket.  The
4355   // shift amount depends on the position: if the byte is coming from the high
4356   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4357   // low part, it must be shifted left.
4358   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4359   if (InputByteNo < ByteValues.size()/2) {
4360     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4361       return true;
4362   } else {
4363     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4364       return true;
4365   }
4366   
4367   // If the destination byte value is already defined, the values are or'd
4368   // together, which isn't a bswap (unless it's an or of the same bits).
4369   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4370     return true;
4371   ByteValues[DestByteNo] = V;
4372   return false;
4373 }
4374
4375 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4376 /// If so, insert the new bswap intrinsic and return it.
4377 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4378   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4379   if (!ITy || ITy->getBitWidth() % 16 || 
4380       // ByteMask only allows up to 32-byte values.
4381       ITy->getBitWidth() > 32*8) 
4382     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4383   
4384   /// ByteValues - For each byte of the result, we keep track of which value
4385   /// defines each byte.
4386   SmallVector<Value*, 8> ByteValues;
4387   ByteValues.resize(ITy->getBitWidth()/8);
4388     
4389   // Try to find all the pieces corresponding to the bswap.
4390   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4391   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4392     return 0;
4393   
4394   // Check to see if all of the bytes come from the same value.
4395   Value *V = ByteValues[0];
4396   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4397   
4398   // Check to make sure that all of the bytes come from the same value.
4399   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4400     if (ByteValues[i] != V)
4401       return 0;
4402   const Type *Tys[] = { ITy };
4403   Module *M = I.getParent()->getParent()->getParent();
4404   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4405   return CallInst::Create(F, V);
4406 }
4407
4408 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4409 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4410 /// we can simplify this expression to "cond ? C : D or B".
4411 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4412                                          Value *C, Value *D,
4413                                          LLVMContext *Context) {
4414   // If A is not a select of -1/0, this cannot match.
4415   Value *Cond = 0;
4416   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4417     return 0;
4418
4419   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4420   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4421     return SelectInst::Create(Cond, C, B);
4422   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4423     return SelectInst::Create(Cond, C, B);
4424   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4425   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4426     return SelectInst::Create(Cond, C, D);
4427   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4428     return SelectInst::Create(Cond, C, D);
4429   return 0;
4430 }
4431
4432 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4433 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4434                                          ICmpInst *LHS, ICmpInst *RHS) {
4435   Value *Val, *Val2;
4436   ConstantInt *LHSCst, *RHSCst;
4437   ICmpInst::Predicate LHSCC, RHSCC;
4438   
4439   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4440   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4441              m_ConstantInt(LHSCst))) ||
4442       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4443              m_ConstantInt(RHSCst))))
4444     return 0;
4445   
4446   // From here on, we only handle:
4447   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4448   if (Val != Val2) return 0;
4449   
4450   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4451   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4452       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4453       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4454       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4455     return 0;
4456   
4457   // We can't fold (ugt x, C) | (sgt x, C2).
4458   if (!PredicatesFoldable(LHSCC, RHSCC))
4459     return 0;
4460   
4461   // Ensure that the larger constant is on the RHS.
4462   bool ShouldSwap;
4463   if (ICmpInst::isSignedPredicate(LHSCC) ||
4464       (ICmpInst::isEquality(LHSCC) && 
4465        ICmpInst::isSignedPredicate(RHSCC)))
4466     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4467   else
4468     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4469   
4470   if (ShouldSwap) {
4471     std::swap(LHS, RHS);
4472     std::swap(LHSCst, RHSCst);
4473     std::swap(LHSCC, RHSCC);
4474   }
4475   
4476   // At this point, we know we have have two icmp instructions
4477   // comparing a value against two constants and or'ing the result
4478   // together.  Because of the above check, we know that we only have
4479   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4480   // FoldICmpLogical check above), that the two constants are not
4481   // equal.
4482   assert(LHSCst != RHSCst && "Compares not folded above?");
4483
4484   switch (LHSCC) {
4485   default: llvm_unreachable("Unknown integer condition code!");
4486   case ICmpInst::ICMP_EQ:
4487     switch (RHSCC) {
4488     default: llvm_unreachable("Unknown integer condition code!");
4489     case ICmpInst::ICMP_EQ:
4490       if (LHSCst == SubOne(RHSCst)) {
4491         // (X == 13 | X == 14) -> X-13 <u 2
4492         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4493         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
4494         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4495         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4496       }
4497       break;                         // (X == 13 | X == 15) -> no change
4498     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4499     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4500       break;
4501     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4502     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4503     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4504       return ReplaceInstUsesWith(I, RHS);
4505     }
4506     break;
4507   case ICmpInst::ICMP_NE:
4508     switch (RHSCC) {
4509     default: llvm_unreachable("Unknown integer condition code!");
4510     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4511     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4512     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4513       return ReplaceInstUsesWith(I, LHS);
4514     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4515     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4516     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4517       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4518     }
4519     break;
4520   case ICmpInst::ICMP_ULT:
4521     switch (RHSCC) {
4522     default: llvm_unreachable("Unknown integer condition code!");
4523     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4524       break;
4525     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4526       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4527       // this can cause overflow.
4528       if (RHSCst->isMaxValue(false))
4529         return ReplaceInstUsesWith(I, LHS);
4530       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4531                              false, false, I);
4532     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4533       break;
4534     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4535     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4536       return ReplaceInstUsesWith(I, RHS);
4537     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4538       break;
4539     }
4540     break;
4541   case ICmpInst::ICMP_SLT:
4542     switch (RHSCC) {
4543     default: llvm_unreachable("Unknown integer condition code!");
4544     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4545       break;
4546     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4547       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4548       // this can cause overflow.
4549       if (RHSCst->isMaxValue(true))
4550         return ReplaceInstUsesWith(I, LHS);
4551       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4552                              true, false, I);
4553     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4554       break;
4555     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4556     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4557       return ReplaceInstUsesWith(I, RHS);
4558     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4559       break;
4560     }
4561     break;
4562   case ICmpInst::ICMP_UGT:
4563     switch (RHSCC) {
4564     default: llvm_unreachable("Unknown integer condition code!");
4565     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4566     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4567       return ReplaceInstUsesWith(I, LHS);
4568     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4569       break;
4570     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4571     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4572       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4573     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4574       break;
4575     }
4576     break;
4577   case ICmpInst::ICMP_SGT:
4578     switch (RHSCC) {
4579     default: llvm_unreachable("Unknown integer condition code!");
4580     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4581     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4582       return ReplaceInstUsesWith(I, LHS);
4583     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4584       break;
4585     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4586     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4587       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4588     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4589       break;
4590     }
4591     break;
4592   }
4593   return 0;
4594 }
4595
4596 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4597                                          FCmpInst *RHS) {
4598   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4599       RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4600       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4601     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4602       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4603         // If either of the constants are nans, then the whole thing returns
4604         // true.
4605         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4606           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4607         
4608         // Otherwise, no need to compare the two constants, compare the
4609         // rest.
4610         return new FCmpInst(FCmpInst::FCMP_UNO,
4611                             LHS->getOperand(0), RHS->getOperand(0));
4612       }
4613     
4614     // Handle vector zeros.  This occurs because the canonical form of
4615     // "fcmp uno x,x" is "fcmp uno x, 0".
4616     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4617         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4618       return new FCmpInst(FCmpInst::FCMP_UNO,
4619                           LHS->getOperand(0), RHS->getOperand(0));
4620     
4621     return 0;
4622   }
4623   
4624   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4625   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4626   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4627   
4628   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4629     // Swap RHS operands to match LHS.
4630     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4631     std::swap(Op1LHS, Op1RHS);
4632   }
4633   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4634     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4635     if (Op0CC == Op1CC)
4636       return new FCmpInst((FCmpInst::Predicate)Op0CC,
4637                           Op0LHS, Op0RHS);
4638     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
4639       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4640     if (Op0CC == FCmpInst::FCMP_FALSE)
4641       return ReplaceInstUsesWith(I, RHS);
4642     if (Op1CC == FCmpInst::FCMP_FALSE)
4643       return ReplaceInstUsesWith(I, LHS);
4644     bool Op0Ordered;
4645     bool Op1Ordered;
4646     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4647     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4648     if (Op0Ordered == Op1Ordered) {
4649       // If both are ordered or unordered, return a new fcmp with
4650       // or'ed predicates.
4651       Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4652                                Op0LHS, Op0RHS, Context);
4653       if (Instruction *I = dyn_cast<Instruction>(RV))
4654         return I;
4655       // Otherwise, it's a constant boolean value...
4656       return ReplaceInstUsesWith(I, RV);
4657     }
4658   }
4659   return 0;
4660 }
4661
4662 /// FoldOrWithConstants - This helper function folds:
4663 ///
4664 ///     ((A | B) & C1) | (B & C2)
4665 ///
4666 /// into:
4667 /// 
4668 ///     (A & C1) | B
4669 ///
4670 /// when the XOR of the two constants is "all ones" (-1).
4671 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4672                                                Value *A, Value *B, Value *C) {
4673   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4674   if (!CI1) return 0;
4675
4676   Value *V1 = 0;
4677   ConstantInt *CI2 = 0;
4678   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4679
4680   APInt Xor = CI1->getValue() ^ CI2->getValue();
4681   if (!Xor.isAllOnesValue()) return 0;
4682
4683   if (V1 == A || V1 == B) {
4684     Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
4685     return BinaryOperator::CreateOr(NewOp, V1);
4686   }
4687
4688   return 0;
4689 }
4690
4691 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4692   bool Changed = SimplifyCommutative(I);
4693   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4694
4695   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4696     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4697
4698   // or X, X = X
4699   if (Op0 == Op1)
4700     return ReplaceInstUsesWith(I, Op0);
4701
4702   // See if we can simplify any instructions used by the instruction whose sole 
4703   // purpose is to compute bits we don't care about.
4704   if (SimplifyDemandedInstructionBits(I))
4705     return &I;
4706   if (isa<VectorType>(I.getType())) {
4707     if (isa<ConstantAggregateZero>(Op1)) {
4708       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4709     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4710       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4711         return ReplaceInstUsesWith(I, I.getOperand(1));
4712     }
4713   }
4714
4715   // or X, -1 == -1
4716   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4717     ConstantInt *C1 = 0; Value *X = 0;
4718     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4719     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
4720         isOnlyUse(Op0)) {
4721       Value *Or = Builder->CreateOr(X, RHS);
4722       Or->takeName(Op0);
4723       return BinaryOperator::CreateAnd(Or, 
4724                ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
4725     }
4726
4727     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4728     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
4729         isOnlyUse(Op0)) {
4730       Value *Or = Builder->CreateOr(X, RHS);
4731       Or->takeName(Op0);
4732       return BinaryOperator::CreateXor(Or,
4733                  ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
4734     }
4735
4736     // Try to fold constant and into select arguments.
4737     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4738       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4739         return R;
4740     if (isa<PHINode>(Op0))
4741       if (Instruction *NV = FoldOpIntoPhi(I))
4742         return NV;
4743   }
4744
4745   Value *A = 0, *B = 0;
4746   ConstantInt *C1 = 0, *C2 = 0;
4747
4748   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4749     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4750       return ReplaceInstUsesWith(I, Op1);
4751   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4752     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4753       return ReplaceInstUsesWith(I, Op0);
4754
4755   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4756   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4757   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4758       match(Op1, m_Or(m_Value(), m_Value())) ||
4759       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4760        match(Op1, m_Shift(m_Value(), m_Value())))) {
4761     if (Instruction *BSwap = MatchBSwap(I))
4762       return BSwap;
4763   }
4764   
4765   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4766   if (Op0->hasOneUse() &&
4767       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4768       MaskedValueIsZero(Op1, C1->getValue())) {
4769     Value *NOr = Builder->CreateOr(A, Op1);
4770     NOr->takeName(Op0);
4771     return BinaryOperator::CreateXor(NOr, C1);
4772   }
4773
4774   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4775   if (Op1->hasOneUse() &&
4776       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4777       MaskedValueIsZero(Op0, C1->getValue())) {
4778     Value *NOr = Builder->CreateOr(A, Op0);
4779     NOr->takeName(Op0);
4780     return BinaryOperator::CreateXor(NOr, C1);
4781   }
4782
4783   // (A & C)|(B & D)
4784   Value *C = 0, *D = 0;
4785   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4786       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4787     Value *V1 = 0, *V2 = 0, *V3 = 0;
4788     C1 = dyn_cast<ConstantInt>(C);
4789     C2 = dyn_cast<ConstantInt>(D);
4790     if (C1 && C2) {  // (A & C1)|(B & C2)
4791       // If we have: ((V + N) & C1) | (V & C2)
4792       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4793       // replace with V+N.
4794       if (C1->getValue() == ~C2->getValue()) {
4795         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4796             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4797           // Add commutes, try both ways.
4798           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4799             return ReplaceInstUsesWith(I, A);
4800           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4801             return ReplaceInstUsesWith(I, A);
4802         }
4803         // Or commutes, try both ways.
4804         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4805             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4806           // Add commutes, try both ways.
4807           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4808             return ReplaceInstUsesWith(I, B);
4809           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4810             return ReplaceInstUsesWith(I, B);
4811         }
4812       }
4813       V1 = 0; V2 = 0; V3 = 0;
4814     }
4815     
4816     // Check to see if we have any common things being and'ed.  If so, find the
4817     // terms for V1 & (V2|V3).
4818     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4819       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4820         V1 = A, V2 = C, V3 = D;
4821       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4822         V1 = A, V2 = B, V3 = C;
4823       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4824         V1 = C, V2 = A, V3 = D;
4825       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4826         V1 = C, V2 = A, V3 = B;
4827       
4828       if (V1) {
4829         Value *Or = Builder->CreateOr(V2, V3, "tmp");
4830         return BinaryOperator::CreateAnd(V1, Or);
4831       }
4832     }
4833
4834     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4835     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4836       return Match;
4837     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4838       return Match;
4839     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4840       return Match;
4841     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4842       return Match;
4843
4844     // ((A&~B)|(~A&B)) -> A^B
4845     if ((match(C, m_Not(m_Specific(D))) &&
4846          match(B, m_Not(m_Specific(A)))))
4847       return BinaryOperator::CreateXor(A, D);
4848     // ((~B&A)|(~A&B)) -> A^B
4849     if ((match(A, m_Not(m_Specific(D))) &&
4850          match(B, m_Not(m_Specific(C)))))
4851       return BinaryOperator::CreateXor(C, D);
4852     // ((A&~B)|(B&~A)) -> A^B
4853     if ((match(C, m_Not(m_Specific(B))) &&
4854          match(D, m_Not(m_Specific(A)))))
4855       return BinaryOperator::CreateXor(A, B);
4856     // ((~B&A)|(B&~A)) -> A^B
4857     if ((match(A, m_Not(m_Specific(B))) &&
4858          match(D, m_Not(m_Specific(C)))))
4859       return BinaryOperator::CreateXor(C, B);
4860   }
4861   
4862   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4863   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4864     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4865       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4866           SI0->getOperand(1) == SI1->getOperand(1) &&
4867           (SI0->hasOneUse() || SI1->hasOneUse())) {
4868         Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4869                                          SI0->getName());
4870         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4871                                       SI1->getOperand(1));
4872       }
4873   }
4874
4875   // ((A|B)&1)|(B&-2) -> (A&1) | B
4876   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4877       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4878     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4879     if (Ret) return Ret;
4880   }
4881   // (B&-2)|((A|B)&1) -> (A&1) | B
4882   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4883       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4884     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4885     if (Ret) return Ret;
4886   }
4887
4888   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4889     if (A == Op1)   // ~A | A == -1
4890       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4891   } else {
4892     A = 0;
4893   }
4894   // Note, A is still live here!
4895   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4896     if (Op0 == B)
4897       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4898
4899     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4900     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4901       Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
4902       return BinaryOperator::CreateNot(And);
4903     }
4904   }
4905
4906   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4907   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4908     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4909       return R;
4910
4911     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4912       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4913         return Res;
4914   }
4915     
4916   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4917   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4918     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4919       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4920         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4921             !isa<ICmpInst>(Op1C->getOperand(0))) {
4922           const Type *SrcTy = Op0C->getOperand(0)->getType();
4923           if (SrcTy == Op1C->getOperand(0)->getType() &&
4924               SrcTy->isIntOrIntVector() &&
4925               // Only do this if the casts both really cause code to be
4926               // generated.
4927               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4928                                 I.getType(), TD) &&
4929               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4930                                 I.getType(), TD)) {
4931             Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
4932                                              Op1C->getOperand(0), I.getName());
4933             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4934           }
4935         }
4936       }
4937   }
4938   
4939     
4940   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4941   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4942     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4943       if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
4944         return Res;
4945   }
4946
4947   return Changed ? &I : 0;
4948 }
4949
4950 namespace {
4951
4952 // XorSelf - Implements: X ^ X --> 0
4953 struct XorSelf {
4954   Value *RHS;
4955   XorSelf(Value *rhs) : RHS(rhs) {}
4956   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4957   Instruction *apply(BinaryOperator &Xor) const {
4958     return &Xor;
4959   }
4960 };
4961
4962 }
4963
4964 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4965   bool Changed = SimplifyCommutative(I);
4966   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4967
4968   if (isa<UndefValue>(Op1)) {
4969     if (isa<UndefValue>(Op0))
4970       // Handle undef ^ undef -> 0 special case. This is a common
4971       // idiom (misuse).
4972       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4973     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4974   }
4975
4976   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4977   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4978     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4979     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4980   }
4981   
4982   // See if we can simplify any instructions used by the instruction whose sole 
4983   // purpose is to compute bits we don't care about.
4984   if (SimplifyDemandedInstructionBits(I))
4985     return &I;
4986   if (isa<VectorType>(I.getType()))
4987     if (isa<ConstantAggregateZero>(Op1))
4988       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4989
4990   // Is this a ~ operation?
4991   if (Value *NotOp = dyn_castNotVal(&I)) {
4992     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4993     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4994     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4995       if (Op0I->getOpcode() == Instruction::And || 
4996           Op0I->getOpcode() == Instruction::Or) {
4997         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4998         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4999           Value *NotY =
5000             Builder->CreateNot(Op0I->getOperand(1),
5001                                Op0I->getOperand(1)->getName()+".not");
5002           if (Op0I->getOpcode() == Instruction::And)
5003             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5004           return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5005         }
5006       }
5007     }
5008   }
5009   
5010   
5011   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5012     if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
5013       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5014       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5015         return new ICmpInst(ICI->getInversePredicate(),
5016                             ICI->getOperand(0), ICI->getOperand(1));
5017
5018       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5019         return new FCmpInst(FCI->getInversePredicate(),
5020                             FCI->getOperand(0), FCI->getOperand(1));
5021     }
5022
5023     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5024     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5025       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5026         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5027           Instruction::CastOps Opcode = Op0C->getOpcode();
5028           if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5029               (RHS == ConstantExpr::getCast(Opcode, 
5030                                             ConstantInt::getTrue(*Context),
5031                                             Op0C->getDestTy()))) {
5032             CI->setPredicate(CI->getInversePredicate());
5033             return CastInst::Create(Opcode, CI, Op0C->getType());
5034           }
5035         }
5036       }
5037     }
5038
5039     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5040       // ~(c-X) == X-c-1 == X+(-c-1)
5041       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5042         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5043           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5044           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5045                                       ConstantInt::get(I.getType(), 1));
5046           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5047         }
5048           
5049       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5050         if (Op0I->getOpcode() == Instruction::Add) {
5051           // ~(X-c) --> (-c-1)-X
5052           if (RHS->isAllOnesValue()) {
5053             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5054             return BinaryOperator::CreateSub(
5055                            ConstantExpr::getSub(NegOp0CI,
5056                                       ConstantInt::get(I.getType(), 1)),
5057                                       Op0I->getOperand(0));
5058           } else if (RHS->getValue().isSignBit()) {
5059             // (X + C) ^ signbit -> (X + C + signbit)
5060             Constant *C = ConstantInt::get(*Context,
5061                                            RHS->getValue() + Op0CI->getValue());
5062             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5063
5064           }
5065         } else if (Op0I->getOpcode() == Instruction::Or) {
5066           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5067           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5068             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5069             // Anything in both C1 and C2 is known to be zero, remove it from
5070             // NewRHS.
5071             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5072             NewRHS = ConstantExpr::getAnd(NewRHS, 
5073                                        ConstantExpr::getNot(CommonBits));
5074             Worklist.Add(Op0I);
5075             I.setOperand(0, Op0I->getOperand(0));
5076             I.setOperand(1, NewRHS);
5077             return &I;
5078           }
5079         }
5080       }
5081     }
5082
5083     // Try to fold constant and into select arguments.
5084     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5085       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5086         return R;
5087     if (isa<PHINode>(Op0))
5088       if (Instruction *NV = FoldOpIntoPhi(I))
5089         return NV;
5090   }
5091
5092   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
5093     if (X == Op1)
5094       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5095
5096   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5097     if (X == Op0)
5098       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5099
5100   
5101   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5102   if (Op1I) {
5103     Value *A, *B;
5104     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5105       if (A == Op0) {              // B^(B|A) == (A|B)^B
5106         Op1I->swapOperands();
5107         I.swapOperands();
5108         std::swap(Op0, Op1);
5109       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5110         I.swapOperands();     // Simplified below.
5111         std::swap(Op0, Op1);
5112       }
5113     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5114       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5115     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5116       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5117     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && 
5118                Op1I->hasOneUse()){
5119       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5120         Op1I->swapOperands();
5121         std::swap(A, B);
5122       }
5123       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5124         I.swapOperands();     // Simplified below.
5125         std::swap(Op0, Op1);
5126       }
5127     }
5128   }
5129   
5130   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5131   if (Op0I) {
5132     Value *A, *B;
5133     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5134         Op0I->hasOneUse()) {
5135       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5136         std::swap(A, B);
5137       if (B == Op1)                                  // (A|B)^B == A & ~B
5138         return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
5139     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5140       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5141     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5142       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5143     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && 
5144                Op0I->hasOneUse()){
5145       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5146         std::swap(A, B);
5147       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5148           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5149         return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
5150       }
5151     }
5152   }
5153   
5154   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5155   if (Op0I && Op1I && Op0I->isShift() && 
5156       Op0I->getOpcode() == Op1I->getOpcode() && 
5157       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5158       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5159     Value *NewOp =
5160       Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5161                          Op0I->getName());
5162     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5163                                   Op1I->getOperand(1));
5164   }
5165     
5166   if (Op0I && Op1I) {
5167     Value *A, *B, *C, *D;
5168     // (A & B)^(A | B) -> A ^ B
5169     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5170         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5171       if ((A == C && B == D) || (A == D && B == C)) 
5172         return BinaryOperator::CreateXor(A, B);
5173     }
5174     // (A | B)^(A & B) -> A ^ B
5175     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5176         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5177       if ((A == C && B == D) || (A == D && B == C)) 
5178         return BinaryOperator::CreateXor(A, B);
5179     }
5180     
5181     // (A & B)^(C & D)
5182     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5183         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5184         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5185       // (X & Y)^(X & Y) -> (Y^Z) & X
5186       Value *X = 0, *Y = 0, *Z = 0;
5187       if (A == C)
5188         X = A, Y = B, Z = D;
5189       else if (A == D)
5190         X = A, Y = B, Z = C;
5191       else if (B == C)
5192         X = B, Y = A, Z = D;
5193       else if (B == D)
5194         X = B, Y = A, Z = C;
5195       
5196       if (X) {
5197         Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
5198         return BinaryOperator::CreateAnd(NewOp, X);
5199       }
5200     }
5201   }
5202     
5203   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5204   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5205     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5206       return R;
5207
5208   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5209   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5210     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5211       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5212         const Type *SrcTy = Op0C->getOperand(0)->getType();
5213         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5214             // Only do this if the casts both really cause code to be generated.
5215             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5216                               I.getType(), TD) &&
5217             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5218                               I.getType(), TD)) {
5219           Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5220                                             Op1C->getOperand(0), I.getName());
5221           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5222         }
5223       }
5224   }
5225
5226   return Changed ? &I : 0;
5227 }
5228
5229 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5230                                    LLVMContext *Context) {
5231   return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5232 }
5233
5234 static bool HasAddOverflow(ConstantInt *Result,
5235                            ConstantInt *In1, ConstantInt *In2,
5236                            bool IsSigned) {
5237   if (IsSigned)
5238     if (In2->getValue().isNegative())
5239       return Result->getValue().sgt(In1->getValue());
5240     else
5241       return Result->getValue().slt(In1->getValue());
5242   else
5243     return Result->getValue().ult(In1->getValue());
5244 }
5245
5246 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5247 /// overflowed for this type.
5248 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5249                             Constant *In2, LLVMContext *Context,
5250                             bool IsSigned = false) {
5251   Result = ConstantExpr::getAdd(In1, In2);
5252
5253   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5254     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5255       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5256       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5257                          ExtractElement(In1, Idx, Context),
5258                          ExtractElement(In2, Idx, Context),
5259                          IsSigned))
5260         return true;
5261     }
5262     return false;
5263   }
5264
5265   return HasAddOverflow(cast<ConstantInt>(Result),
5266                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5267                         IsSigned);
5268 }
5269
5270 static bool HasSubOverflow(ConstantInt *Result,
5271                            ConstantInt *In1, ConstantInt *In2,
5272                            bool IsSigned) {
5273   if (IsSigned)
5274     if (In2->getValue().isNegative())
5275       return Result->getValue().slt(In1->getValue());
5276     else
5277       return Result->getValue().sgt(In1->getValue());
5278   else
5279     return Result->getValue().ugt(In1->getValue());
5280 }
5281
5282 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5283 /// overflowed for this type.
5284 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5285                             Constant *In2, LLVMContext *Context,
5286                             bool IsSigned = false) {
5287   Result = ConstantExpr::getSub(In1, In2);
5288
5289   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5290     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5291       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5292       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5293                          ExtractElement(In1, Idx, Context),
5294                          ExtractElement(In2, Idx, Context),
5295                          IsSigned))
5296         return true;
5297     }
5298     return false;
5299   }
5300
5301   return HasSubOverflow(cast<ConstantInt>(Result),
5302                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5303                         IsSigned);
5304 }
5305
5306 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5307 /// code necessary to compute the offset from the base pointer (without adding
5308 /// in the base pointer).  Return the result as a signed integer of intptr size.
5309 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5310   TargetData &TD = *IC.getTargetData();
5311   gep_type_iterator GTI = gep_type_begin(GEP);
5312   const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
5313   Value *Result = Constant::getNullValue(IntPtrTy);
5314
5315   // Build a mask for high order bits.
5316   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5317   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5318
5319   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5320        ++i, ++GTI) {
5321     Value *Op = *i;
5322     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5323     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5324       if (OpC->isZero()) continue;
5325       
5326       // Handle a struct index, which adds its field offset to the pointer.
5327       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5328         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5329         
5330         Result = IC.Builder->CreateAdd(Result,
5331                                        ConstantInt::get(IntPtrTy, Size),
5332                                        GEP->getName()+".offs");
5333         continue;
5334       }
5335       
5336       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5337       Constant *OC =
5338               ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5339       Scale = ConstantExpr::getMul(OC, Scale);
5340       // Emit an add instruction.
5341       Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
5342       continue;
5343     }
5344     // Convert to correct type.
5345     if (Op->getType() != IntPtrTy)
5346       Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
5347     if (Size != 1) {
5348       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5349       // We'll let instcombine(mul) convert this to a shl if possible.
5350       Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
5351     }
5352
5353     // Emit an add instruction.
5354     Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
5355   }
5356   return Result;
5357 }
5358
5359
5360 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5361 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
5362 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
5363 /// be complex, and scales are involved.  The above expression would also be
5364 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5365 /// This later form is less amenable to optimization though, and we are allowed
5366 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5367 ///
5368 /// If we can't emit an optimized form for this expression, this returns null.
5369 /// 
5370 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5371                                           InstCombiner &IC) {
5372   TargetData &TD = *IC.getTargetData();
5373   gep_type_iterator GTI = gep_type_begin(GEP);
5374
5375   // Check to see if this gep only has a single variable index.  If so, and if
5376   // any constant indices are a multiple of its scale, then we can compute this
5377   // in terms of the scale of the variable index.  For example, if the GEP
5378   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5379   // because the expression will cross zero at the same point.
5380   unsigned i, e = GEP->getNumOperands();
5381   int64_t Offset = 0;
5382   for (i = 1; i != e; ++i, ++GTI) {
5383     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5384       // Compute the aggregate offset of constant indices.
5385       if (CI->isZero()) continue;
5386
5387       // Handle a struct index, which adds its field offset to the pointer.
5388       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5389         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5390       } else {
5391         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5392         Offset += Size*CI->getSExtValue();
5393       }
5394     } else {
5395       // Found our variable index.
5396       break;
5397     }
5398   }
5399   
5400   // If there are no variable indices, we must have a constant offset, just
5401   // evaluate it the general way.
5402   if (i == e) return 0;
5403   
5404   Value *VariableIdx = GEP->getOperand(i);
5405   // Determine the scale factor of the variable element.  For example, this is
5406   // 4 if the variable index is into an array of i32.
5407   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5408   
5409   // Verify that there are no other variable indices.  If so, emit the hard way.
5410   for (++i, ++GTI; i != e; ++i, ++GTI) {
5411     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5412     if (!CI) return 0;
5413    
5414     // Compute the aggregate offset of constant indices.
5415     if (CI->isZero()) continue;
5416     
5417     // Handle a struct index, which adds its field offset to the pointer.
5418     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5419       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5420     } else {
5421       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5422       Offset += Size*CI->getSExtValue();
5423     }
5424   }
5425   
5426   // Okay, we know we have a single variable index, which must be a
5427   // pointer/array/vector index.  If there is no offset, life is simple, return
5428   // the index.
5429   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5430   if (Offset == 0) {
5431     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5432     // we don't need to bother extending: the extension won't affect where the
5433     // computation crosses zero.
5434     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5435       VariableIdx = new TruncInst(VariableIdx, 
5436                                   TD.getIntPtrType(VariableIdx->getContext()),
5437                                   VariableIdx->getName(), &I);
5438     return VariableIdx;
5439   }
5440   
5441   // Otherwise, there is an index.  The computation we will do will be modulo
5442   // the pointer size, so get it.
5443   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5444   
5445   Offset &= PtrSizeMask;
5446   VariableScale &= PtrSizeMask;
5447
5448   // To do this transformation, any constant index must be a multiple of the
5449   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5450   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5451   // multiple of the variable scale.
5452   int64_t NewOffs = Offset / (int64_t)VariableScale;
5453   if (Offset != NewOffs*(int64_t)VariableScale)
5454     return 0;
5455
5456   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5457   const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
5458   if (VariableIdx->getType() != IntPtrTy)
5459     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5460                                               true /*SExt*/, 
5461                                               VariableIdx->getName(), &I);
5462   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5463   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5464 }
5465
5466
5467 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5468 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5469 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
5470                                        ICmpInst::Predicate Cond,
5471                                        Instruction &I) {
5472   // Look through bitcasts.
5473   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5474     RHS = BCI->getOperand(0);
5475
5476   Value *PtrBase = GEPLHS->getOperand(0);
5477   if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
5478     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5479     // This transformation (ignoring the base and scales) is valid because we
5480     // know pointers can't overflow since the gep is inbounds.  See if we can
5481     // output an optimized form.
5482     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5483     
5484     // If not, synthesize the offset the hard way.
5485     if (Offset == 0)
5486       Offset = EmitGEPOffset(GEPLHS, I, *this);
5487     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5488                         Constant::getNullValue(Offset->getType()));
5489   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
5490     // If the base pointers are different, but the indices are the same, just
5491     // compare the base pointer.
5492     if (PtrBase != GEPRHS->getOperand(0)) {
5493       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5494       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5495                         GEPRHS->getOperand(0)->getType();
5496       if (IndicesTheSame)
5497         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5498           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5499             IndicesTheSame = false;
5500             break;
5501           }
5502
5503       // If all indices are the same, just compare the base pointers.
5504       if (IndicesTheSame)
5505         return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5506                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5507
5508       // Otherwise, the base pointers are different and the indices are
5509       // different, bail out.
5510       return 0;
5511     }
5512
5513     // If one of the GEPs has all zero indices, recurse.
5514     bool AllZeros = true;
5515     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5516       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5517           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5518         AllZeros = false;
5519         break;
5520       }
5521     if (AllZeros)
5522       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5523                           ICmpInst::getSwappedPredicate(Cond), I);
5524
5525     // If the other GEP has all zero indices, recurse.
5526     AllZeros = true;
5527     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5528       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5529           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5530         AllZeros = false;
5531         break;
5532       }
5533     if (AllZeros)
5534       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5535
5536     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5537       // If the GEPs only differ by one index, compare it.
5538       unsigned NumDifferences = 0;  // Keep track of # differences.
5539       unsigned DiffOperand = 0;     // The operand that differs.
5540       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5541         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5542           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5543                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5544             // Irreconcilable differences.
5545             NumDifferences = 2;
5546             break;
5547           } else {
5548             if (NumDifferences++) break;
5549             DiffOperand = i;
5550           }
5551         }
5552
5553       if (NumDifferences == 0)   // SAME GEP?
5554         return ReplaceInstUsesWith(I, // No comparison is needed here.
5555                                    ConstantInt::get(Type::getInt1Ty(*Context),
5556                                              ICmpInst::isTrueWhenEqual(Cond)));
5557
5558       else if (NumDifferences == 1) {
5559         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5560         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5561         // Make sure we do a signed comparison here.
5562         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5563       }
5564     }
5565
5566     // Only lower this if the icmp is the only user of the GEP or if we expect
5567     // the result to fold to a constant!
5568     if (TD &&
5569         (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5570         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5571       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5572       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5573       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5574       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5575     }
5576   }
5577   return 0;
5578 }
5579
5580 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5581 ///
5582 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5583                                                 Instruction *LHSI,
5584                                                 Constant *RHSC) {
5585   if (!isa<ConstantFP>(RHSC)) return 0;
5586   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5587   
5588   // Get the width of the mantissa.  We don't want to hack on conversions that
5589   // might lose information from the integer, e.g. "i64 -> float"
5590   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5591   if (MantissaWidth == -1) return 0;  // Unknown.
5592   
5593   // Check to see that the input is converted from an integer type that is small
5594   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5595   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5596   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5597   
5598   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5599   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5600   if (LHSUnsigned)
5601     ++InputSize;
5602   
5603   // If the conversion would lose info, don't hack on this.
5604   if ((int)InputSize > MantissaWidth)
5605     return 0;
5606   
5607   // Otherwise, we can potentially simplify the comparison.  We know that it
5608   // will always come through as an integer value and we know the constant is
5609   // not a NAN (it would have been previously simplified).
5610   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5611   
5612   ICmpInst::Predicate Pred;
5613   switch (I.getPredicate()) {
5614   default: llvm_unreachable("Unexpected predicate!");
5615   case FCmpInst::FCMP_UEQ:
5616   case FCmpInst::FCMP_OEQ:
5617     Pred = ICmpInst::ICMP_EQ;
5618     break;
5619   case FCmpInst::FCMP_UGT:
5620   case FCmpInst::FCMP_OGT:
5621     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5622     break;
5623   case FCmpInst::FCMP_UGE:
5624   case FCmpInst::FCMP_OGE:
5625     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5626     break;
5627   case FCmpInst::FCMP_ULT:
5628   case FCmpInst::FCMP_OLT:
5629     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5630     break;
5631   case FCmpInst::FCMP_ULE:
5632   case FCmpInst::FCMP_OLE:
5633     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5634     break;
5635   case FCmpInst::FCMP_UNE:
5636   case FCmpInst::FCMP_ONE:
5637     Pred = ICmpInst::ICMP_NE;
5638     break;
5639   case FCmpInst::FCMP_ORD:
5640     return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5641   case FCmpInst::FCMP_UNO:
5642     return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5643   }
5644   
5645   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5646   
5647   // Now we know that the APFloat is a normal number, zero or inf.
5648   
5649   // See if the FP constant is too large for the integer.  For example,
5650   // comparing an i8 to 300.0.
5651   unsigned IntWidth = IntTy->getScalarSizeInBits();
5652   
5653   if (!LHSUnsigned) {
5654     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5655     // and large values.
5656     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5657     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5658                           APFloat::rmNearestTiesToEven);
5659     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5660       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5661           Pred == ICmpInst::ICMP_SLE)
5662         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5663       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5664     }
5665   } else {
5666     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5667     // +INF and large values.
5668     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5669     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5670                           APFloat::rmNearestTiesToEven);
5671     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5672       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5673           Pred == ICmpInst::ICMP_ULE)
5674         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5675       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5676     }
5677   }
5678   
5679   if (!LHSUnsigned) {
5680     // See if the RHS value is < SignedMin.
5681     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5682     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5683                           APFloat::rmNearestTiesToEven);
5684     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5685       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5686           Pred == ICmpInst::ICMP_SGE)
5687         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5688       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5689     }
5690   }
5691
5692   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5693   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5694   // casting the FP value to the integer value and back, checking for equality.
5695   // Don't do this for zero, because -0.0 is not fractional.
5696   Constant *RHSInt = LHSUnsigned
5697     ? ConstantExpr::getFPToUI(RHSC, IntTy)
5698     : ConstantExpr::getFPToSI(RHSC, IntTy);
5699   if (!RHS.isZero()) {
5700     bool Equal = LHSUnsigned
5701       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5702       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5703     if (!Equal) {
5704       // If we had a comparison against a fractional value, we have to adjust
5705       // the compare predicate and sometimes the value.  RHSC is rounded towards
5706       // zero at this point.
5707       switch (Pred) {
5708       default: llvm_unreachable("Unexpected integer comparison!");
5709       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5710         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5711       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5712         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5713       case ICmpInst::ICMP_ULE:
5714         // (float)int <= 4.4   --> int <= 4
5715         // (float)int <= -4.4  --> false
5716         if (RHS.isNegative())
5717           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5718         break;
5719       case ICmpInst::ICMP_SLE:
5720         // (float)int <= 4.4   --> int <= 4
5721         // (float)int <= -4.4  --> int < -4
5722         if (RHS.isNegative())
5723           Pred = ICmpInst::ICMP_SLT;
5724         break;
5725       case ICmpInst::ICMP_ULT:
5726         // (float)int < -4.4   --> false
5727         // (float)int < 4.4    --> int <= 4
5728         if (RHS.isNegative())
5729           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5730         Pred = ICmpInst::ICMP_ULE;
5731         break;
5732       case ICmpInst::ICMP_SLT:
5733         // (float)int < -4.4   --> int < -4
5734         // (float)int < 4.4    --> int <= 4
5735         if (!RHS.isNegative())
5736           Pred = ICmpInst::ICMP_SLE;
5737         break;
5738       case ICmpInst::ICMP_UGT:
5739         // (float)int > 4.4    --> int > 4
5740         // (float)int > -4.4   --> true
5741         if (RHS.isNegative())
5742           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5743         break;
5744       case ICmpInst::ICMP_SGT:
5745         // (float)int > 4.4    --> int > 4
5746         // (float)int > -4.4   --> int >= -4
5747         if (RHS.isNegative())
5748           Pred = ICmpInst::ICMP_SGE;
5749         break;
5750       case ICmpInst::ICMP_UGE:
5751         // (float)int >= -4.4   --> true
5752         // (float)int >= 4.4    --> int > 4
5753         if (!RHS.isNegative())
5754           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5755         Pred = ICmpInst::ICMP_UGT;
5756         break;
5757       case ICmpInst::ICMP_SGE:
5758         // (float)int >= -4.4   --> int >= -4
5759         // (float)int >= 4.4    --> int > 4
5760         if (!RHS.isNegative())
5761           Pred = ICmpInst::ICMP_SGT;
5762         break;
5763       }
5764     }
5765   }
5766
5767   // Lower this FP comparison into an appropriate integer version of the
5768   // comparison.
5769   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5770 }
5771
5772 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5773   bool Changed = SimplifyCompare(I);
5774   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5775
5776   // Fold trivial predicates.
5777   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5778     return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5779   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5780     return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5781   
5782   // Simplify 'fcmp pred X, X'
5783   if (Op0 == Op1) {
5784     switch (I.getPredicate()) {
5785     default: llvm_unreachable("Unknown predicate!");
5786     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5787     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5788     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5789       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5790     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5791     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5792     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5793       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5794       
5795     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5796     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5797     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5798     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5799       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5800       I.setPredicate(FCmpInst::FCMP_UNO);
5801       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5802       return &I;
5803       
5804     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5805     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5806     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5807     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5808       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5809       I.setPredicate(FCmpInst::FCMP_ORD);
5810       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5811       return &I;
5812     }
5813   }
5814     
5815   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5816     return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
5817
5818   // Handle fcmp with constant RHS
5819   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5820     // If the constant is a nan, see if we can fold the comparison based on it.
5821     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5822       if (CFP->getValueAPF().isNaN()) {
5823         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5824           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5825         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5826                "Comparison must be either ordered or unordered!");
5827         // True if unordered.
5828         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5829       }
5830     }
5831     
5832     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5833       switch (LHSI->getOpcode()) {
5834       case Instruction::PHI:
5835         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5836         // block.  If in the same block, we're encouraging jump threading.  If
5837         // not, we are just pessimizing the code by making an i1 phi.
5838         if (LHSI->getParent() == I.getParent())
5839           if (Instruction *NV = FoldOpIntoPhi(I))
5840             return NV;
5841         break;
5842       case Instruction::SIToFP:
5843       case Instruction::UIToFP:
5844         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5845           return NV;
5846         break;
5847       case Instruction::Select:
5848         // If either operand of the select is a constant, we can fold the
5849         // comparison into the select arms, which will cause one to be
5850         // constant folded and the select turned into a bitwise or.
5851         Value *Op1 = 0, *Op2 = 0;
5852         if (LHSI->hasOneUse()) {
5853           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5854             // Fold the known value into the constant operand.
5855             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5856             // Insert a new FCmp of the other select operand.
5857             Op2 = Builder->CreateFCmp(I.getPredicate(),
5858                                       LHSI->getOperand(2), RHSC, I.getName());
5859           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5860             // Fold the known value into the constant operand.
5861             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5862             // Insert a new FCmp of the other select operand.
5863             Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5864                                       RHSC, I.getName());
5865           }
5866         }
5867
5868         if (Op1)
5869           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5870         break;
5871       }
5872   }
5873
5874   return Changed ? &I : 0;
5875 }
5876
5877 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5878   bool Changed = SimplifyCompare(I);
5879   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5880   const Type *Ty = Op0->getType();
5881
5882   // icmp X, X
5883   if (Op0 == Op1)
5884     return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context), 
5885                                                    I.isTrueWhenEqual()));
5886
5887   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5888     return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
5889   
5890   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5891   // addresses never equal each other!  We already know that Op0 != Op1.
5892   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5893        isa<ConstantPointerNull>(Op0)) &&
5894       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5895        isa<ConstantPointerNull>(Op1)))
5896     return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context), 
5897                                                    !I.isTrueWhenEqual()));
5898
5899   // icmp's with boolean values can always be turned into bitwise operations
5900   if (Ty == Type::getInt1Ty(*Context)) {
5901     switch (I.getPredicate()) {
5902     default: llvm_unreachable("Invalid icmp instruction!");
5903     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5904       Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
5905       return BinaryOperator::CreateNot(Xor);
5906     }
5907     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5908       return BinaryOperator::CreateXor(Op0, Op1);
5909
5910     case ICmpInst::ICMP_UGT:
5911       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5912       // FALL THROUGH
5913     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5914       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
5915       return BinaryOperator::CreateAnd(Not, Op1);
5916     }
5917     case ICmpInst::ICMP_SGT:
5918       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5919       // FALL THROUGH
5920     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5921       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
5922       return BinaryOperator::CreateAnd(Not, Op0);
5923     }
5924     case ICmpInst::ICMP_UGE:
5925       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
5926       // FALL THROUGH
5927     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
5928       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
5929       return BinaryOperator::CreateOr(Not, Op1);
5930     }
5931     case ICmpInst::ICMP_SGE:
5932       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
5933       // FALL THROUGH
5934     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
5935       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
5936       return BinaryOperator::CreateOr(Not, Op0);
5937     }
5938     }
5939   }
5940
5941   unsigned BitWidth = 0;
5942   if (TD)
5943     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
5944   else if (Ty->isIntOrIntVector())
5945     BitWidth = Ty->getScalarSizeInBits();
5946
5947   bool isSignBit = false;
5948
5949   // See if we are doing a comparison with a constant.
5950   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5951     Value *A = 0, *B = 0;
5952     
5953     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5954     if (I.isEquality() && CI->isNullValue() &&
5955         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5956       // (icmp cond A B) if cond is equality
5957       return new ICmpInst(I.getPredicate(), A, B);
5958     }
5959     
5960     // If we have an icmp le or icmp ge instruction, turn it into the
5961     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
5962     // them being folded in the code below.
5963     switch (I.getPredicate()) {
5964     default: break;
5965     case ICmpInst::ICMP_ULE:
5966       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5967         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5968       return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
5969                           AddOne(CI));
5970     case ICmpInst::ICMP_SLE:
5971       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5972         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5973       return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5974                           AddOne(CI));
5975     case ICmpInst::ICMP_UGE:
5976       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5977         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5978       return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
5979                           SubOne(CI));
5980     case ICmpInst::ICMP_SGE:
5981       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5982         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5983       return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5984                           SubOne(CI));
5985     }
5986     
5987     // If this comparison is a normal comparison, it demands all
5988     // bits, if it is a sign bit comparison, it only demands the sign bit.
5989     bool UnusedBit;
5990     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5991   }
5992
5993   // See if we can fold the comparison based on range information we can get
5994   // by checking whether bits are known to be zero or one in the input.
5995   if (BitWidth != 0) {
5996     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
5997     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
5998
5999     if (SimplifyDemandedBits(I.getOperandUse(0),
6000                              isSignBit ? APInt::getSignBit(BitWidth)
6001                                        : APInt::getAllOnesValue(BitWidth),
6002                              Op0KnownZero, Op0KnownOne, 0))
6003       return &I;
6004     if (SimplifyDemandedBits(I.getOperandUse(1),
6005                              APInt::getAllOnesValue(BitWidth),
6006                              Op1KnownZero, Op1KnownOne, 0))
6007       return &I;
6008
6009     // Given the known and unknown bits, compute a range that the LHS could be
6010     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6011     // EQ and NE we use unsigned values.
6012     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6013     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6014     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6015       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6016                                              Op0Min, Op0Max);
6017       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6018                                              Op1Min, Op1Max);
6019     } else {
6020       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6021                                                Op0Min, Op0Max);
6022       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6023                                                Op1Min, Op1Max);
6024     }
6025
6026     // If Min and Max are known to be the same, then SimplifyDemandedBits
6027     // figured out that the LHS is a constant.  Just constant fold this now so
6028     // that code below can assume that Min != Max.
6029     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6030       return new ICmpInst(I.getPredicate(),
6031                           ConstantInt::get(*Context, Op0Min), Op1);
6032     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6033       return new ICmpInst(I.getPredicate(), Op0,
6034                           ConstantInt::get(*Context, Op1Min));
6035
6036     // Based on the range information we know about the LHS, see if we can
6037     // simplify this comparison.  For example, (x&4) < 8  is always true.
6038     switch (I.getPredicate()) {
6039     default: llvm_unreachable("Unknown icmp opcode!");
6040     case ICmpInst::ICMP_EQ:
6041       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6042         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6043       break;
6044     case ICmpInst::ICMP_NE:
6045       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6046         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6047       break;
6048     case ICmpInst::ICMP_ULT:
6049       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6050         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6051       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6052         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6053       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6054         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6055       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6056         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6057           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6058                               SubOne(CI));
6059
6060         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6061         if (CI->isMinValue(true))
6062           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6063                            Constant::getAllOnesValue(Op0->getType()));
6064       }
6065       break;
6066     case ICmpInst::ICMP_UGT:
6067       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6068         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6069       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6070         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6071
6072       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6073         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6074       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6075         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6076           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6077                               AddOne(CI));
6078
6079         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6080         if (CI->isMaxValue(true))
6081           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6082                               Constant::getNullValue(Op0->getType()));
6083       }
6084       break;
6085     case ICmpInst::ICMP_SLT:
6086       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6087         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6088       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6089         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6090       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6091         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6092       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6093         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6094           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6095                               SubOne(CI));
6096       }
6097       break;
6098     case ICmpInst::ICMP_SGT:
6099       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6100         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6101       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6102         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6103
6104       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6105         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6106       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6107         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6108           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6109                               AddOne(CI));
6110       }
6111       break;
6112     case ICmpInst::ICMP_SGE:
6113       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6114       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6115         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6116       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6117         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6118       break;
6119     case ICmpInst::ICMP_SLE:
6120       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6121       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6122         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6123       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6124         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6125       break;
6126     case ICmpInst::ICMP_UGE:
6127       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6128       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6129         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6130       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6131         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6132       break;
6133     case ICmpInst::ICMP_ULE:
6134       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6135       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6136         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6137       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6138         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6139       break;
6140     }
6141
6142     // Turn a signed comparison into an unsigned one if both operands
6143     // are known to have the same sign.
6144     if (I.isSignedPredicate() &&
6145         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6146          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6147       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6148   }
6149
6150   // Test if the ICmpInst instruction is used exclusively by a select as
6151   // part of a minimum or maximum operation. If so, refrain from doing
6152   // any other folding. This helps out other analyses which understand
6153   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6154   // and CodeGen. And in this case, at least one of the comparison
6155   // operands has at least one user besides the compare (the select),
6156   // which would often largely negate the benefit of folding anyway.
6157   if (I.hasOneUse())
6158     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6159       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6160           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6161         return 0;
6162
6163   // See if we are doing a comparison between a constant and an instruction that
6164   // can be folded into the comparison.
6165   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6166     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6167     // instruction, see if that instruction also has constants so that the 
6168     // instruction can be folded into the icmp 
6169     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6170       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6171         return Res;
6172   }
6173
6174   // Handle icmp with constant (but not simple integer constant) RHS
6175   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6176     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6177       switch (LHSI->getOpcode()) {
6178       case Instruction::GetElementPtr:
6179         if (RHSC->isNullValue()) {
6180           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6181           bool isAllZeros = true;
6182           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6183             if (!isa<Constant>(LHSI->getOperand(i)) ||
6184                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6185               isAllZeros = false;
6186               break;
6187             }
6188           if (isAllZeros)
6189             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6190                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
6191         }
6192         break;
6193
6194       case Instruction::PHI:
6195         // Only fold icmp into the PHI if the phi and fcmp are in the same
6196         // block.  If in the same block, we're encouraging jump threading.  If
6197         // not, we are just pessimizing the code by making an i1 phi.
6198         if (LHSI->getParent() == I.getParent())
6199           if (Instruction *NV = FoldOpIntoPhi(I))
6200             return NV;
6201         break;
6202       case Instruction::Select: {
6203         // If either operand of the select is a constant, we can fold the
6204         // comparison into the select arms, which will cause one to be
6205         // constant folded and the select turned into a bitwise or.
6206         Value *Op1 = 0, *Op2 = 0;
6207         if (LHSI->hasOneUse()) {
6208           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6209             // Fold the known value into the constant operand.
6210             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6211             // Insert a new ICmp of the other select operand.
6212             Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6213                                       RHSC, I.getName());
6214           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6215             // Fold the known value into the constant operand.
6216             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6217             // Insert a new ICmp of the other select operand.
6218             Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6219                                       RHSC, I.getName());
6220           }
6221         }
6222
6223         if (Op1)
6224           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6225         break;
6226       }
6227       case Instruction::Malloc:
6228         // If we have (malloc != null), and if the malloc has a single use, we
6229         // can assume it is successful and remove the malloc.
6230         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6231           Worklist.Add(LHSI);
6232           return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
6233                                                          !I.isTrueWhenEqual()));
6234         }
6235         break;
6236       }
6237   }
6238
6239   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6240   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6241     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6242       return NI;
6243   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6244     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6245                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6246       return NI;
6247
6248   // Test to see if the operands of the icmp are casted versions of other
6249   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6250   // now.
6251   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6252     if (isa<PointerType>(Op0->getType()) && 
6253         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6254       // We keep moving the cast from the left operand over to the right
6255       // operand, where it can often be eliminated completely.
6256       Op0 = CI->getOperand(0);
6257
6258       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6259       // so eliminate it as well.
6260       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6261         Op1 = CI2->getOperand(0);
6262
6263       // If Op1 is a constant, we can fold the cast into the constant.
6264       if (Op0->getType() != Op1->getType()) {
6265         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6266           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6267         } else {
6268           // Otherwise, cast the RHS right before the icmp
6269           Op1 = Builder->CreateBitCast(Op1, Op0->getType());
6270         }
6271       }
6272       return new ICmpInst(I.getPredicate(), Op0, Op1);
6273     }
6274   }
6275   
6276   if (isa<CastInst>(Op0)) {
6277     // Handle the special case of: icmp (cast bool to X), <cst>
6278     // This comes up when you have code like
6279     //   int X = A < B;
6280     //   if (X) ...
6281     // For generality, we handle any zero-extension of any operand comparison
6282     // with a constant or another cast from the same type.
6283     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6284       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6285         return R;
6286   }
6287   
6288   // See if it's the same type of instruction on the left and right.
6289   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6290     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6291       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6292           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6293         switch (Op0I->getOpcode()) {
6294         default: break;
6295         case Instruction::Add:
6296         case Instruction::Sub:
6297         case Instruction::Xor:
6298           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6299             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6300                                 Op1I->getOperand(0));
6301           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6302           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6303             if (CI->getValue().isSignBit()) {
6304               ICmpInst::Predicate Pred = I.isSignedPredicate()
6305                                              ? I.getUnsignedPredicate()
6306                                              : I.getSignedPredicate();
6307               return new ICmpInst(Pred, Op0I->getOperand(0),
6308                                   Op1I->getOperand(0));
6309             }
6310             
6311             if (CI->getValue().isMaxSignedValue()) {
6312               ICmpInst::Predicate Pred = I.isSignedPredicate()
6313                                              ? I.getUnsignedPredicate()
6314                                              : I.getSignedPredicate();
6315               Pred = I.getSwappedPredicate(Pred);
6316               return new ICmpInst(Pred, Op0I->getOperand(0),
6317                                   Op1I->getOperand(0));
6318             }
6319           }
6320           break;
6321         case Instruction::Mul:
6322           if (!I.isEquality())
6323             break;
6324
6325           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6326             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6327             // Mask = -1 >> count-trailing-zeros(Cst).
6328             if (!CI->isZero() && !CI->isOne()) {
6329               const APInt &AP = CI->getValue();
6330               ConstantInt *Mask = ConstantInt::get(*Context, 
6331                                       APInt::getLowBitsSet(AP.getBitWidth(),
6332                                                            AP.getBitWidth() -
6333                                                       AP.countTrailingZeros()));
6334               Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6335               Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
6336               return new ICmpInst(I.getPredicate(), And1, And2);
6337             }
6338           }
6339           break;
6340         }
6341       }
6342     }
6343   }
6344   
6345   // ~x < ~y --> y < x
6346   { Value *A, *B;
6347     if (match(Op0, m_Not(m_Value(A))) &&
6348         match(Op1, m_Not(m_Value(B))))
6349       return new ICmpInst(I.getPredicate(), B, A);
6350   }
6351   
6352   if (I.isEquality()) {
6353     Value *A, *B, *C, *D;
6354     
6355     // -x == -y --> x == y
6356     if (match(Op0, m_Neg(m_Value(A))) &&
6357         match(Op1, m_Neg(m_Value(B))))
6358       return new ICmpInst(I.getPredicate(), A, B);
6359     
6360     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6361       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6362         Value *OtherVal = A == Op1 ? B : A;
6363         return new ICmpInst(I.getPredicate(), OtherVal,
6364                             Constant::getNullValue(A->getType()));
6365       }
6366
6367       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6368         // A^c1 == C^c2 --> A == C^(c1^c2)
6369         ConstantInt *C1, *C2;
6370         if (match(B, m_ConstantInt(C1)) &&
6371             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6372           Constant *NC = 
6373                    ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6374           Value *Xor = Builder->CreateXor(C, NC, "tmp");
6375           return new ICmpInst(I.getPredicate(), A, Xor);
6376         }
6377         
6378         // A^B == A^D -> B == D
6379         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6380         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6381         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6382         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6383       }
6384     }
6385     
6386     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6387         (A == Op0 || B == Op0)) {
6388       // A == (A^B)  ->  B == 0
6389       Value *OtherVal = A == Op0 ? B : A;
6390       return new ICmpInst(I.getPredicate(), OtherVal,
6391                           Constant::getNullValue(A->getType()));
6392     }
6393
6394     // (A-B) == A  ->  B == 0
6395     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6396       return new ICmpInst(I.getPredicate(), B, 
6397                           Constant::getNullValue(B->getType()));
6398
6399     // A == (A-B)  ->  B == 0
6400     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6401       return new ICmpInst(I.getPredicate(), B,
6402                           Constant::getNullValue(B->getType()));
6403     
6404     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6405     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6406         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6407         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6408       Value *X = 0, *Y = 0, *Z = 0;
6409       
6410       if (A == C) {
6411         X = B; Y = D; Z = A;
6412       } else if (A == D) {
6413         X = B; Y = C; Z = A;
6414       } else if (B == C) {
6415         X = A; Y = D; Z = B;
6416       } else if (B == D) {
6417         X = A; Y = C; Z = B;
6418       }
6419       
6420       if (X) {   // Build (X^Y) & Z
6421         Op1 = Builder->CreateXor(X, Y, "tmp");
6422         Op1 = Builder->CreateAnd(Op1, Z, "tmp");
6423         I.setOperand(0, Op1);
6424         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6425         return &I;
6426       }
6427     }
6428   }
6429   return Changed ? &I : 0;
6430 }
6431
6432
6433 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6434 /// and CmpRHS are both known to be integer constants.
6435 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6436                                           ConstantInt *DivRHS) {
6437   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6438   const APInt &CmpRHSV = CmpRHS->getValue();
6439   
6440   // FIXME: If the operand types don't match the type of the divide 
6441   // then don't attempt this transform. The code below doesn't have the
6442   // logic to deal with a signed divide and an unsigned compare (and
6443   // vice versa). This is because (x /s C1) <s C2  produces different 
6444   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6445   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6446   // work. :(  The if statement below tests that condition and bails 
6447   // if it finds it. 
6448   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6449   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6450     return 0;
6451   if (DivRHS->isZero())
6452     return 0; // The ProdOV computation fails on divide by zero.
6453   if (DivIsSigned && DivRHS->isAllOnesValue())
6454     return 0; // The overflow computation also screws up here
6455   if (DivRHS->isOne())
6456     return 0; // Not worth bothering, and eliminates some funny cases
6457               // with INT_MIN.
6458
6459   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6460   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6461   // C2 (CI). By solving for X we can turn this into a range check 
6462   // instead of computing a divide. 
6463   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6464
6465   // Determine if the product overflows by seeing if the product is
6466   // not equal to the divide. Make sure we do the same kind of divide
6467   // as in the LHS instruction that we're folding. 
6468   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6469                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6470
6471   // Get the ICmp opcode
6472   ICmpInst::Predicate Pred = ICI.getPredicate();
6473
6474   // Figure out the interval that is being checked.  For example, a comparison
6475   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6476   // Compute this interval based on the constants involved and the signedness of
6477   // the compare/divide.  This computes a half-open interval, keeping track of
6478   // whether either value in the interval overflows.  After analysis each
6479   // overflow variable is set to 0 if it's corresponding bound variable is valid
6480   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6481   int LoOverflow = 0, HiOverflow = 0;
6482   Constant *LoBound = 0, *HiBound = 0;
6483   
6484   if (!DivIsSigned) {  // udiv
6485     // e.g. X/5 op 3  --> [15, 20)
6486     LoBound = Prod;
6487     HiOverflow = LoOverflow = ProdOV;
6488     if (!HiOverflow)
6489       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6490   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6491     if (CmpRHSV == 0) {       // (X / pos) op 0
6492       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6493       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6494       HiBound = DivRHS;
6495     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6496       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6497       HiOverflow = LoOverflow = ProdOV;
6498       if (!HiOverflow)
6499         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6500     } else {                       // (X / pos) op neg
6501       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6502       HiBound = AddOne(Prod);
6503       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6504       if (!LoOverflow) {
6505         ConstantInt* DivNeg =
6506                          cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6507         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6508                                      true) ? -1 : 0;
6509        }
6510     }
6511   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6512     if (CmpRHSV == 0) {       // (X / neg) op 0
6513       // e.g. X/-5 op 0  --> [-4, 5)
6514       LoBound = AddOne(DivRHS);
6515       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6516       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6517         HiOverflow = 1;            // [INTMIN+1, overflow)
6518         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6519       }
6520     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6521       // e.g. X/-5 op 3  --> [-19, -14)
6522       HiBound = AddOne(Prod);
6523       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6524       if (!LoOverflow)
6525         LoOverflow = AddWithOverflow(LoBound, HiBound,
6526                                      DivRHS, Context, true) ? -1 : 0;
6527     } else {                       // (X / neg) op neg
6528       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6529       LoOverflow = HiOverflow = ProdOV;
6530       if (!HiOverflow)
6531         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6532     }
6533     
6534     // Dividing by a negative swaps the condition.  LT <-> GT
6535     Pred = ICmpInst::getSwappedPredicate(Pred);
6536   }
6537
6538   Value *X = DivI->getOperand(0);
6539   switch (Pred) {
6540   default: llvm_unreachable("Unhandled icmp opcode!");
6541   case ICmpInst::ICMP_EQ:
6542     if (LoOverflow && HiOverflow)
6543       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6544     else if (HiOverflow)
6545       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6546                           ICmpInst::ICMP_UGE, X, LoBound);
6547     else if (LoOverflow)
6548       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6549                           ICmpInst::ICMP_ULT, X, HiBound);
6550     else
6551       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6552   case ICmpInst::ICMP_NE:
6553     if (LoOverflow && HiOverflow)
6554       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6555     else if (HiOverflow)
6556       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6557                           ICmpInst::ICMP_ULT, X, LoBound);
6558     else if (LoOverflow)
6559       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6560                           ICmpInst::ICMP_UGE, X, HiBound);
6561     else
6562       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6563   case ICmpInst::ICMP_ULT:
6564   case ICmpInst::ICMP_SLT:
6565     if (LoOverflow == +1)   // Low bound is greater than input range.
6566       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6567     if (LoOverflow == -1)   // Low bound is less than input range.
6568       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6569     return new ICmpInst(Pred, X, LoBound);
6570   case ICmpInst::ICMP_UGT:
6571   case ICmpInst::ICMP_SGT:
6572     if (HiOverflow == +1)       // High bound greater than input range.
6573       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6574     else if (HiOverflow == -1)  // High bound less than input range.
6575       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6576     if (Pred == ICmpInst::ICMP_UGT)
6577       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6578     else
6579       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6580   }
6581 }
6582
6583
6584 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6585 ///
6586 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6587                                                           Instruction *LHSI,
6588                                                           ConstantInt *RHS) {
6589   const APInt &RHSV = RHS->getValue();
6590   
6591   switch (LHSI->getOpcode()) {
6592   case Instruction::Trunc:
6593     if (ICI.isEquality() && LHSI->hasOneUse()) {
6594       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6595       // of the high bits truncated out of x are known.
6596       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6597              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6598       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6599       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6600       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6601       
6602       // If all the high bits are known, we can do this xform.
6603       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6604         // Pull in the high bits from known-ones set.
6605         APInt NewRHS(RHS->getValue());
6606         NewRHS.zext(SrcBits);
6607         NewRHS |= KnownOne;
6608         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6609                             ConstantInt::get(*Context, NewRHS));
6610       }
6611     }
6612     break;
6613       
6614   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6615     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6616       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6617       // fold the xor.
6618       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6619           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6620         Value *CompareVal = LHSI->getOperand(0);
6621         
6622         // If the sign bit of the XorCST is not set, there is no change to
6623         // the operation, just stop using the Xor.
6624         if (!XorCST->getValue().isNegative()) {
6625           ICI.setOperand(0, CompareVal);
6626           Worklist.Add(LHSI);
6627           return &ICI;
6628         }
6629         
6630         // Was the old condition true if the operand is positive?
6631         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6632         
6633         // If so, the new one isn't.
6634         isTrueIfPositive ^= true;
6635         
6636         if (isTrueIfPositive)
6637           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
6638                               SubOne(RHS));
6639         else
6640           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
6641                               AddOne(RHS));
6642       }
6643
6644       if (LHSI->hasOneUse()) {
6645         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6646         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6647           const APInt &SignBit = XorCST->getValue();
6648           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6649                                          ? ICI.getUnsignedPredicate()
6650                                          : ICI.getSignedPredicate();
6651           return new ICmpInst(Pred, LHSI->getOperand(0),
6652                               ConstantInt::get(*Context, RHSV ^ SignBit));
6653         }
6654
6655         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6656         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6657           const APInt &NotSignBit = XorCST->getValue();
6658           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6659                                          ? ICI.getUnsignedPredicate()
6660                                          : ICI.getSignedPredicate();
6661           Pred = ICI.getSwappedPredicate(Pred);
6662           return new ICmpInst(Pred, LHSI->getOperand(0),
6663                               ConstantInt::get(*Context, RHSV ^ NotSignBit));
6664         }
6665       }
6666     }
6667     break;
6668   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6669     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6670         LHSI->getOperand(0)->hasOneUse()) {
6671       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6672       
6673       // If the LHS is an AND of a truncating cast, we can widen the
6674       // and/compare to be the input width without changing the value
6675       // produced, eliminating a cast.
6676       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6677         // We can do this transformation if either the AND constant does not
6678         // have its sign bit set or if it is an equality comparison. 
6679         // Extending a relational comparison when we're checking the sign
6680         // bit would not work.
6681         if (Cast->hasOneUse() &&
6682             (ICI.isEquality() ||
6683              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6684           uint32_t BitWidth = 
6685             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6686           APInt NewCST = AndCST->getValue();
6687           NewCST.zext(BitWidth);
6688           APInt NewCI = RHSV;
6689           NewCI.zext(BitWidth);
6690           Value *NewAnd = 
6691             Builder->CreateAnd(Cast->getOperand(0),
6692                            ConstantInt::get(*Context, NewCST), LHSI->getName());
6693           return new ICmpInst(ICI.getPredicate(), NewAnd,
6694                               ConstantInt::get(*Context, NewCI));
6695         }
6696       }
6697       
6698       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6699       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6700       // happens a LOT in code produced by the C front-end, for bitfield
6701       // access.
6702       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6703       if (Shift && !Shift->isShift())
6704         Shift = 0;
6705       
6706       ConstantInt *ShAmt;
6707       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6708       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6709       const Type *AndTy = AndCST->getType();          // Type of the and.
6710       
6711       // We can fold this as long as we can't shift unknown bits
6712       // into the mask.  This can only happen with signed shift
6713       // rights, as they sign-extend.
6714       if (ShAmt) {
6715         bool CanFold = Shift->isLogicalShift();
6716         if (!CanFold) {
6717           // To test for the bad case of the signed shr, see if any
6718           // of the bits shifted in could be tested after the mask.
6719           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6720           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6721           
6722           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6723           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6724                AndCST->getValue()) == 0)
6725             CanFold = true;
6726         }
6727         
6728         if (CanFold) {
6729           Constant *NewCst;
6730           if (Shift->getOpcode() == Instruction::Shl)
6731             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6732           else
6733             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6734           
6735           // Check to see if we are shifting out any of the bits being
6736           // compared.
6737           if (ConstantExpr::get(Shift->getOpcode(),
6738                                        NewCst, ShAmt) != RHS) {
6739             // If we shifted bits out, the fold is not going to work out.
6740             // As a special case, check to see if this means that the
6741             // result is always true or false now.
6742             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6743               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6744             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6745               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6746           } else {
6747             ICI.setOperand(1, NewCst);
6748             Constant *NewAndCST;
6749             if (Shift->getOpcode() == Instruction::Shl)
6750               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6751             else
6752               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6753             LHSI->setOperand(1, NewAndCST);
6754             LHSI->setOperand(0, Shift->getOperand(0));
6755             Worklist.Add(Shift); // Shift is dead.
6756             return &ICI;
6757           }
6758         }
6759       }
6760       
6761       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6762       // preferable because it allows the C<<Y expression to be hoisted out
6763       // of a loop if Y is invariant and X is not.
6764       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6765           ICI.isEquality() && !Shift->isArithmeticShift() &&
6766           !isa<Constant>(Shift->getOperand(0))) {
6767         // Compute C << Y.
6768         Value *NS;
6769         if (Shift->getOpcode() == Instruction::LShr) {
6770           NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
6771         } else {
6772           // Insert a logical shift.
6773           NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
6774         }
6775         
6776         // Compute X & (C << Y).
6777         Value *NewAnd = 
6778           Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6779         
6780         ICI.setOperand(0, NewAnd);
6781         return &ICI;
6782       }
6783     }
6784     break;
6785     
6786   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6787     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6788     if (!ShAmt) break;
6789     
6790     uint32_t TypeBits = RHSV.getBitWidth();
6791     
6792     // Check that the shift amount is in range.  If not, don't perform
6793     // undefined shifts.  When the shift is visited it will be
6794     // simplified.
6795     if (ShAmt->uge(TypeBits))
6796       break;
6797     
6798     if (ICI.isEquality()) {
6799       // If we are comparing against bits always shifted out, the
6800       // comparison cannot succeed.
6801       Constant *Comp =
6802         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
6803                                                                  ShAmt);
6804       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6805         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6806         Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6807         return ReplaceInstUsesWith(ICI, Cst);
6808       }
6809       
6810       if (LHSI->hasOneUse()) {
6811         // Otherwise strength reduce the shift into an and.
6812         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6813         Constant *Mask =
6814           ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits, 
6815                                                        TypeBits-ShAmtVal));
6816         
6817         Value *And =
6818           Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
6819         return new ICmpInst(ICI.getPredicate(), And,
6820                             ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
6821       }
6822     }
6823     
6824     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6825     bool TrueIfSigned = false;
6826     if (LHSI->hasOneUse() &&
6827         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6828       // (X << 31) <s 0  --> (X&1) != 0
6829       Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
6830                                            (TypeBits-ShAmt->getZExtValue()-1));
6831       Value *And =
6832         Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
6833       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6834                           And, Constant::getNullValue(And->getType()));
6835     }
6836     break;
6837   }
6838     
6839   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6840   case Instruction::AShr: {
6841     // Only handle equality comparisons of shift-by-constant.
6842     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6843     if (!ShAmt || !ICI.isEquality()) break;
6844
6845     // Check that the shift amount is in range.  If not, don't perform
6846     // undefined shifts.  When the shift is visited it will be
6847     // simplified.
6848     uint32_t TypeBits = RHSV.getBitWidth();
6849     if (ShAmt->uge(TypeBits))
6850       break;
6851     
6852     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6853       
6854     // If we are comparing against bits always shifted out, the
6855     // comparison cannot succeed.
6856     APInt Comp = RHSV << ShAmtVal;
6857     if (LHSI->getOpcode() == Instruction::LShr)
6858       Comp = Comp.lshr(ShAmtVal);
6859     else
6860       Comp = Comp.ashr(ShAmtVal);
6861     
6862     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6863       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6864       Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6865       return ReplaceInstUsesWith(ICI, Cst);
6866     }
6867     
6868     // Otherwise, check to see if the bits shifted out are known to be zero.
6869     // If so, we can compare against the unshifted value:
6870     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6871     if (LHSI->hasOneUse() &&
6872         MaskedValueIsZero(LHSI->getOperand(0), 
6873                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6874       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6875                           ConstantExpr::getShl(RHS, ShAmt));
6876     }
6877       
6878     if (LHSI->hasOneUse()) {
6879       // Otherwise strength reduce the shift into an and.
6880       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6881       Constant *Mask = ConstantInt::get(*Context, Val);
6882       
6883       Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6884                                       Mask, LHSI->getName()+".mask");
6885       return new ICmpInst(ICI.getPredicate(), And,
6886                           ConstantExpr::getShl(RHS, ShAmt));
6887     }
6888     break;
6889   }
6890     
6891   case Instruction::SDiv:
6892   case Instruction::UDiv:
6893     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6894     // Fold this div into the comparison, producing a range check. 
6895     // Determine, based on the divide type, what the range is being 
6896     // checked.  If there is an overflow on the low or high side, remember 
6897     // it, otherwise compute the range [low, hi) bounding the new value.
6898     // See: InsertRangeTest above for the kinds of replacements possible.
6899     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6900       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6901                                           DivRHS))
6902         return R;
6903     break;
6904
6905   case Instruction::Add:
6906     // Fold: icmp pred (add, X, C1), C2
6907
6908     if (!ICI.isEquality()) {
6909       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6910       if (!LHSC) break;
6911       const APInt &LHSV = LHSC->getValue();
6912
6913       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6914                             .subtract(LHSV);
6915
6916       if (ICI.isSignedPredicate()) {
6917         if (CR.getLower().isSignBit()) {
6918           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6919                               ConstantInt::get(*Context, CR.getUpper()));
6920         } else if (CR.getUpper().isSignBit()) {
6921           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6922                               ConstantInt::get(*Context, CR.getLower()));
6923         }
6924       } else {
6925         if (CR.getLower().isMinValue()) {
6926           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6927                               ConstantInt::get(*Context, CR.getUpper()));
6928         } else if (CR.getUpper().isMinValue()) {
6929           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6930                               ConstantInt::get(*Context, CR.getLower()));
6931         }
6932       }
6933     }
6934     break;
6935   }
6936   
6937   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6938   if (ICI.isEquality()) {
6939     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6940     
6941     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6942     // the second operand is a constant, simplify a bit.
6943     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6944       switch (BO->getOpcode()) {
6945       case Instruction::SRem:
6946         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6947         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6948           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6949           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6950             Value *NewRem =
6951               Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
6952                                   BO->getName());
6953             return new ICmpInst(ICI.getPredicate(), NewRem,
6954                                 Constant::getNullValue(BO->getType()));
6955           }
6956         }
6957         break;
6958       case Instruction::Add:
6959         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6960         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6961           if (BO->hasOneUse())
6962             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6963                                 ConstantExpr::getSub(RHS, BOp1C));
6964         } else if (RHSV == 0) {
6965           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6966           // efficiently invertible, or if the add has just this one use.
6967           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6968           
6969           if (Value *NegVal = dyn_castNegVal(BOp1))
6970             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6971           else if (Value *NegVal = dyn_castNegVal(BOp0))
6972             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6973           else if (BO->hasOneUse()) {
6974             Value *Neg = Builder->CreateNeg(BOp1);
6975             Neg->takeName(BO);
6976             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6977           }
6978         }
6979         break;
6980       case Instruction::Xor:
6981         // For the xor case, we can xor two constants together, eliminating
6982         // the explicit xor.
6983         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6984           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6985                               ConstantExpr::getXor(RHS, BOC));
6986         
6987         // FALLTHROUGH
6988       case Instruction::Sub:
6989         // Replace (([sub|xor] A, B) != 0) with (A != B)
6990         if (RHSV == 0)
6991           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6992                               BO->getOperand(1));
6993         break;
6994         
6995       case Instruction::Or:
6996         // If bits are being or'd in that are not present in the constant we
6997         // are comparing against, then the comparison could never succeed!
6998         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6999           Constant *NotCI = ConstantExpr::getNot(RHS);
7000           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7001             return ReplaceInstUsesWith(ICI,
7002                                        ConstantInt::get(Type::getInt1Ty(*Context), 
7003                                        isICMP_NE));
7004         }
7005         break;
7006         
7007       case Instruction::And:
7008         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7009           // If bits are being compared against that are and'd out, then the
7010           // comparison can never succeed!
7011           if ((RHSV & ~BOC->getValue()) != 0)
7012             return ReplaceInstUsesWith(ICI,
7013                                        ConstantInt::get(Type::getInt1Ty(*Context),
7014                                        isICMP_NE));
7015           
7016           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7017           if (RHS == BOC && RHSV.isPowerOf2())
7018             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7019                                 ICmpInst::ICMP_NE, LHSI,
7020                                 Constant::getNullValue(RHS->getType()));
7021           
7022           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7023           if (BOC->getValue().isSignBit()) {
7024             Value *X = BO->getOperand(0);
7025             Constant *Zero = Constant::getNullValue(X->getType());
7026             ICmpInst::Predicate pred = isICMP_NE ? 
7027               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7028             return new ICmpInst(pred, X, Zero);
7029           }
7030           
7031           // ((X & ~7) == 0) --> X < 8
7032           if (RHSV == 0 && isHighOnes(BOC)) {
7033             Value *X = BO->getOperand(0);
7034             Constant *NegX = ConstantExpr::getNeg(BOC);
7035             ICmpInst::Predicate pred = isICMP_NE ? 
7036               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7037             return new ICmpInst(pred, X, NegX);
7038           }
7039         }
7040       default: break;
7041       }
7042     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7043       // Handle icmp {eq|ne} <intrinsic>, intcst.
7044       if (II->getIntrinsicID() == Intrinsic::bswap) {
7045         Worklist.Add(II);
7046         ICI.setOperand(0, II->getOperand(1));
7047         ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7048         return &ICI;
7049       }
7050     }
7051   }
7052   return 0;
7053 }
7054
7055 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7056 /// We only handle extending casts so far.
7057 ///
7058 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7059   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7060   Value *LHSCIOp        = LHSCI->getOperand(0);
7061   const Type *SrcTy     = LHSCIOp->getType();
7062   const Type *DestTy    = LHSCI->getType();
7063   Value *RHSCIOp;
7064
7065   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7066   // integer type is the same size as the pointer type.
7067   if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7068       TD->getPointerSizeInBits() ==
7069          cast<IntegerType>(DestTy)->getBitWidth()) {
7070     Value *RHSOp = 0;
7071     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7072       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7073     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7074       RHSOp = RHSC->getOperand(0);
7075       // If the pointer types don't match, insert a bitcast.
7076       if (LHSCIOp->getType() != RHSOp->getType())
7077         RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
7078     }
7079
7080     if (RHSOp)
7081       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7082   }
7083   
7084   // The code below only handles extension cast instructions, so far.
7085   // Enforce this.
7086   if (LHSCI->getOpcode() != Instruction::ZExt &&
7087       LHSCI->getOpcode() != Instruction::SExt)
7088     return 0;
7089
7090   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7091   bool isSignedCmp = ICI.isSignedPredicate();
7092
7093   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7094     // Not an extension from the same type?
7095     RHSCIOp = CI->getOperand(0);
7096     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7097       return 0;
7098     
7099     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7100     // and the other is a zext), then we can't handle this.
7101     if (CI->getOpcode() != LHSCI->getOpcode())
7102       return 0;
7103
7104     // Deal with equality cases early.
7105     if (ICI.isEquality())
7106       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7107
7108     // A signed comparison of sign extended values simplifies into a
7109     // signed comparison.
7110     if (isSignedCmp && isSignedExt)
7111       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7112
7113     // The other three cases all fold into an unsigned comparison.
7114     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7115   }
7116
7117   // If we aren't dealing with a constant on the RHS, exit early
7118   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7119   if (!CI)
7120     return 0;
7121
7122   // Compute the constant that would happen if we truncated to SrcTy then
7123   // reextended to DestTy.
7124   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7125   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7126                                                 Res1, DestTy);
7127
7128   // If the re-extended constant didn't change...
7129   if (Res2 == CI) {
7130     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7131     // For example, we might have:
7132     //    %A = sext i16 %X to i32
7133     //    %B = icmp ugt i32 %A, 1330
7134     // It is incorrect to transform this into 
7135     //    %B = icmp ugt i16 %X, 1330
7136     // because %A may have negative value. 
7137     //
7138     // However, we allow this when the compare is EQ/NE, because they are
7139     // signless.
7140     if (isSignedExt == isSignedCmp || ICI.isEquality())
7141       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7142     return 0;
7143   }
7144
7145   // The re-extended constant changed so the constant cannot be represented 
7146   // in the shorter type. Consequently, we cannot emit a simple comparison.
7147
7148   // First, handle some easy cases. We know the result cannot be equal at this
7149   // point so handle the ICI.isEquality() cases
7150   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7151     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7152   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7153     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7154
7155   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7156   // should have been folded away previously and not enter in here.
7157   Value *Result;
7158   if (isSignedCmp) {
7159     // We're performing a signed comparison.
7160     if (cast<ConstantInt>(CI)->getValue().isNegative())
7161       Result = ConstantInt::getFalse(*Context);          // X < (small) --> false
7162     else
7163       Result = ConstantInt::getTrue(*Context);           // X < (large) --> true
7164   } else {
7165     // We're performing an unsigned comparison.
7166     if (isSignedExt) {
7167       // We're performing an unsigned comp with a sign extended value.
7168       // This is true if the input is >= 0. [aka >s -1]
7169       Constant *NegOne = Constant::getAllOnesValue(SrcTy);
7170       Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
7171     } else {
7172       // Unsigned extend & unsigned compare -> always true.
7173       Result = ConstantInt::getTrue(*Context);
7174     }
7175   }
7176
7177   // Finally, return the value computed.
7178   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7179       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7180     return ReplaceInstUsesWith(ICI, Result);
7181
7182   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7183           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7184          "ICmp should be folded!");
7185   if (Constant *CI = dyn_cast<Constant>(Result))
7186     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7187   return BinaryOperator::CreateNot(Result);
7188 }
7189
7190 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7191   return commonShiftTransforms(I);
7192 }
7193
7194 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7195   return commonShiftTransforms(I);
7196 }
7197
7198 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7199   if (Instruction *R = commonShiftTransforms(I))
7200     return R;
7201   
7202   Value *Op0 = I.getOperand(0);
7203   
7204   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7205   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7206     if (CSI->isAllOnesValue())
7207       return ReplaceInstUsesWith(I, CSI);
7208
7209   // See if we can turn a signed shr into an unsigned shr.
7210   if (MaskedValueIsZero(Op0,
7211                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7212     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7213
7214   // Arithmetic shifting an all-sign-bit value is a no-op.
7215   unsigned NumSignBits = ComputeNumSignBits(Op0);
7216   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7217     return ReplaceInstUsesWith(I, Op0);
7218
7219   return 0;
7220 }
7221
7222 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7223   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7224   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7225
7226   // shl X, 0 == X and shr X, 0 == X
7227   // shl 0, X == 0 and shr 0, X == 0
7228   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7229       Op0 == Constant::getNullValue(Op0->getType()))
7230     return ReplaceInstUsesWith(I, Op0);
7231   
7232   if (isa<UndefValue>(Op0)) {            
7233     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7234       return ReplaceInstUsesWith(I, Op0);
7235     else                                    // undef << X -> 0, undef >>u X -> 0
7236       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7237   }
7238   if (isa<UndefValue>(Op1)) {
7239     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7240       return ReplaceInstUsesWith(I, Op0);          
7241     else                                     // X << undef, X >>u undef -> 0
7242       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7243   }
7244
7245   // See if we can fold away this shift.
7246   if (SimplifyDemandedInstructionBits(I))
7247     return &I;
7248
7249   // Try to fold constant and into select arguments.
7250   if (isa<Constant>(Op0))
7251     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7252       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7253         return R;
7254
7255   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7256     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7257       return Res;
7258   return 0;
7259 }
7260
7261 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7262                                                BinaryOperator &I) {
7263   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7264
7265   // See if we can simplify any instructions used by the instruction whose sole 
7266   // purpose is to compute bits we don't care about.
7267   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7268   
7269   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7270   // a signed shift.
7271   //
7272   if (Op1->uge(TypeBits)) {
7273     if (I.getOpcode() != Instruction::AShr)
7274       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7275     else {
7276       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7277       return &I;
7278     }
7279   }
7280   
7281   // ((X*C1) << C2) == (X * (C1 << C2))
7282   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7283     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7284       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7285         return BinaryOperator::CreateMul(BO->getOperand(0),
7286                                         ConstantExpr::getShl(BOOp, Op1));
7287   
7288   // Try to fold constant and into select arguments.
7289   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7290     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7291       return R;
7292   if (isa<PHINode>(Op0))
7293     if (Instruction *NV = FoldOpIntoPhi(I))
7294       return NV;
7295   
7296   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7297   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7298     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7299     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7300     // place.  Don't try to do this transformation in this case.  Also, we
7301     // require that the input operand is a shift-by-constant so that we have
7302     // confidence that the shifts will get folded together.  We could do this
7303     // xform in more cases, but it is unlikely to be profitable.
7304     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7305         isa<ConstantInt>(TrOp->getOperand(1))) {
7306       // Okay, we'll do this xform.  Make the shift of shift.
7307       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7308       // (shift2 (shift1 & 0x00FF), c2)
7309       Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
7310
7311       // For logical shifts, the truncation has the effect of making the high
7312       // part of the register be zeros.  Emulate this by inserting an AND to
7313       // clear the top bits as needed.  This 'and' will usually be zapped by
7314       // other xforms later if dead.
7315       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7316       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7317       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7318       
7319       // The mask we constructed says what the trunc would do if occurring
7320       // between the shifts.  We want to know the effect *after* the second
7321       // shift.  We know that it is a logical shift by a constant, so adjust the
7322       // mask as appropriate.
7323       if (I.getOpcode() == Instruction::Shl)
7324         MaskV <<= Op1->getZExtValue();
7325       else {
7326         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7327         MaskV = MaskV.lshr(Op1->getZExtValue());
7328       }
7329
7330       // shift1 & 0x00FF
7331       Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7332                                       TI->getName());
7333
7334       // Return the value truncated to the interesting size.
7335       return new TruncInst(And, I.getType());
7336     }
7337   }
7338   
7339   if (Op0->hasOneUse()) {
7340     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7341       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7342       Value *V1, *V2;
7343       ConstantInt *CC;
7344       switch (Op0BO->getOpcode()) {
7345         default: break;
7346         case Instruction::Add:
7347         case Instruction::And:
7348         case Instruction::Or:
7349         case Instruction::Xor: {
7350           // These operators commute.
7351           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7352           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7353               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7354                     m_Specific(Op1)))) {
7355             Value *YS =         // (Y << C)
7356               Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7357             // (X + (Y << C))
7358             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7359                                             Op0BO->getOperand(1)->getName());
7360             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7361             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7362                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7363           }
7364           
7365           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7366           Value *Op0BOOp1 = Op0BO->getOperand(1);
7367           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7368               match(Op0BOOp1, 
7369                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7370                           m_ConstantInt(CC))) &&
7371               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7372             Value *YS =   // (Y << C)
7373               Builder->CreateShl(Op0BO->getOperand(0), Op1,
7374                                            Op0BO->getName());
7375             // X & (CC << C)
7376             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7377                                            V1->getName()+".mask");
7378             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7379           }
7380         }
7381           
7382         // FALL THROUGH.
7383         case Instruction::Sub: {
7384           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7385           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7386               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7387                     m_Specific(Op1)))) {
7388             Value *YS =  // (Y << C)
7389               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7390             // (X + (Y << C))
7391             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7392                                             Op0BO->getOperand(0)->getName());
7393             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7394             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7395                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7396           }
7397           
7398           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7399           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7400               match(Op0BO->getOperand(0),
7401                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7402                           m_ConstantInt(CC))) && V2 == Op1 &&
7403               cast<BinaryOperator>(Op0BO->getOperand(0))
7404                   ->getOperand(0)->hasOneUse()) {
7405             Value *YS = // (Y << C)
7406               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7407             // X & (CC << C)
7408             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7409                                            V1->getName()+".mask");
7410             
7411             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7412           }
7413           
7414           break;
7415         }
7416       }
7417       
7418       
7419       // If the operand is an bitwise operator with a constant RHS, and the
7420       // shift is the only use, we can pull it out of the shift.
7421       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7422         bool isValid = true;     // Valid only for And, Or, Xor
7423         bool highBitSet = false; // Transform if high bit of constant set?
7424         
7425         switch (Op0BO->getOpcode()) {
7426           default: isValid = false; break;   // Do not perform transform!
7427           case Instruction::Add:
7428             isValid = isLeftShift;
7429             break;
7430           case Instruction::Or:
7431           case Instruction::Xor:
7432             highBitSet = false;
7433             break;
7434           case Instruction::And:
7435             highBitSet = true;
7436             break;
7437         }
7438         
7439         // If this is a signed shift right, and the high bit is modified
7440         // by the logical operation, do not perform the transformation.
7441         // The highBitSet boolean indicates the value of the high bit of
7442         // the constant which would cause it to be modified for this
7443         // operation.
7444         //
7445         if (isValid && I.getOpcode() == Instruction::AShr)
7446           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7447         
7448         if (isValid) {
7449           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7450           
7451           Value *NewShift =
7452             Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
7453           NewShift->takeName(Op0BO);
7454           
7455           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7456                                         NewRHS);
7457         }
7458       }
7459     }
7460   }
7461   
7462   // Find out if this is a shift of a shift by a constant.
7463   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7464   if (ShiftOp && !ShiftOp->isShift())
7465     ShiftOp = 0;
7466   
7467   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7468     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7469     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7470     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7471     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7472     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7473     Value *X = ShiftOp->getOperand(0);
7474     
7475     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7476     
7477     const IntegerType *Ty = cast<IntegerType>(I.getType());
7478     
7479     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7480     if (I.getOpcode() == ShiftOp->getOpcode()) {
7481       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7482       // saturates.
7483       if (AmtSum >= TypeBits) {
7484         if (I.getOpcode() != Instruction::AShr)
7485           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7486         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7487       }
7488       
7489       return BinaryOperator::Create(I.getOpcode(), X,
7490                                     ConstantInt::get(Ty, AmtSum));
7491     }
7492     
7493     if (ShiftOp->getOpcode() == Instruction::LShr &&
7494         I.getOpcode() == Instruction::AShr) {
7495       if (AmtSum >= TypeBits)
7496         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7497       
7498       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7499       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7500     }
7501     
7502     if (ShiftOp->getOpcode() == Instruction::AShr &&
7503         I.getOpcode() == Instruction::LShr) {
7504       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7505       if (AmtSum >= TypeBits)
7506         AmtSum = TypeBits-1;
7507       
7508       Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7509
7510       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7511       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
7512     }
7513     
7514     // Okay, if we get here, one shift must be left, and the other shift must be
7515     // right.  See if the amounts are equal.
7516     if (ShiftAmt1 == ShiftAmt2) {
7517       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7518       if (I.getOpcode() == Instruction::Shl) {
7519         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7520         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7521       }
7522       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7523       if (I.getOpcode() == Instruction::LShr) {
7524         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7525         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7526       }
7527       // We can simplify ((X << C) >>s C) into a trunc + sext.
7528       // NOTE: we could do this for any C, but that would make 'unusual' integer
7529       // types.  For now, just stick to ones well-supported by the code
7530       // generators.
7531       const Type *SExtType = 0;
7532       switch (Ty->getBitWidth() - ShiftAmt1) {
7533       case 1  :
7534       case 8  :
7535       case 16 :
7536       case 32 :
7537       case 64 :
7538       case 128:
7539         SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
7540         break;
7541       default: break;
7542       }
7543       if (SExtType)
7544         return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
7545       // Otherwise, we can't handle it yet.
7546     } else if (ShiftAmt1 < ShiftAmt2) {
7547       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7548       
7549       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7550       if (I.getOpcode() == Instruction::Shl) {
7551         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7552                ShiftOp->getOpcode() == Instruction::AShr);
7553         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7554         
7555         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7556         return BinaryOperator::CreateAnd(Shift,
7557                                          ConstantInt::get(*Context, Mask));
7558       }
7559       
7560       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7561       if (I.getOpcode() == Instruction::LShr) {
7562         assert(ShiftOp->getOpcode() == Instruction::Shl);
7563         Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7564         
7565         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7566         return BinaryOperator::CreateAnd(Shift,
7567                                          ConstantInt::get(*Context, Mask));
7568       }
7569       
7570       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7571     } else {
7572       assert(ShiftAmt2 < ShiftAmt1);
7573       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7574
7575       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7576       if (I.getOpcode() == Instruction::Shl) {
7577         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7578                ShiftOp->getOpcode() == Instruction::AShr);
7579         Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7580                                             ConstantInt::get(Ty, ShiftDiff));
7581         
7582         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7583         return BinaryOperator::CreateAnd(Shift,
7584                                          ConstantInt::get(*Context, Mask));
7585       }
7586       
7587       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7588       if (I.getOpcode() == Instruction::LShr) {
7589         assert(ShiftOp->getOpcode() == Instruction::Shl);
7590         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7591         
7592         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7593         return BinaryOperator::CreateAnd(Shift,
7594                                          ConstantInt::get(*Context, Mask));
7595       }
7596       
7597       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7598     }
7599   }
7600   return 0;
7601 }
7602
7603
7604 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7605 /// expression.  If so, decompose it, returning some value X, such that Val is
7606 /// X*Scale+Offset.
7607 ///
7608 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7609                                         int &Offset, LLVMContext *Context) {
7610   assert(Val->getType() == Type::getInt32Ty(*Context) && 
7611          "Unexpected allocation size type!");
7612   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7613     Offset = CI->getZExtValue();
7614     Scale  = 0;
7615     return ConstantInt::get(Type::getInt32Ty(*Context), 0);
7616   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7617     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7618       if (I->getOpcode() == Instruction::Shl) {
7619         // This is a value scaled by '1 << the shift amt'.
7620         Scale = 1U << RHS->getZExtValue();
7621         Offset = 0;
7622         return I->getOperand(0);
7623       } else if (I->getOpcode() == Instruction::Mul) {
7624         // This value is scaled by 'RHS'.
7625         Scale = RHS->getZExtValue();
7626         Offset = 0;
7627         return I->getOperand(0);
7628       } else if (I->getOpcode() == Instruction::Add) {
7629         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7630         // where C1 is divisible by C2.
7631         unsigned SubScale;
7632         Value *SubVal = 
7633           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7634                                     Offset, Context);
7635         Offset += RHS->getZExtValue();
7636         Scale = SubScale;
7637         return SubVal;
7638       }
7639     }
7640   }
7641
7642   // Otherwise, we can't look past this.
7643   Scale = 1;
7644   Offset = 0;
7645   return Val;
7646 }
7647
7648
7649 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7650 /// try to eliminate the cast by moving the type information into the alloc.
7651 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7652                                                    AllocationInst &AI) {
7653   const PointerType *PTy = cast<PointerType>(CI.getType());
7654   
7655   BuilderTy AllocaBuilder(*Builder);
7656   AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7657   
7658   // Remove any uses of AI that are dead.
7659   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7660   
7661   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7662     Instruction *User = cast<Instruction>(*UI++);
7663     if (isInstructionTriviallyDead(User)) {
7664       while (UI != E && *UI == User)
7665         ++UI; // If this instruction uses AI more than once, don't break UI.
7666       
7667       ++NumDeadInst;
7668       DEBUG(errs() << "IC: DCE: " << *User << '\n');
7669       EraseInstFromFunction(*User);
7670     }
7671   }
7672
7673   // This requires TargetData to get the alloca alignment and size information.
7674   if (!TD) return 0;
7675
7676   // Get the type really allocated and the type casted to.
7677   const Type *AllocElTy = AI.getAllocatedType();
7678   const Type *CastElTy = PTy->getElementType();
7679   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7680
7681   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7682   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7683   if (CastElTyAlign < AllocElTyAlign) return 0;
7684
7685   // If the allocation has multiple uses, only promote it if we are strictly
7686   // increasing the alignment of the resultant allocation.  If we keep it the
7687   // same, we open the door to infinite loops of various kinds.  (A reference
7688   // from a dbg.declare doesn't count as a use for this purpose.)
7689   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7690       CastElTyAlign == AllocElTyAlign) return 0;
7691
7692   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7693   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7694   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7695
7696   // See if we can satisfy the modulus by pulling a scale out of the array
7697   // size argument.
7698   unsigned ArraySizeScale;
7699   int ArrayOffset;
7700   Value *NumElements = // See if the array size is a decomposable linear expr.
7701     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7702                               ArrayOffset, Context);
7703  
7704   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7705   // do the xform.
7706   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7707       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7708
7709   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7710   Value *Amt = 0;
7711   if (Scale == 1) {
7712     Amt = NumElements;
7713   } else {
7714     Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
7715     // Insert before the alloca, not before the cast.
7716     Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
7717   }
7718   
7719   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7720     Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
7721     Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
7722   }
7723   
7724   AllocationInst *New;
7725   if (isa<MallocInst>(AI))
7726     New = AllocaBuilder.CreateMalloc(CastElTy, Amt);
7727   else
7728     New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7729   New->setAlignment(AI.getAlignment());
7730   New->takeName(&AI);
7731   
7732   // If the allocation has one real use plus a dbg.declare, just remove the
7733   // declare.
7734   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7735     EraseInstFromFunction(*DI);
7736   }
7737   // If the allocation has multiple real uses, insert a cast and change all
7738   // things that used it to use the new cast.  This will also hack on CI, but it
7739   // will die soon.
7740   else if (!AI.hasOneUse()) {
7741     // New is the allocation instruction, pointer typed. AI is the original
7742     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7743     Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
7744     AI.replaceAllUsesWith(NewCast);
7745   }
7746   return ReplaceInstUsesWith(CI, New);
7747 }
7748
7749 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7750 /// and return it as type Ty without inserting any new casts and without
7751 /// changing the computed value.  This is used by code that tries to decide
7752 /// whether promoting or shrinking integer operations to wider or smaller types
7753 /// will allow us to eliminate a truncate or extend.
7754 ///
7755 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7756 /// extension operation if Ty is larger.
7757 ///
7758 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7759 /// should return true if trunc(V) can be computed by computing V in the smaller
7760 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7761 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7762 /// efficiently truncated.
7763 ///
7764 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7765 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7766 /// the final result.
7767 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7768                                               unsigned CastOpc,
7769                                               int &NumCastsRemoved){
7770   // We can always evaluate constants in another type.
7771   if (isa<Constant>(V))
7772     return true;
7773   
7774   Instruction *I = dyn_cast<Instruction>(V);
7775   if (!I) return false;
7776   
7777   const Type *OrigTy = V->getType();
7778   
7779   // If this is an extension or truncate, we can often eliminate it.
7780   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7781     // If this is a cast from the destination type, we can trivially eliminate
7782     // it, and this will remove a cast overall.
7783     if (I->getOperand(0)->getType() == Ty) {
7784       // If the first operand is itself a cast, and is eliminable, do not count
7785       // this as an eliminable cast.  We would prefer to eliminate those two
7786       // casts first.
7787       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7788         ++NumCastsRemoved;
7789       return true;
7790     }
7791   }
7792
7793   // We can't extend or shrink something that has multiple uses: doing so would
7794   // require duplicating the instruction in general, which isn't profitable.
7795   if (!I->hasOneUse()) return false;
7796
7797   unsigned Opc = I->getOpcode();
7798   switch (Opc) {
7799   case Instruction::Add:
7800   case Instruction::Sub:
7801   case Instruction::Mul:
7802   case Instruction::And:
7803   case Instruction::Or:
7804   case Instruction::Xor:
7805     // These operators can all arbitrarily be extended or truncated.
7806     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7807                                       NumCastsRemoved) &&
7808            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7809                                       NumCastsRemoved);
7810
7811   case Instruction::UDiv:
7812   case Instruction::URem: {
7813     // UDiv and URem can be truncated if all the truncated bits are zero.
7814     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7815     uint32_t BitWidth = Ty->getScalarSizeInBits();
7816     if (BitWidth < OrigBitWidth) {
7817       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7818       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7819           MaskedValueIsZero(I->getOperand(1), Mask)) {
7820         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7821                                           NumCastsRemoved) &&
7822                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7823                                           NumCastsRemoved);
7824       }
7825     }
7826     break;
7827   }
7828   case Instruction::Shl:
7829     // If we are truncating the result of this SHL, and if it's a shift of a
7830     // constant amount, we can always perform a SHL in a smaller type.
7831     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7832       uint32_t BitWidth = Ty->getScalarSizeInBits();
7833       if (BitWidth < OrigTy->getScalarSizeInBits() &&
7834           CI->getLimitedValue(BitWidth) < BitWidth)
7835         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7836                                           NumCastsRemoved);
7837     }
7838     break;
7839   case Instruction::LShr:
7840     // If this is a truncate of a logical shr, we can truncate it to a smaller
7841     // lshr iff we know that the bits we would otherwise be shifting in are
7842     // already zeros.
7843     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7844       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7845       uint32_t BitWidth = Ty->getScalarSizeInBits();
7846       if (BitWidth < OrigBitWidth &&
7847           MaskedValueIsZero(I->getOperand(0),
7848             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7849           CI->getLimitedValue(BitWidth) < BitWidth) {
7850         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7851                                           NumCastsRemoved);
7852       }
7853     }
7854     break;
7855   case Instruction::ZExt:
7856   case Instruction::SExt:
7857   case Instruction::Trunc:
7858     // If this is the same kind of case as our original (e.g. zext+zext), we
7859     // can safely replace it.  Note that replacing it does not reduce the number
7860     // of casts in the input.
7861     if (Opc == CastOpc)
7862       return true;
7863
7864     // sext (zext ty1), ty2 -> zext ty2
7865     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7866       return true;
7867     break;
7868   case Instruction::Select: {
7869     SelectInst *SI = cast<SelectInst>(I);
7870     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7871                                       NumCastsRemoved) &&
7872            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7873                                       NumCastsRemoved);
7874   }
7875   case Instruction::PHI: {
7876     // We can change a phi if we can change all operands.
7877     PHINode *PN = cast<PHINode>(I);
7878     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7879       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7880                                       NumCastsRemoved))
7881         return false;
7882     return true;
7883   }
7884   default:
7885     // TODO: Can handle more cases here.
7886     break;
7887   }
7888   
7889   return false;
7890 }
7891
7892 /// EvaluateInDifferentType - Given an expression that 
7893 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7894 /// evaluate the expression.
7895 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7896                                              bool isSigned) {
7897   if (Constant *C = dyn_cast<Constant>(V))
7898     return ConstantExpr::getIntegerCast(C, Ty,
7899                                                isSigned /*Sext or ZExt*/);
7900
7901   // Otherwise, it must be an instruction.
7902   Instruction *I = cast<Instruction>(V);
7903   Instruction *Res = 0;
7904   unsigned Opc = I->getOpcode();
7905   switch (Opc) {
7906   case Instruction::Add:
7907   case Instruction::Sub:
7908   case Instruction::Mul:
7909   case Instruction::And:
7910   case Instruction::Or:
7911   case Instruction::Xor:
7912   case Instruction::AShr:
7913   case Instruction::LShr:
7914   case Instruction::Shl:
7915   case Instruction::UDiv:
7916   case Instruction::URem: {
7917     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7918     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7919     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7920     break;
7921   }    
7922   case Instruction::Trunc:
7923   case Instruction::ZExt:
7924   case Instruction::SExt:
7925     // If the source type of the cast is the type we're trying for then we can
7926     // just return the source.  There's no need to insert it because it is not
7927     // new.
7928     if (I->getOperand(0)->getType() == Ty)
7929       return I->getOperand(0);
7930     
7931     // Otherwise, must be the same type of cast, so just reinsert a new one.
7932     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7933                            Ty);
7934     break;
7935   case Instruction::Select: {
7936     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7937     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7938     Res = SelectInst::Create(I->getOperand(0), True, False);
7939     break;
7940   }
7941   case Instruction::PHI: {
7942     PHINode *OPN = cast<PHINode>(I);
7943     PHINode *NPN = PHINode::Create(Ty);
7944     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7945       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7946       NPN->addIncoming(V, OPN->getIncomingBlock(i));
7947     }
7948     Res = NPN;
7949     break;
7950   }
7951   default: 
7952     // TODO: Can handle more cases here.
7953     llvm_unreachable("Unreachable!");
7954     break;
7955   }
7956   
7957   Res->takeName(I);
7958   return InsertNewInstBefore(Res, *I);
7959 }
7960
7961 /// @brief Implement the transforms common to all CastInst visitors.
7962 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7963   Value *Src = CI.getOperand(0);
7964
7965   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7966   // eliminate it now.
7967   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7968     if (Instruction::CastOps opc = 
7969         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7970       // The first cast (CSrc) is eliminable so we need to fix up or replace
7971       // the second cast (CI). CSrc will then have a good chance of being dead.
7972       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7973     }
7974   }
7975
7976   // If we are casting a select then fold the cast into the select
7977   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7978     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7979       return NV;
7980
7981   // If we are casting a PHI then fold the cast into the PHI
7982   if (isa<PHINode>(Src))
7983     if (Instruction *NV = FoldOpIntoPhi(CI))
7984       return NV;
7985   
7986   return 0;
7987 }
7988
7989 /// FindElementAtOffset - Given a type and a constant offset, determine whether
7990 /// or not there is a sequence of GEP indices into the type that will land us at
7991 /// the specified offset.  If so, fill them into NewIndices and return the
7992 /// resultant element type, otherwise return null.
7993 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
7994                                        SmallVectorImpl<Value*> &NewIndices,
7995                                        const TargetData *TD,
7996                                        LLVMContext *Context) {
7997   if (!TD) return 0;
7998   if (!Ty->isSized()) return 0;
7999   
8000   // Start with the index over the outer type.  Note that the type size
8001   // might be zero (even if the offset isn't zero) if the indexed type
8002   // is something like [0 x {int, int}]
8003   const Type *IntPtrTy = TD->getIntPtrType(*Context);
8004   int64_t FirstIdx = 0;
8005   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8006     FirstIdx = Offset/TySize;
8007     Offset -= FirstIdx*TySize;
8008     
8009     // Handle hosts where % returns negative instead of values [0..TySize).
8010     if (Offset < 0) {
8011       --FirstIdx;
8012       Offset += TySize;
8013       assert(Offset >= 0);
8014     }
8015     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8016   }
8017   
8018   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8019     
8020   // Index into the types.  If we fail, set OrigBase to null.
8021   while (Offset) {
8022     // Indexing into tail padding between struct/array elements.
8023     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8024       return 0;
8025     
8026     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8027       const StructLayout *SL = TD->getStructLayout(STy);
8028       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8029              "Offset must stay within the indexed type");
8030       
8031       unsigned Elt = SL->getElementContainingOffset(Offset);
8032       NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
8033       
8034       Offset -= SL->getElementOffset(Elt);
8035       Ty = STy->getElementType(Elt);
8036     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8037       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8038       assert(EltSize && "Cannot index into a zero-sized array");
8039       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8040       Offset %= EltSize;
8041       Ty = AT->getElementType();
8042     } else {
8043       // Otherwise, we can't index into the middle of this atomic type, bail.
8044       return 0;
8045     }
8046   }
8047   
8048   return Ty;
8049 }
8050
8051 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8052 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8053   Value *Src = CI.getOperand(0);
8054   
8055   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8056     // If casting the result of a getelementptr instruction with no offset, turn
8057     // this into a cast of the original pointer!
8058     if (GEP->hasAllZeroIndices()) {
8059       // Changing the cast operand is usually not a good idea but it is safe
8060       // here because the pointer operand is being replaced with another 
8061       // pointer operand so the opcode doesn't need to change.
8062       Worklist.Add(GEP);
8063       CI.setOperand(0, GEP->getOperand(0));
8064       return &CI;
8065     }
8066     
8067     // If the GEP has a single use, and the base pointer is a bitcast, and the
8068     // GEP computes a constant offset, see if we can convert these three
8069     // instructions into fewer.  This typically happens with unions and other
8070     // non-type-safe code.
8071     if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8072       if (GEP->hasAllConstantIndices()) {
8073         // We are guaranteed to get a constant from EmitGEPOffset.
8074         ConstantInt *OffsetV =
8075                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8076         int64_t Offset = OffsetV->getSExtValue();
8077         
8078         // Get the base pointer input of the bitcast, and the type it points to.
8079         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8080         const Type *GEPIdxTy =
8081           cast<PointerType>(OrigBase->getType())->getElementType();
8082         SmallVector<Value*, 8> NewIndices;
8083         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8084           // If we were able to index down into an element, create the GEP
8085           // and bitcast the result.  This eliminates one bitcast, potentially
8086           // two.
8087           Value *NGEP = Builder->CreateGEP(OrigBase, NewIndices.begin(),
8088                                            NewIndices.end());
8089           NGEP->takeName(GEP);
8090           if (isa<Instruction>(NGEP) && cast<GEPOperator>(GEP)->isInBounds())
8091             cast<GEPOperator>(NGEP)->setIsInBounds(true);
8092           
8093           if (isa<BitCastInst>(CI))
8094             return new BitCastInst(NGEP, CI.getType());
8095           assert(isa<PtrToIntInst>(CI));
8096           return new PtrToIntInst(NGEP, CI.getType());
8097         }
8098       }      
8099     }
8100   }
8101     
8102   return commonCastTransforms(CI);
8103 }
8104
8105 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8106 /// type like i42.  We don't want to introduce operations on random non-legal
8107 /// integer types where they don't already exist in the code.  In the future,
8108 /// we should consider making this based off target-data, so that 32-bit targets
8109 /// won't get i64 operations etc.
8110 static bool isSafeIntegerType(const Type *Ty) {
8111   switch (Ty->getPrimitiveSizeInBits()) {
8112   case 8:
8113   case 16:
8114   case 32:
8115   case 64:
8116     return true;
8117   default: 
8118     return false;
8119   }
8120 }
8121
8122 /// commonIntCastTransforms - This function implements the common transforms
8123 /// for trunc, zext, and sext.
8124 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8125   if (Instruction *Result = commonCastTransforms(CI))
8126     return Result;
8127
8128   Value *Src = CI.getOperand(0);
8129   const Type *SrcTy = Src->getType();
8130   const Type *DestTy = CI.getType();
8131   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8132   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8133
8134   // See if we can simplify any instructions used by the LHS whose sole 
8135   // purpose is to compute bits we don't care about.
8136   if (SimplifyDemandedInstructionBits(CI))
8137     return &CI;
8138
8139   // If the source isn't an instruction or has more than one use then we
8140   // can't do anything more. 
8141   Instruction *SrcI = dyn_cast<Instruction>(Src);
8142   if (!SrcI || !Src->hasOneUse())
8143     return 0;
8144
8145   // Attempt to propagate the cast into the instruction for int->int casts.
8146   int NumCastsRemoved = 0;
8147   // Only do this if the dest type is a simple type, don't convert the
8148   // expression tree to something weird like i93 unless the source is also
8149   // strange.
8150   if ((isSafeIntegerType(DestTy->getScalarType()) ||
8151        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8152       CanEvaluateInDifferentType(SrcI, DestTy,
8153                                  CI.getOpcode(), NumCastsRemoved)) {
8154     // If this cast is a truncate, evaluting in a different type always
8155     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8156     // we need to do an AND to maintain the clear top-part of the computation,
8157     // so we require that the input have eliminated at least one cast.  If this
8158     // is a sign extension, we insert two new casts (to do the extension) so we
8159     // require that two casts have been eliminated.
8160     bool DoXForm = false;
8161     bool JustReplace = false;
8162     switch (CI.getOpcode()) {
8163     default:
8164       // All the others use floating point so we shouldn't actually 
8165       // get here because of the check above.
8166       llvm_unreachable("Unknown cast type");
8167     case Instruction::Trunc:
8168       DoXForm = true;
8169       break;
8170     case Instruction::ZExt: {
8171       DoXForm = NumCastsRemoved >= 1;
8172       if (!DoXForm && 0) {
8173         // If it's unnecessary to issue an AND to clear the high bits, it's
8174         // always profitable to do this xform.
8175         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8176         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8177         if (MaskedValueIsZero(TryRes, Mask))
8178           return ReplaceInstUsesWith(CI, TryRes);
8179         
8180         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8181           if (TryI->use_empty())
8182             EraseInstFromFunction(*TryI);
8183       }
8184       break;
8185     }
8186     case Instruction::SExt: {
8187       DoXForm = NumCastsRemoved >= 2;
8188       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8189         // If we do not have to emit the truncate + sext pair, then it's always
8190         // profitable to do this xform.
8191         //
8192         // It's not safe to eliminate the trunc + sext pair if one of the
8193         // eliminated cast is a truncate. e.g.
8194         // t2 = trunc i32 t1 to i16
8195         // t3 = sext i16 t2 to i32
8196         // !=
8197         // i32 t1
8198         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8199         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8200         if (NumSignBits > (DestBitSize - SrcBitSize))
8201           return ReplaceInstUsesWith(CI, TryRes);
8202         
8203         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8204           if (TryI->use_empty())
8205             EraseInstFromFunction(*TryI);
8206       }
8207       break;
8208     }
8209     }
8210     
8211     if (DoXForm) {
8212       DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8213             " to avoid cast: " << CI);
8214       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8215                                            CI.getOpcode() == Instruction::SExt);
8216       if (JustReplace)
8217         // Just replace this cast with the result.
8218         return ReplaceInstUsesWith(CI, Res);
8219
8220       assert(Res->getType() == DestTy);
8221       switch (CI.getOpcode()) {
8222       default: llvm_unreachable("Unknown cast type!");
8223       case Instruction::Trunc:
8224         // Just replace this cast with the result.
8225         return ReplaceInstUsesWith(CI, Res);
8226       case Instruction::ZExt: {
8227         assert(SrcBitSize < DestBitSize && "Not a zext?");
8228
8229         // If the high bits are already zero, just replace this cast with the
8230         // result.
8231         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8232         if (MaskedValueIsZero(Res, Mask))
8233           return ReplaceInstUsesWith(CI, Res);
8234
8235         // We need to emit an AND to clear the high bits.
8236         Constant *C = ConstantInt::get(*Context, 
8237                                  APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8238         return BinaryOperator::CreateAnd(Res, C);
8239       }
8240       case Instruction::SExt: {
8241         // If the high bits are already filled with sign bit, just replace this
8242         // cast with the result.
8243         unsigned NumSignBits = ComputeNumSignBits(Res);
8244         if (NumSignBits > (DestBitSize - SrcBitSize))
8245           return ReplaceInstUsesWith(CI, Res);
8246
8247         // We need to emit a cast to truncate, then a cast to sext.
8248         return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
8249       }
8250       }
8251     }
8252   }
8253   
8254   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8255   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8256
8257   switch (SrcI->getOpcode()) {
8258   case Instruction::Add:
8259   case Instruction::Mul:
8260   case Instruction::And:
8261   case Instruction::Or:
8262   case Instruction::Xor:
8263     // If we are discarding information, rewrite.
8264     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8265       // Don't insert two casts unless at least one can be eliminated.
8266       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8267           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8268         Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8269         Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8270         return BinaryOperator::Create(
8271             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8272       }
8273     }
8274
8275     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8276     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8277         SrcI->getOpcode() == Instruction::Xor &&
8278         Op1 == ConstantInt::getTrue(*Context) &&
8279         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8280       Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
8281       return BinaryOperator::CreateXor(New,
8282                                       ConstantInt::get(CI.getType(), 1));
8283     }
8284     break;
8285
8286   case Instruction::Shl: {
8287     // Canonicalize trunc inside shl, if we can.
8288     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8289     if (CI && DestBitSize < SrcBitSize &&
8290         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8291       Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8292       Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8293       return BinaryOperator::CreateShl(Op0c, Op1c);
8294     }
8295     break;
8296   }
8297   }
8298   return 0;
8299 }
8300
8301 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8302   if (Instruction *Result = commonIntCastTransforms(CI))
8303     return Result;
8304   
8305   Value *Src = CI.getOperand(0);
8306   const Type *Ty = CI.getType();
8307   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8308   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8309
8310   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8311   if (DestBitWidth == 1) {
8312     Constant *One = ConstantInt::get(Src->getType(), 1);
8313     Src = Builder->CreateAnd(Src, One, "tmp");
8314     Value *Zero = Constant::getNullValue(Src->getType());
8315     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8316   }
8317
8318   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8319   ConstantInt *ShAmtV = 0;
8320   Value *ShiftOp = 0;
8321   if (Src->hasOneUse() &&
8322       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8323     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8324     
8325     // Get a mask for the bits shifting in.
8326     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8327     if (MaskedValueIsZero(ShiftOp, Mask)) {
8328       if (ShAmt >= DestBitWidth)        // All zeros.
8329         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8330       
8331       // Okay, we can shrink this.  Truncate the input, then return a new
8332       // shift.
8333       Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
8334       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8335       return BinaryOperator::CreateLShr(V1, V2);
8336     }
8337   }
8338   
8339   return 0;
8340 }
8341
8342 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8343 /// in order to eliminate the icmp.
8344 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8345                                              bool DoXform) {
8346   // If we are just checking for a icmp eq of a single bit and zext'ing it
8347   // to an integer, then shift the bit to the appropriate place and then
8348   // cast to integer to avoid the comparison.
8349   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8350     const APInt &Op1CV = Op1C->getValue();
8351       
8352     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8353     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8354     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8355         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8356       if (!DoXform) return ICI;
8357
8358       Value *In = ICI->getOperand(0);
8359       Value *Sh = ConstantInt::get(In->getType(),
8360                                    In->getType()->getScalarSizeInBits()-1);
8361       In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
8362       if (In->getType() != CI.getType())
8363         In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
8364
8365       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8366         Constant *One = ConstantInt::get(In->getType(), 1);
8367         In = Builder->CreateXor(In, One, In->getName()+".not");
8368       }
8369
8370       return ReplaceInstUsesWith(CI, In);
8371     }
8372       
8373       
8374       
8375     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8376     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8377     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8378     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8379     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8380     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8381     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8382     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8383     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8384         // This only works for EQ and NE
8385         ICI->isEquality()) {
8386       // If Op1C some other power of two, convert:
8387       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8388       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8389       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8390       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8391         
8392       APInt KnownZeroMask(~KnownZero);
8393       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8394         if (!DoXform) return ICI;
8395
8396         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8397         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8398           // (X&4) == 2 --> false
8399           // (X&4) != 2 --> true
8400           Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
8401           Res = ConstantExpr::getZExt(Res, CI.getType());
8402           return ReplaceInstUsesWith(CI, Res);
8403         }
8404           
8405         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8406         Value *In = ICI->getOperand(0);
8407         if (ShiftAmt) {
8408           // Perform a logical shr by shiftamt.
8409           // Insert the shift to put the result in the low bit.
8410           In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8411                                    In->getName()+".lobit");
8412         }
8413           
8414         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8415           Constant *One = ConstantInt::get(In->getType(), 1);
8416           In = Builder->CreateXor(In, One, "tmp");
8417         }
8418           
8419         if (CI.getType() == In->getType())
8420           return ReplaceInstUsesWith(CI, In);
8421         else
8422           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8423       }
8424     }
8425   }
8426
8427   return 0;
8428 }
8429
8430 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8431   // If one of the common conversion will work ..
8432   if (Instruction *Result = commonIntCastTransforms(CI))
8433     return Result;
8434
8435   Value *Src = CI.getOperand(0);
8436
8437   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8438   // types and if the sizes are just right we can convert this into a logical
8439   // 'and' which will be much cheaper than the pair of casts.
8440   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8441     // Get the sizes of the types involved.  We know that the intermediate type
8442     // will be smaller than A or C, but don't know the relation between A and C.
8443     Value *A = CSrc->getOperand(0);
8444     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8445     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8446     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8447     // If we're actually extending zero bits, then if
8448     // SrcSize <  DstSize: zext(a & mask)
8449     // SrcSize == DstSize: a & mask
8450     // SrcSize  > DstSize: trunc(a) & mask
8451     if (SrcSize < DstSize) {
8452       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8453       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8454       Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
8455       return new ZExtInst(And, CI.getType());
8456     }
8457     
8458     if (SrcSize == DstSize) {
8459       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8460       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8461                                                            AndValue));
8462     }
8463     if (SrcSize > DstSize) {
8464       Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
8465       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8466       return BinaryOperator::CreateAnd(Trunc, 
8467                                        ConstantInt::get(Trunc->getType(),
8468                                                                AndValue));
8469     }
8470   }
8471
8472   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8473     return transformZExtICmp(ICI, CI);
8474
8475   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8476   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8477     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8478     // of the (zext icmp) will be transformed.
8479     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8480     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8481     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8482         (transformZExtICmp(LHS, CI, false) ||
8483          transformZExtICmp(RHS, CI, false))) {
8484       Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8485       Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
8486       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8487     }
8488   }
8489
8490   // zext(trunc(t) & C) -> (t & zext(C)).
8491   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8492     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8493       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8494         Value *TI0 = TI->getOperand(0);
8495         if (TI0->getType() == CI.getType())
8496           return
8497             BinaryOperator::CreateAnd(TI0,
8498                                 ConstantExpr::getZExt(C, CI.getType()));
8499       }
8500
8501   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8502   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8503     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8504       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8505         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8506             And->getOperand(1) == C)
8507           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8508             Value *TI0 = TI->getOperand(0);
8509             if (TI0->getType() == CI.getType()) {
8510               Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8511               Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
8512               return BinaryOperator::CreateXor(NewAnd, ZC);
8513             }
8514           }
8515
8516   return 0;
8517 }
8518
8519 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8520   if (Instruction *I = commonIntCastTransforms(CI))
8521     return I;
8522   
8523   Value *Src = CI.getOperand(0);
8524   
8525   // Canonicalize sign-extend from i1 to a select.
8526   if (Src->getType() == Type::getInt1Ty(*Context))
8527     return SelectInst::Create(Src,
8528                               Constant::getAllOnesValue(CI.getType()),
8529                               Constant::getNullValue(CI.getType()));
8530
8531   // See if the value being truncated is already sign extended.  If so, just
8532   // eliminate the trunc/sext pair.
8533   if (Operator::getOpcode(Src) == Instruction::Trunc) {
8534     Value *Op = cast<User>(Src)->getOperand(0);
8535     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8536     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8537     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8538     unsigned NumSignBits = ComputeNumSignBits(Op);
8539
8540     if (OpBits == DestBits) {
8541       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8542       // bits, it is already ready.
8543       if (NumSignBits > DestBits-MidBits)
8544         return ReplaceInstUsesWith(CI, Op);
8545     } else if (OpBits < DestBits) {
8546       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8547       // bits, just sext from i32.
8548       if (NumSignBits > OpBits-MidBits)
8549         return new SExtInst(Op, CI.getType(), "tmp");
8550     } else {
8551       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8552       // bits, just truncate to i32.
8553       if (NumSignBits > OpBits-MidBits)
8554         return new TruncInst(Op, CI.getType(), "tmp");
8555     }
8556   }
8557
8558   // If the input is a shl/ashr pair of a same constant, then this is a sign
8559   // extension from a smaller value.  If we could trust arbitrary bitwidth
8560   // integers, we could turn this into a truncate to the smaller bit and then
8561   // use a sext for the whole extension.  Since we don't, look deeper and check
8562   // for a truncate.  If the source and dest are the same type, eliminate the
8563   // trunc and extend and just do shifts.  For example, turn:
8564   //   %a = trunc i32 %i to i8
8565   //   %b = shl i8 %a, 6
8566   //   %c = ashr i8 %b, 6
8567   //   %d = sext i8 %c to i32
8568   // into:
8569   //   %a = shl i32 %i, 30
8570   //   %d = ashr i32 %a, 30
8571   Value *A = 0;
8572   ConstantInt *BA = 0, *CA = 0;
8573   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8574                         m_ConstantInt(CA))) &&
8575       BA == CA && isa<TruncInst>(A)) {
8576     Value *I = cast<TruncInst>(A)->getOperand(0);
8577     if (I->getType() == CI.getType()) {
8578       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8579       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8580       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8581       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8582       I = Builder->CreateShl(I, ShAmtV, CI.getName());
8583       return BinaryOperator::CreateAShr(I, ShAmtV);
8584     }
8585   }
8586   
8587   return 0;
8588 }
8589
8590 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8591 /// in the specified FP type without changing its value.
8592 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8593                               LLVMContext *Context) {
8594   bool losesInfo;
8595   APFloat F = CFP->getValueAPF();
8596   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8597   if (!losesInfo)
8598     return ConstantFP::get(*Context, F);
8599   return 0;
8600 }
8601
8602 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8603 /// through it until we get the source value.
8604 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8605   if (Instruction *I = dyn_cast<Instruction>(V))
8606     if (I->getOpcode() == Instruction::FPExt)
8607       return LookThroughFPExtensions(I->getOperand(0), Context);
8608   
8609   // If this value is a constant, return the constant in the smallest FP type
8610   // that can accurately represent it.  This allows us to turn
8611   // (float)((double)X+2.0) into x+2.0f.
8612   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8613     if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
8614       return V;  // No constant folding of this.
8615     // See if the value can be truncated to float and then reextended.
8616     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8617       return V;
8618     if (CFP->getType() == Type::getDoubleTy(*Context))
8619       return V;  // Won't shrink.
8620     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8621       return V;
8622     // Don't try to shrink to various long double types.
8623   }
8624   
8625   return V;
8626 }
8627
8628 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8629   if (Instruction *I = commonCastTransforms(CI))
8630     return I;
8631   
8632   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8633   // smaller than the destination type, we can eliminate the truncate by doing
8634   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8635   // many builtins (sqrt, etc).
8636   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8637   if (OpI && OpI->hasOneUse()) {
8638     switch (OpI->getOpcode()) {
8639     default: break;
8640     case Instruction::FAdd:
8641     case Instruction::FSub:
8642     case Instruction::FMul:
8643     case Instruction::FDiv:
8644     case Instruction::FRem:
8645       const Type *SrcTy = OpI->getType();
8646       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8647       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8648       if (LHSTrunc->getType() != SrcTy && 
8649           RHSTrunc->getType() != SrcTy) {
8650         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8651         // If the source types were both smaller than the destination type of
8652         // the cast, do this xform.
8653         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8654             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8655           LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8656           RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
8657           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8658         }
8659       }
8660       break;  
8661     }
8662   }
8663   return 0;
8664 }
8665
8666 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8667   return commonCastTransforms(CI);
8668 }
8669
8670 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8671   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8672   if (OpI == 0)
8673     return commonCastTransforms(FI);
8674
8675   // fptoui(uitofp(X)) --> X
8676   // fptoui(sitofp(X)) --> X
8677   // This is safe if the intermediate type has enough bits in its mantissa to
8678   // accurately represent all values of X.  For example, do not do this with
8679   // i64->float->i64.  This is also safe for sitofp case, because any negative
8680   // 'X' value would cause an undefined result for the fptoui. 
8681   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8682       OpI->getOperand(0)->getType() == FI.getType() &&
8683       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8684                     OpI->getType()->getFPMantissaWidth())
8685     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8686
8687   return commonCastTransforms(FI);
8688 }
8689
8690 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8691   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8692   if (OpI == 0)
8693     return commonCastTransforms(FI);
8694   
8695   // fptosi(sitofp(X)) --> X
8696   // fptosi(uitofp(X)) --> X
8697   // This is safe if the intermediate type has enough bits in its mantissa to
8698   // accurately represent all values of X.  For example, do not do this with
8699   // i64->float->i64.  This is also safe for sitofp case, because any negative
8700   // 'X' value would cause an undefined result for the fptoui. 
8701   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8702       OpI->getOperand(0)->getType() == FI.getType() &&
8703       (int)FI.getType()->getScalarSizeInBits() <=
8704                     OpI->getType()->getFPMantissaWidth())
8705     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8706   
8707   return commonCastTransforms(FI);
8708 }
8709
8710 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8711   return commonCastTransforms(CI);
8712 }
8713
8714 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8715   return commonCastTransforms(CI);
8716 }
8717
8718 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8719   // If the destination integer type is smaller than the intptr_t type for
8720   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8721   // trunc to be exposed to other transforms.  Don't do this for extending
8722   // ptrtoint's, because we don't know if the target sign or zero extends its
8723   // pointers.
8724   if (TD &&
8725       CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8726     Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8727                                        TD->getIntPtrType(CI.getContext()),
8728                                        "tmp");
8729     return new TruncInst(P, CI.getType());
8730   }
8731   
8732   return commonPointerCastTransforms(CI);
8733 }
8734
8735 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8736   // If the source integer type is larger than the intptr_t type for
8737   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8738   // allows the trunc to be exposed to other transforms.  Don't do this for
8739   // extending inttoptr's, because we don't know if the target sign or zero
8740   // extends to pointers.
8741   if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
8742       TD->getPointerSizeInBits()) {
8743     Value *P = Builder->CreateTrunc(CI.getOperand(0),
8744                                     TD->getIntPtrType(CI.getContext()), "tmp");
8745     return new IntToPtrInst(P, CI.getType());
8746   }
8747   
8748   if (Instruction *I = commonCastTransforms(CI))
8749     return I;
8750
8751   return 0;
8752 }
8753
8754 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8755   // If the operands are integer typed then apply the integer transforms,
8756   // otherwise just apply the common ones.
8757   Value *Src = CI.getOperand(0);
8758   const Type *SrcTy = Src->getType();
8759   const Type *DestTy = CI.getType();
8760
8761   if (isa<PointerType>(SrcTy)) {
8762     if (Instruction *I = commonPointerCastTransforms(CI))
8763       return I;
8764   } else {
8765     if (Instruction *Result = commonCastTransforms(CI))
8766       return Result;
8767   }
8768
8769
8770   // Get rid of casts from one type to the same type. These are useless and can
8771   // be replaced by the operand.
8772   if (DestTy == Src->getType())
8773     return ReplaceInstUsesWith(CI, Src);
8774
8775   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8776     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8777     const Type *DstElTy = DstPTy->getElementType();
8778     const Type *SrcElTy = SrcPTy->getElementType();
8779     
8780     // If the address spaces don't match, don't eliminate the bitcast, which is
8781     // required for changing types.
8782     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8783       return 0;
8784     
8785     // If we are casting a malloc or alloca to a pointer to a type of the same
8786     // size, rewrite the allocation instruction to allocate the "right" type.
8787     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8788       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8789         return V;
8790     
8791     // If the source and destination are pointers, and this cast is equivalent
8792     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8793     // This can enhance SROA and other transforms that want type-safe pointers.
8794     Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
8795     unsigned NumZeros = 0;
8796     while (SrcElTy != DstElTy && 
8797            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8798            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8799       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8800       ++NumZeros;
8801     }
8802
8803     // If we found a path from the src to dest, create the getelementptr now.
8804     if (SrcElTy == DstElTy) {
8805       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8806       Instruction *GEP = GetElementPtrInst::Create(Src,
8807                                                    Idxs.begin(), Idxs.end(), "",
8808                                                    ((Instruction*) NULL));
8809       cast<GEPOperator>(GEP)->setIsInBounds(true);
8810       return GEP;
8811     }
8812   }
8813
8814   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8815     if (DestVTy->getNumElements() == 1) {
8816       if (!isa<VectorType>(SrcTy)) {
8817         Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
8818         return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
8819                             Constant::getNullValue(Type::getInt32Ty(*Context)));
8820       }
8821       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8822     }
8823   }
8824
8825   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8826     if (SrcVTy->getNumElements() == 1) {
8827       if (!isa<VectorType>(DestTy)) {
8828         Value *Elem = 
8829           Builder->CreateExtractElement(Src,
8830                             Constant::getNullValue(Type::getInt32Ty(*Context)));
8831         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8832       }
8833     }
8834   }
8835
8836   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8837     if (SVI->hasOneUse()) {
8838       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8839       // a bitconvert to a vector with the same # elts.
8840       if (isa<VectorType>(DestTy) && 
8841           cast<VectorType>(DestTy)->getNumElements() ==
8842                 SVI->getType()->getNumElements() &&
8843           SVI->getType()->getNumElements() ==
8844             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8845         CastInst *Tmp;
8846         // If either of the operands is a cast from CI.getType(), then
8847         // evaluating the shuffle in the casted destination's type will allow
8848         // us to eliminate at least one cast.
8849         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8850              Tmp->getOperand(0)->getType() == DestTy) ||
8851             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8852              Tmp->getOperand(0)->getType() == DestTy)) {
8853           Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8854           Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
8855           // Return a new shuffle vector.  Use the same element ID's, as we
8856           // know the vector types match #elts.
8857           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8858         }
8859       }
8860     }
8861   }
8862   return 0;
8863 }
8864
8865 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8866 ///   %C = or %A, %B
8867 ///   %D = select %cond, %C, %A
8868 /// into:
8869 ///   %C = select %cond, %B, 0
8870 ///   %D = or %A, %C
8871 ///
8872 /// Assuming that the specified instruction is an operand to the select, return
8873 /// a bitmask indicating which operands of this instruction are foldable if they
8874 /// equal the other incoming value of the select.
8875 ///
8876 static unsigned GetSelectFoldableOperands(Instruction *I) {
8877   switch (I->getOpcode()) {
8878   case Instruction::Add:
8879   case Instruction::Mul:
8880   case Instruction::And:
8881   case Instruction::Or:
8882   case Instruction::Xor:
8883     return 3;              // Can fold through either operand.
8884   case Instruction::Sub:   // Can only fold on the amount subtracted.
8885   case Instruction::Shl:   // Can only fold on the shift amount.
8886   case Instruction::LShr:
8887   case Instruction::AShr:
8888     return 1;
8889   default:
8890     return 0;              // Cannot fold
8891   }
8892 }
8893
8894 /// GetSelectFoldableConstant - For the same transformation as the previous
8895 /// function, return the identity constant that goes into the select.
8896 static Constant *GetSelectFoldableConstant(Instruction *I,
8897                                            LLVMContext *Context) {
8898   switch (I->getOpcode()) {
8899   default: llvm_unreachable("This cannot happen!");
8900   case Instruction::Add:
8901   case Instruction::Sub:
8902   case Instruction::Or:
8903   case Instruction::Xor:
8904   case Instruction::Shl:
8905   case Instruction::LShr:
8906   case Instruction::AShr:
8907     return Constant::getNullValue(I->getType());
8908   case Instruction::And:
8909     return Constant::getAllOnesValue(I->getType());
8910   case Instruction::Mul:
8911     return ConstantInt::get(I->getType(), 1);
8912   }
8913 }
8914
8915 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8916 /// have the same opcode and only one use each.  Try to simplify this.
8917 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8918                                           Instruction *FI) {
8919   if (TI->getNumOperands() == 1) {
8920     // If this is a non-volatile load or a cast from the same type,
8921     // merge.
8922     if (TI->isCast()) {
8923       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8924         return 0;
8925     } else {
8926       return 0;  // unknown unary op.
8927     }
8928
8929     // Fold this by inserting a select from the input values.
8930     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8931                                           FI->getOperand(0), SI.getName()+".v");
8932     InsertNewInstBefore(NewSI, SI);
8933     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
8934                             TI->getType());
8935   }
8936
8937   // Only handle binary operators here.
8938   if (!isa<BinaryOperator>(TI))
8939     return 0;
8940
8941   // Figure out if the operations have any operands in common.
8942   Value *MatchOp, *OtherOpT, *OtherOpF;
8943   bool MatchIsOpZero;
8944   if (TI->getOperand(0) == FI->getOperand(0)) {
8945     MatchOp  = TI->getOperand(0);
8946     OtherOpT = TI->getOperand(1);
8947     OtherOpF = FI->getOperand(1);
8948     MatchIsOpZero = true;
8949   } else if (TI->getOperand(1) == FI->getOperand(1)) {
8950     MatchOp  = TI->getOperand(1);
8951     OtherOpT = TI->getOperand(0);
8952     OtherOpF = FI->getOperand(0);
8953     MatchIsOpZero = false;
8954   } else if (!TI->isCommutative()) {
8955     return 0;
8956   } else if (TI->getOperand(0) == FI->getOperand(1)) {
8957     MatchOp  = TI->getOperand(0);
8958     OtherOpT = TI->getOperand(1);
8959     OtherOpF = FI->getOperand(0);
8960     MatchIsOpZero = true;
8961   } else if (TI->getOperand(1) == FI->getOperand(0)) {
8962     MatchOp  = TI->getOperand(1);
8963     OtherOpT = TI->getOperand(0);
8964     OtherOpF = FI->getOperand(1);
8965     MatchIsOpZero = true;
8966   } else {
8967     return 0;
8968   }
8969
8970   // If we reach here, they do have operations in common.
8971   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8972                                          OtherOpF, SI.getName()+".v");
8973   InsertNewInstBefore(NewSI, SI);
8974
8975   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8976     if (MatchIsOpZero)
8977       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8978     else
8979       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8980   }
8981   llvm_unreachable("Shouldn't get here");
8982   return 0;
8983 }
8984
8985 static bool isSelect01(Constant *C1, Constant *C2) {
8986   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
8987   if (!C1I)
8988     return false;
8989   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
8990   if (!C2I)
8991     return false;
8992   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
8993 }
8994
8995 /// FoldSelectIntoOp - Try fold the select into one of the operands to
8996 /// facilitate further optimization.
8997 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
8998                                             Value *FalseVal) {
8999   // See the comment above GetSelectFoldableOperands for a description of the
9000   // transformation we are doing here.
9001   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9002     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9003         !isa<Constant>(FalseVal)) {
9004       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9005         unsigned OpToFold = 0;
9006         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9007           OpToFold = 1;
9008         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9009           OpToFold = 2;
9010         }
9011
9012         if (OpToFold) {
9013           Constant *C = GetSelectFoldableConstant(TVI, Context);
9014           Value *OOp = TVI->getOperand(2-OpToFold);
9015           // Avoid creating select between 2 constants unless it's selecting
9016           // between 0 and 1.
9017           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9018             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9019             InsertNewInstBefore(NewSel, SI);
9020             NewSel->takeName(TVI);
9021             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9022               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9023             llvm_unreachable("Unknown instruction!!");
9024           }
9025         }
9026       }
9027     }
9028   }
9029
9030   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9031     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9032         !isa<Constant>(TrueVal)) {
9033       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9034         unsigned OpToFold = 0;
9035         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9036           OpToFold = 1;
9037         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9038           OpToFold = 2;
9039         }
9040
9041         if (OpToFold) {
9042           Constant *C = GetSelectFoldableConstant(FVI, Context);
9043           Value *OOp = FVI->getOperand(2-OpToFold);
9044           // Avoid creating select between 2 constants unless it's selecting
9045           // between 0 and 1.
9046           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9047             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9048             InsertNewInstBefore(NewSel, SI);
9049             NewSel->takeName(FVI);
9050             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9051               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9052             llvm_unreachable("Unknown instruction!!");
9053           }
9054         }
9055       }
9056     }
9057   }
9058
9059   return 0;
9060 }
9061
9062 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9063 /// ICmpInst as its first operand.
9064 ///
9065 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9066                                                    ICmpInst *ICI) {
9067   bool Changed = false;
9068   ICmpInst::Predicate Pred = ICI->getPredicate();
9069   Value *CmpLHS = ICI->getOperand(0);
9070   Value *CmpRHS = ICI->getOperand(1);
9071   Value *TrueVal = SI.getTrueValue();
9072   Value *FalseVal = SI.getFalseValue();
9073
9074   // Check cases where the comparison is with a constant that
9075   // can be adjusted to fit the min/max idiom. We may edit ICI in
9076   // place here, so make sure the select is the only user.
9077   if (ICI->hasOneUse())
9078     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9079       switch (Pred) {
9080       default: break;
9081       case ICmpInst::ICMP_ULT:
9082       case ICmpInst::ICMP_SLT: {
9083         // X < MIN ? T : F  -->  F
9084         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9085           return ReplaceInstUsesWith(SI, FalseVal);
9086         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9087         Constant *AdjustedRHS = SubOne(CI);
9088         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9089             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9090           Pred = ICmpInst::getSwappedPredicate(Pred);
9091           CmpRHS = AdjustedRHS;
9092           std::swap(FalseVal, TrueVal);
9093           ICI->setPredicate(Pred);
9094           ICI->setOperand(1, CmpRHS);
9095           SI.setOperand(1, TrueVal);
9096           SI.setOperand(2, FalseVal);
9097           Changed = true;
9098         }
9099         break;
9100       }
9101       case ICmpInst::ICMP_UGT:
9102       case ICmpInst::ICMP_SGT: {
9103         // X > MAX ? T : F  -->  F
9104         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9105           return ReplaceInstUsesWith(SI, FalseVal);
9106         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9107         Constant *AdjustedRHS = AddOne(CI);
9108         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9109             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9110           Pred = ICmpInst::getSwappedPredicate(Pred);
9111           CmpRHS = AdjustedRHS;
9112           std::swap(FalseVal, TrueVal);
9113           ICI->setPredicate(Pred);
9114           ICI->setOperand(1, CmpRHS);
9115           SI.setOperand(1, TrueVal);
9116           SI.setOperand(2, FalseVal);
9117           Changed = true;
9118         }
9119         break;
9120       }
9121       }
9122
9123       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9124       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9125       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9126       if (match(TrueVal, m_ConstantInt<-1>()) &&
9127           match(FalseVal, m_ConstantInt<0>()))
9128         Pred = ICI->getPredicate();
9129       else if (match(TrueVal, m_ConstantInt<0>()) &&
9130                match(FalseVal, m_ConstantInt<-1>()))
9131         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9132       
9133       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9134         // If we are just checking for a icmp eq of a single bit and zext'ing it
9135         // to an integer, then shift the bit to the appropriate place and then
9136         // cast to integer to avoid the comparison.
9137         const APInt &Op1CV = CI->getValue();
9138     
9139         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9140         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9141         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9142             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9143           Value *In = ICI->getOperand(0);
9144           Value *Sh = ConstantInt::get(In->getType(),
9145                                        In->getType()->getScalarSizeInBits()-1);
9146           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9147                                                         In->getName()+".lobit"),
9148                                    *ICI);
9149           if (In->getType() != SI.getType())
9150             In = CastInst::CreateIntegerCast(In, SI.getType(),
9151                                              true/*SExt*/, "tmp", ICI);
9152     
9153           if (Pred == ICmpInst::ICMP_SGT)
9154             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9155                                        In->getName()+".not"), *ICI);
9156     
9157           return ReplaceInstUsesWith(SI, In);
9158         }
9159       }
9160     }
9161
9162   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9163     // Transform (X == Y) ? X : Y  -> Y
9164     if (Pred == ICmpInst::ICMP_EQ)
9165       return ReplaceInstUsesWith(SI, FalseVal);
9166     // Transform (X != Y) ? X : Y  -> X
9167     if (Pred == ICmpInst::ICMP_NE)
9168       return ReplaceInstUsesWith(SI, TrueVal);
9169     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9170
9171   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9172     // Transform (X == Y) ? Y : X  -> X
9173     if (Pred == ICmpInst::ICMP_EQ)
9174       return ReplaceInstUsesWith(SI, FalseVal);
9175     // Transform (X != Y) ? Y : X  -> Y
9176     if (Pred == ICmpInst::ICMP_NE)
9177       return ReplaceInstUsesWith(SI, TrueVal);
9178     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9179   }
9180
9181   /// NOTE: if we wanted to, this is where to detect integer ABS
9182
9183   return Changed ? &SI : 0;
9184 }
9185
9186 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9187   Value *CondVal = SI.getCondition();
9188   Value *TrueVal = SI.getTrueValue();
9189   Value *FalseVal = SI.getFalseValue();
9190
9191   // select true, X, Y  -> X
9192   // select false, X, Y -> Y
9193   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9194     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9195
9196   // select C, X, X -> X
9197   if (TrueVal == FalseVal)
9198     return ReplaceInstUsesWith(SI, TrueVal);
9199
9200   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9201     return ReplaceInstUsesWith(SI, FalseVal);
9202   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9203     return ReplaceInstUsesWith(SI, TrueVal);
9204   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9205     if (isa<Constant>(TrueVal))
9206       return ReplaceInstUsesWith(SI, TrueVal);
9207     else
9208       return ReplaceInstUsesWith(SI, FalseVal);
9209   }
9210
9211   if (SI.getType() == Type::getInt1Ty(*Context)) {
9212     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9213       if (C->getZExtValue()) {
9214         // Change: A = select B, true, C --> A = or B, C
9215         return BinaryOperator::CreateOr(CondVal, FalseVal);
9216       } else {
9217         // Change: A = select B, false, C --> A = and !B, C
9218         Value *NotCond =
9219           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9220                                              "not."+CondVal->getName()), SI);
9221         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9222       }
9223     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9224       if (C->getZExtValue() == false) {
9225         // Change: A = select B, C, false --> A = and B, C
9226         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9227       } else {
9228         // Change: A = select B, C, true --> A = or !B, C
9229         Value *NotCond =
9230           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9231                                              "not."+CondVal->getName()), SI);
9232         return BinaryOperator::CreateOr(NotCond, TrueVal);
9233       }
9234     }
9235     
9236     // select a, b, a  -> a&b
9237     // select a, a, b  -> a|b
9238     if (CondVal == TrueVal)
9239       return BinaryOperator::CreateOr(CondVal, FalseVal);
9240     else if (CondVal == FalseVal)
9241       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9242   }
9243
9244   // Selecting between two integer constants?
9245   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9246     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9247       // select C, 1, 0 -> zext C to int
9248       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9249         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9250       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9251         // select C, 0, 1 -> zext !C to int
9252         Value *NotCond =
9253           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9254                                                "not."+CondVal->getName()), SI);
9255         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9256       }
9257
9258       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9259         // If one of the constants is zero (we know they can't both be) and we
9260         // have an icmp instruction with zero, and we have an 'and' with the
9261         // non-constant value, eliminate this whole mess.  This corresponds to
9262         // cases like this: ((X & 27) ? 27 : 0)
9263         if (TrueValC->isZero() || FalseValC->isZero())
9264           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9265               cast<Constant>(IC->getOperand(1))->isNullValue())
9266             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9267               if (ICA->getOpcode() == Instruction::And &&
9268                   isa<ConstantInt>(ICA->getOperand(1)) &&
9269                   (ICA->getOperand(1) == TrueValC ||
9270                    ICA->getOperand(1) == FalseValC) &&
9271                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9272                 // Okay, now we know that everything is set up, we just don't
9273                 // know whether we have a icmp_ne or icmp_eq and whether the 
9274                 // true or false val is the zero.
9275                 bool ShouldNotVal = !TrueValC->isZero();
9276                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9277                 Value *V = ICA;
9278                 if (ShouldNotVal)
9279                   V = InsertNewInstBefore(BinaryOperator::Create(
9280                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9281                 return ReplaceInstUsesWith(SI, V);
9282               }
9283       }
9284     }
9285
9286   // See if we are selecting two values based on a comparison of the two values.
9287   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9288     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9289       // Transform (X == Y) ? X : Y  -> Y
9290       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9291         // This is not safe in general for floating point:  
9292         // consider X== -0, Y== +0.
9293         // It becomes safe if either operand is a nonzero constant.
9294         ConstantFP *CFPt, *CFPf;
9295         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9296               !CFPt->getValueAPF().isZero()) ||
9297             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9298              !CFPf->getValueAPF().isZero()))
9299         return ReplaceInstUsesWith(SI, FalseVal);
9300       }
9301       // Transform (X != Y) ? X : Y  -> X
9302       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9303         return ReplaceInstUsesWith(SI, TrueVal);
9304       // NOTE: if we wanted to, this is where to detect MIN/MAX
9305
9306     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9307       // Transform (X == Y) ? Y : X  -> X
9308       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9309         // This is not safe in general for floating point:  
9310         // consider X== -0, Y== +0.
9311         // It becomes safe if either operand is a nonzero constant.
9312         ConstantFP *CFPt, *CFPf;
9313         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9314               !CFPt->getValueAPF().isZero()) ||
9315             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9316              !CFPf->getValueAPF().isZero()))
9317           return ReplaceInstUsesWith(SI, FalseVal);
9318       }
9319       // Transform (X != Y) ? Y : X  -> Y
9320       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9321         return ReplaceInstUsesWith(SI, TrueVal);
9322       // NOTE: if we wanted to, this is where to detect MIN/MAX
9323     }
9324     // NOTE: if we wanted to, this is where to detect ABS
9325   }
9326
9327   // See if we are selecting two values based on a comparison of the two values.
9328   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9329     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9330       return Result;
9331
9332   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9333     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9334       if (TI->hasOneUse() && FI->hasOneUse()) {
9335         Instruction *AddOp = 0, *SubOp = 0;
9336
9337         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9338         if (TI->getOpcode() == FI->getOpcode())
9339           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9340             return IV;
9341
9342         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9343         // even legal for FP.
9344         if ((TI->getOpcode() == Instruction::Sub &&
9345              FI->getOpcode() == Instruction::Add) ||
9346             (TI->getOpcode() == Instruction::FSub &&
9347              FI->getOpcode() == Instruction::FAdd)) {
9348           AddOp = FI; SubOp = TI;
9349         } else if ((FI->getOpcode() == Instruction::Sub &&
9350                     TI->getOpcode() == Instruction::Add) ||
9351                    (FI->getOpcode() == Instruction::FSub &&
9352                     TI->getOpcode() == Instruction::FAdd)) {
9353           AddOp = TI; SubOp = FI;
9354         }
9355
9356         if (AddOp) {
9357           Value *OtherAddOp = 0;
9358           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9359             OtherAddOp = AddOp->getOperand(1);
9360           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9361             OtherAddOp = AddOp->getOperand(0);
9362           }
9363
9364           if (OtherAddOp) {
9365             // So at this point we know we have (Y -> OtherAddOp):
9366             //        select C, (add X, Y), (sub X, Z)
9367             Value *NegVal;  // Compute -Z
9368             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9369               NegVal = ConstantExpr::getNeg(C);
9370             } else {
9371               NegVal = InsertNewInstBefore(
9372                     BinaryOperator::CreateNeg(SubOp->getOperand(1),
9373                                               "tmp"), SI);
9374             }
9375
9376             Value *NewTrueOp = OtherAddOp;
9377             Value *NewFalseOp = NegVal;
9378             if (AddOp != TI)
9379               std::swap(NewTrueOp, NewFalseOp);
9380             Instruction *NewSel =
9381               SelectInst::Create(CondVal, NewTrueOp,
9382                                  NewFalseOp, SI.getName() + ".p");
9383
9384             NewSel = InsertNewInstBefore(NewSel, SI);
9385             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9386           }
9387         }
9388       }
9389
9390   // See if we can fold the select into one of our operands.
9391   if (SI.getType()->isInteger()) {
9392     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9393     if (FoldI)
9394       return FoldI;
9395   }
9396
9397   if (BinaryOperator::isNot(CondVal)) {
9398     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9399     SI.setOperand(1, FalseVal);
9400     SI.setOperand(2, TrueVal);
9401     return &SI;
9402   }
9403
9404   return 0;
9405 }
9406
9407 /// EnforceKnownAlignment - If the specified pointer points to an object that
9408 /// we control, modify the object's alignment to PrefAlign. This isn't
9409 /// often possible though. If alignment is important, a more reliable approach
9410 /// is to simply align all global variables and allocation instructions to
9411 /// their preferred alignment from the beginning.
9412 ///
9413 static unsigned EnforceKnownAlignment(Value *V,
9414                                       unsigned Align, unsigned PrefAlign) {
9415
9416   User *U = dyn_cast<User>(V);
9417   if (!U) return Align;
9418
9419   switch (Operator::getOpcode(U)) {
9420   default: break;
9421   case Instruction::BitCast:
9422     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9423   case Instruction::GetElementPtr: {
9424     // If all indexes are zero, it is just the alignment of the base pointer.
9425     bool AllZeroOperands = true;
9426     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9427       if (!isa<Constant>(*i) ||
9428           !cast<Constant>(*i)->isNullValue()) {
9429         AllZeroOperands = false;
9430         break;
9431       }
9432
9433     if (AllZeroOperands) {
9434       // Treat this like a bitcast.
9435       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9436     }
9437     break;
9438   }
9439   }
9440
9441   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9442     // If there is a large requested alignment and we can, bump up the alignment
9443     // of the global.
9444     if (!GV->isDeclaration()) {
9445       if (GV->getAlignment() >= PrefAlign)
9446         Align = GV->getAlignment();
9447       else {
9448         GV->setAlignment(PrefAlign);
9449         Align = PrefAlign;
9450       }
9451     }
9452   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9453     // If there is a requested alignment and if this is an alloca, round up.  We
9454     // don't do this for malloc, because some systems can't respect the request.
9455     if (isa<AllocaInst>(AI)) {
9456       if (AI->getAlignment() >= PrefAlign)
9457         Align = AI->getAlignment();
9458       else {
9459         AI->setAlignment(PrefAlign);
9460         Align = PrefAlign;
9461       }
9462     }
9463   }
9464
9465   return Align;
9466 }
9467
9468 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9469 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9470 /// and it is more than the alignment of the ultimate object, see if we can
9471 /// increase the alignment of the ultimate object, making this check succeed.
9472 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9473                                                   unsigned PrefAlign) {
9474   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9475                       sizeof(PrefAlign) * CHAR_BIT;
9476   APInt Mask = APInt::getAllOnesValue(BitWidth);
9477   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9478   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9479   unsigned TrailZ = KnownZero.countTrailingOnes();
9480   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9481
9482   if (PrefAlign > Align)
9483     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9484   
9485     // We don't need to make any adjustment.
9486   return Align;
9487 }
9488
9489 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9490   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9491   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9492   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9493   unsigned CopyAlign = MI->getAlignment();
9494
9495   if (CopyAlign < MinAlign) {
9496     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), 
9497                                              MinAlign, false));
9498     return MI;
9499   }
9500   
9501   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9502   // load/store.
9503   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9504   if (MemOpLength == 0) return 0;
9505   
9506   // Source and destination pointer types are always "i8*" for intrinsic.  See
9507   // if the size is something we can handle with a single primitive load/store.
9508   // A single load+store correctly handles overlapping memory in the memmove
9509   // case.
9510   unsigned Size = MemOpLength->getZExtValue();
9511   if (Size == 0) return MI;  // Delete this mem transfer.
9512   
9513   if (Size > 8 || (Size&(Size-1)))
9514     return 0;  // If not 1/2/4/8 bytes, exit.
9515   
9516   // Use an integer load+store unless we can find something better.
9517   Type *NewPtrTy =
9518                 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
9519   
9520   // Memcpy forces the use of i8* for the source and destination.  That means
9521   // that if you're using memcpy to move one double around, you'll get a cast
9522   // from double* to i8*.  We'd much rather use a double load+store rather than
9523   // an i64 load+store, here because this improves the odds that the source or
9524   // dest address will be promotable.  See if we can find a better type than the
9525   // integer datatype.
9526   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9527     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9528     if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9529       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9530       // down through these levels if so.
9531       while (!SrcETy->isSingleValueType()) {
9532         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9533           if (STy->getNumElements() == 1)
9534             SrcETy = STy->getElementType(0);
9535           else
9536             break;
9537         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9538           if (ATy->getNumElements() == 1)
9539             SrcETy = ATy->getElementType();
9540           else
9541             break;
9542         } else
9543           break;
9544       }
9545       
9546       if (SrcETy->isSingleValueType())
9547         NewPtrTy = PointerType::getUnqual(SrcETy);
9548     }
9549   }
9550   
9551   
9552   // If the memcpy/memmove provides better alignment info than we can
9553   // infer, use it.
9554   SrcAlign = std::max(SrcAlign, CopyAlign);
9555   DstAlign = std::max(DstAlign, CopyAlign);
9556   
9557   Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9558   Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
9559   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9560   InsertNewInstBefore(L, *MI);
9561   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9562
9563   // Set the size of the copy to 0, it will be deleted on the next iteration.
9564   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9565   return MI;
9566 }
9567
9568 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9569   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9570   if (MI->getAlignment() < Alignment) {
9571     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9572                                              Alignment, false));
9573     return MI;
9574   }
9575   
9576   // Extract the length and alignment and fill if they are constant.
9577   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9578   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9579   if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
9580     return 0;
9581   uint64_t Len = LenC->getZExtValue();
9582   Alignment = MI->getAlignment();
9583   
9584   // If the length is zero, this is a no-op
9585   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9586   
9587   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9588   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9589     const Type *ITy = IntegerType::get(*Context, Len*8);  // n=1 -> i8.
9590     
9591     Value *Dest = MI->getDest();
9592     Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
9593
9594     // Alignment 0 is identity for alignment 1 for memset, but not store.
9595     if (Alignment == 0) Alignment = 1;
9596     
9597     // Extract the fill value and store.
9598     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9599     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
9600                                       Dest, false, Alignment), *MI);
9601     
9602     // Set the size of the copy to 0, it will be deleted on the next iteration.
9603     MI->setLength(Constant::getNullValue(LenC->getType()));
9604     return MI;
9605   }
9606
9607   return 0;
9608 }
9609
9610
9611 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9612 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9613 /// the heavy lifting.
9614 ///
9615 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9616   // If the caller function is nounwind, mark the call as nounwind, even if the
9617   // callee isn't.
9618   if (CI.getParent()->getParent()->doesNotThrow() &&
9619       !CI.doesNotThrow()) {
9620     CI.setDoesNotThrow();
9621     return &CI;
9622   }
9623   
9624   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9625   if (!II) return visitCallSite(&CI);
9626   
9627   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9628   // visitCallSite.
9629   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9630     bool Changed = false;
9631
9632     // memmove/cpy/set of zero bytes is a noop.
9633     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9634       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9635
9636       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9637         if (CI->getZExtValue() == 1) {
9638           // Replace the instruction with just byte operations.  We would
9639           // transform other cases to loads/stores, but we don't know if
9640           // alignment is sufficient.
9641         }
9642     }
9643
9644     // If we have a memmove and the source operation is a constant global,
9645     // then the source and dest pointers can't alias, so we can change this
9646     // into a call to memcpy.
9647     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9648       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9649         if (GVSrc->isConstant()) {
9650           Module *M = CI.getParent()->getParent()->getParent();
9651           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9652           const Type *Tys[1];
9653           Tys[0] = CI.getOperand(3)->getType();
9654           CI.setOperand(0, 
9655                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9656           Changed = true;
9657         }
9658
9659       // memmove(x,x,size) -> noop.
9660       if (MMI->getSource() == MMI->getDest())
9661         return EraseInstFromFunction(CI);
9662     }
9663
9664     // If we can determine a pointer alignment that is bigger than currently
9665     // set, update the alignment.
9666     if (isa<MemTransferInst>(MI)) {
9667       if (Instruction *I = SimplifyMemTransfer(MI))
9668         return I;
9669     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9670       if (Instruction *I = SimplifyMemSet(MSI))
9671         return I;
9672     }
9673           
9674     if (Changed) return II;
9675   }
9676   
9677   switch (II->getIntrinsicID()) {
9678   default: break;
9679   case Intrinsic::bswap:
9680     // bswap(bswap(x)) -> x
9681     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9682       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9683         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9684     break;
9685   case Intrinsic::ppc_altivec_lvx:
9686   case Intrinsic::ppc_altivec_lvxl:
9687   case Intrinsic::x86_sse_loadu_ps:
9688   case Intrinsic::x86_sse2_loadu_pd:
9689   case Intrinsic::x86_sse2_loadu_dq:
9690     // Turn PPC lvx     -> load if the pointer is known aligned.
9691     // Turn X86 loadups -> load if the pointer is known aligned.
9692     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9693       Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9694                                          PointerType::getUnqual(II->getType()));
9695       return new LoadInst(Ptr);
9696     }
9697     break;
9698   case Intrinsic::ppc_altivec_stvx:
9699   case Intrinsic::ppc_altivec_stvxl:
9700     // Turn stvx -> store if the pointer is known aligned.
9701     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9702       const Type *OpPtrTy = 
9703         PointerType::getUnqual(II->getOperand(1)->getType());
9704       Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
9705       return new StoreInst(II->getOperand(1), Ptr);
9706     }
9707     break;
9708   case Intrinsic::x86_sse_storeu_ps:
9709   case Intrinsic::x86_sse2_storeu_pd:
9710   case Intrinsic::x86_sse2_storeu_dq:
9711     // Turn X86 storeu -> store if the pointer is known aligned.
9712     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9713       const Type *OpPtrTy = 
9714         PointerType::getUnqual(II->getOperand(2)->getType());
9715       Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
9716       return new StoreInst(II->getOperand(2), Ptr);
9717     }
9718     break;
9719     
9720   case Intrinsic::x86_sse_cvttss2si: {
9721     // These intrinsics only demands the 0th element of its input vector.  If
9722     // we can simplify the input based on that, do so now.
9723     unsigned VWidth =
9724       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9725     APInt DemandedElts(VWidth, 1);
9726     APInt UndefElts(VWidth, 0);
9727     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9728                                               UndefElts)) {
9729       II->setOperand(1, V);
9730       return II;
9731     }
9732     break;
9733   }
9734     
9735   case Intrinsic::ppc_altivec_vperm:
9736     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9737     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9738       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9739       
9740       // Check that all of the elements are integer constants or undefs.
9741       bool AllEltsOk = true;
9742       for (unsigned i = 0; i != 16; ++i) {
9743         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9744             !isa<UndefValue>(Mask->getOperand(i))) {
9745           AllEltsOk = false;
9746           break;
9747         }
9748       }
9749       
9750       if (AllEltsOk) {
9751         // Cast the input vectors to byte vectors.
9752         Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9753         Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
9754         Value *Result = UndefValue::get(Op0->getType());
9755         
9756         // Only extract each element once.
9757         Value *ExtractedElts[32];
9758         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9759         
9760         for (unsigned i = 0; i != 16; ++i) {
9761           if (isa<UndefValue>(Mask->getOperand(i)))
9762             continue;
9763           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9764           Idx &= 31;  // Match the hardware behavior.
9765           
9766           if (ExtractedElts[Idx] == 0) {
9767             ExtractedElts[Idx] = 
9768               Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1, 
9769                   ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9770                                             "tmp");
9771           }
9772         
9773           // Insert this value into the result vector.
9774           Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9775                          ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9776                                                 "tmp");
9777         }
9778         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9779       }
9780     }
9781     break;
9782
9783   case Intrinsic::stackrestore: {
9784     // If the save is right next to the restore, remove the restore.  This can
9785     // happen when variable allocas are DCE'd.
9786     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9787       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9788         BasicBlock::iterator BI = SS;
9789         if (&*++BI == II)
9790           return EraseInstFromFunction(CI);
9791       }
9792     }
9793     
9794     // Scan down this block to see if there is another stack restore in the
9795     // same block without an intervening call/alloca.
9796     BasicBlock::iterator BI = II;
9797     TerminatorInst *TI = II->getParent()->getTerminator();
9798     bool CannotRemove = false;
9799     for (++BI; &*BI != TI; ++BI) {
9800       if (isa<AllocaInst>(BI)) {
9801         CannotRemove = true;
9802         break;
9803       }
9804       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9805         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9806           // If there is a stackrestore below this one, remove this one.
9807           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9808             return EraseInstFromFunction(CI);
9809           // Otherwise, ignore the intrinsic.
9810         } else {
9811           // If we found a non-intrinsic call, we can't remove the stack
9812           // restore.
9813           CannotRemove = true;
9814           break;
9815         }
9816       }
9817     }
9818     
9819     // If the stack restore is in a return/unwind block and if there are no
9820     // allocas or calls between the restore and the return, nuke the restore.
9821     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9822       return EraseInstFromFunction(CI);
9823     break;
9824   }
9825   }
9826
9827   return visitCallSite(II);
9828 }
9829
9830 // InvokeInst simplification
9831 //
9832 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9833   return visitCallSite(&II);
9834 }
9835
9836 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9837 /// passed through the varargs area, we can eliminate the use of the cast.
9838 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9839                                          const CastInst * const CI,
9840                                          const TargetData * const TD,
9841                                          const int ix) {
9842   if (!CI->isLosslessCast())
9843     return false;
9844
9845   // The size of ByVal arguments is derived from the type, so we
9846   // can't change to a type with a different size.  If the size were
9847   // passed explicitly we could avoid this check.
9848   if (!CS.paramHasAttr(ix, Attribute::ByVal))
9849     return true;
9850
9851   const Type* SrcTy = 
9852             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9853   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9854   if (!SrcTy->isSized() || !DstTy->isSized())
9855     return false;
9856   if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
9857     return false;
9858   return true;
9859 }
9860
9861 // visitCallSite - Improvements for call and invoke instructions.
9862 //
9863 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9864   bool Changed = false;
9865
9866   // If the callee is a constexpr cast of a function, attempt to move the cast
9867   // to the arguments of the call/invoke.
9868   if (transformConstExprCastCall(CS)) return 0;
9869
9870   Value *Callee = CS.getCalledValue();
9871
9872   if (Function *CalleeF = dyn_cast<Function>(Callee))
9873     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9874       Instruction *OldCall = CS.getInstruction();
9875       // If the call and callee calling conventions don't match, this call must
9876       // be unreachable, as the call is undefined.
9877       new StoreInst(ConstantInt::getTrue(*Context),
9878                 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), 
9879                                   OldCall);
9880       if (!OldCall->use_empty())
9881         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9882       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
9883         return EraseInstFromFunction(*OldCall);
9884       return 0;
9885     }
9886
9887   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9888     // This instruction is not reachable, just remove it.  We insert a store to
9889     // undef so that we know that this code is not reachable, despite the fact
9890     // that we can't modify the CFG here.
9891     new StoreInst(ConstantInt::getTrue(*Context),
9892                UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
9893                   CS.getInstruction());
9894
9895     if (!CS.getInstruction()->use_empty())
9896       CS.getInstruction()->
9897         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9898
9899     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9900       // Don't break the CFG, insert a dummy cond branch.
9901       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9902                          ConstantInt::getTrue(*Context), II);
9903     }
9904     return EraseInstFromFunction(*CS.getInstruction());
9905   }
9906
9907   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9908     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9909       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9910         return transformCallThroughTrampoline(CS);
9911
9912   const PointerType *PTy = cast<PointerType>(Callee->getType());
9913   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9914   if (FTy->isVarArg()) {
9915     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9916     // See if we can optimize any arguments passed through the varargs area of
9917     // the call.
9918     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9919            E = CS.arg_end(); I != E; ++I, ++ix) {
9920       CastInst *CI = dyn_cast<CastInst>(*I);
9921       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9922         *I = CI->getOperand(0);
9923         Changed = true;
9924       }
9925     }
9926   }
9927
9928   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
9929     // Inline asm calls cannot throw - mark them 'nounwind'.
9930     CS.setDoesNotThrow();
9931     Changed = true;
9932   }
9933
9934   return Changed ? CS.getInstruction() : 0;
9935 }
9936
9937 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
9938 // attempt to move the cast to the arguments of the call/invoke.
9939 //
9940 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9941   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9942   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9943   if (CE->getOpcode() != Instruction::BitCast || 
9944       !isa<Function>(CE->getOperand(0)))
9945     return false;
9946   Function *Callee = cast<Function>(CE->getOperand(0));
9947   Instruction *Caller = CS.getInstruction();
9948   const AttrListPtr &CallerPAL = CS.getAttributes();
9949
9950   // Okay, this is a cast from a function to a different type.  Unless doing so
9951   // would cause a type conversion of one of our arguments, change this call to
9952   // be a direct call with arguments casted to the appropriate types.
9953   //
9954   const FunctionType *FT = Callee->getFunctionType();
9955   const Type *OldRetTy = Caller->getType();
9956   const Type *NewRetTy = FT->getReturnType();
9957
9958   if (isa<StructType>(NewRetTy))
9959     return false; // TODO: Handle multiple return values.
9960
9961   // Check to see if we are changing the return type...
9962   if (OldRetTy != NewRetTy) {
9963     if (Callee->isDeclaration() &&
9964         // Conversion is ok if changing from one pointer type to another or from
9965         // a pointer to an integer of the same size.
9966         !((isa<PointerType>(OldRetTy) || !TD ||
9967            OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
9968           (isa<PointerType>(NewRetTy) || !TD ||
9969            NewRetTy == TD->getIntPtrType(Caller->getContext()))))
9970       return false;   // Cannot transform this return value.
9971
9972     if (!Caller->use_empty() &&
9973         // void -> non-void is handled specially
9974         NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
9975       return false;   // Cannot transform this return value.
9976
9977     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9978       Attributes RAttrs = CallerPAL.getRetAttributes();
9979       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
9980         return false;   // Attribute not compatible with transformed value.
9981     }
9982
9983     // If the callsite is an invoke instruction, and the return value is used by
9984     // a PHI node in a successor, we cannot change the return type of the call
9985     // because there is no place to put the cast instruction (without breaking
9986     // the critical edge).  Bail out in this case.
9987     if (!Caller->use_empty())
9988       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9989         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9990              UI != E; ++UI)
9991           if (PHINode *PN = dyn_cast<PHINode>(*UI))
9992             if (PN->getParent() == II->getNormalDest() ||
9993                 PN->getParent() == II->getUnwindDest())
9994               return false;
9995   }
9996
9997   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9998   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9999
10000   CallSite::arg_iterator AI = CS.arg_begin();
10001   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10002     const Type *ParamTy = FT->getParamType(i);
10003     const Type *ActTy = (*AI)->getType();
10004
10005     if (!CastInst::isCastable(ActTy, ParamTy))
10006       return false;   // Cannot transform this parameter value.
10007
10008     if (CallerPAL.getParamAttributes(i + 1) 
10009         & Attribute::typeIncompatible(ParamTy))
10010       return false;   // Attribute not compatible with transformed value.
10011
10012     // Converting from one pointer type to another or between a pointer and an
10013     // integer of the same size is safe even if we do not have a body.
10014     bool isConvertible = ActTy == ParamTy ||
10015       (TD && ((isa<PointerType>(ParamTy) ||
10016       ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10017               (isa<PointerType>(ActTy) ||
10018               ActTy == TD->getIntPtrType(Caller->getContext()))));
10019     if (Callee->isDeclaration() && !isConvertible) return false;
10020   }
10021
10022   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10023       Callee->isDeclaration())
10024     return false;   // Do not delete arguments unless we have a function body.
10025
10026   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10027       !CallerPAL.isEmpty())
10028     // In this case we have more arguments than the new function type, but we
10029     // won't be dropping them.  Check that these extra arguments have attributes
10030     // that are compatible with being a vararg call argument.
10031     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10032       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10033         break;
10034       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10035       if (PAttrs & Attribute::VarArgsIncompatible)
10036         return false;
10037     }
10038
10039   // Okay, we decided that this is a safe thing to do: go ahead and start
10040   // inserting cast instructions as necessary...
10041   std::vector<Value*> Args;
10042   Args.reserve(NumActualArgs);
10043   SmallVector<AttributeWithIndex, 8> attrVec;
10044   attrVec.reserve(NumCommonArgs);
10045
10046   // Get any return attributes.
10047   Attributes RAttrs = CallerPAL.getRetAttributes();
10048
10049   // If the return value is not being used, the type may not be compatible
10050   // with the existing attributes.  Wipe out any problematic attributes.
10051   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10052
10053   // Add the new return attributes.
10054   if (RAttrs)
10055     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10056
10057   AI = CS.arg_begin();
10058   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10059     const Type *ParamTy = FT->getParamType(i);
10060     if ((*AI)->getType() == ParamTy) {
10061       Args.push_back(*AI);
10062     } else {
10063       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10064           false, ParamTy, false);
10065       Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
10066     }
10067
10068     // Add any parameter attributes.
10069     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10070       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10071   }
10072
10073   // If the function takes more arguments than the call was taking, add them
10074   // now.
10075   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10076     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10077
10078   // If we are removing arguments to the function, emit an obnoxious warning.
10079   if (FT->getNumParams() < NumActualArgs) {
10080     if (!FT->isVarArg()) {
10081       errs() << "WARNING: While resolving call to function '"
10082              << Callee->getName() << "' arguments were dropped!\n";
10083     } else {
10084       // Add all of the arguments in their promoted form to the arg list.
10085       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10086         const Type *PTy = getPromotedType((*AI)->getType());
10087         if (PTy != (*AI)->getType()) {
10088           // Must promote to pass through va_arg area!
10089           Instruction::CastOps opcode =
10090             CastInst::getCastOpcode(*AI, false, PTy, false);
10091           Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
10092         } else {
10093           Args.push_back(*AI);
10094         }
10095
10096         // Add any parameter attributes.
10097         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10098           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10099       }
10100     }
10101   }
10102
10103   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10104     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10105
10106   if (NewRetTy == Type::getVoidTy(*Context))
10107     Caller->setName("");   // Void type should not have a name.
10108
10109   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10110                                                      attrVec.end());
10111
10112   Instruction *NC;
10113   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10114     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10115                             Args.begin(), Args.end(),
10116                             Caller->getName(), Caller);
10117     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10118     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10119   } else {
10120     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10121                           Caller->getName(), Caller);
10122     CallInst *CI = cast<CallInst>(Caller);
10123     if (CI->isTailCall())
10124       cast<CallInst>(NC)->setTailCall();
10125     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10126     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10127   }
10128
10129   // Insert a cast of the return type as necessary.
10130   Value *NV = NC;
10131   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10132     if (NV->getType() != Type::getVoidTy(*Context)) {
10133       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10134                                                             OldRetTy, false);
10135       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10136
10137       // If this is an invoke instruction, we should insert it after the first
10138       // non-phi, instruction in the normal successor block.
10139       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10140         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10141         InsertNewInstBefore(NC, *I);
10142       } else {
10143         // Otherwise, it's a call, just insert cast right after the call instr
10144         InsertNewInstBefore(NC, *Caller);
10145       }
10146       Worklist.AddUsersToWorkList(*Caller);
10147     } else {
10148       NV = UndefValue::get(Caller->getType());
10149     }
10150   }
10151
10152   if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
10153     Caller->replaceAllUsesWith(NV);
10154   Caller->eraseFromParent();
10155   Worklist.Remove(Caller);
10156   return true;
10157 }
10158
10159 // transformCallThroughTrampoline - Turn a call to a function created by the
10160 // init_trampoline intrinsic into a direct call to the underlying function.
10161 //
10162 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10163   Value *Callee = CS.getCalledValue();
10164   const PointerType *PTy = cast<PointerType>(Callee->getType());
10165   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10166   const AttrListPtr &Attrs = CS.getAttributes();
10167
10168   // If the call already has the 'nest' attribute somewhere then give up -
10169   // otherwise 'nest' would occur twice after splicing in the chain.
10170   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10171     return 0;
10172
10173   IntrinsicInst *Tramp =
10174     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10175
10176   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10177   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10178   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10179
10180   const AttrListPtr &NestAttrs = NestF->getAttributes();
10181   if (!NestAttrs.isEmpty()) {
10182     unsigned NestIdx = 1;
10183     const Type *NestTy = 0;
10184     Attributes NestAttr = Attribute::None;
10185
10186     // Look for a parameter marked with the 'nest' attribute.
10187     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10188          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10189       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10190         // Record the parameter type and any other attributes.
10191         NestTy = *I;
10192         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10193         break;
10194       }
10195
10196     if (NestTy) {
10197       Instruction *Caller = CS.getInstruction();
10198       std::vector<Value*> NewArgs;
10199       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10200
10201       SmallVector<AttributeWithIndex, 8> NewAttrs;
10202       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10203
10204       // Insert the nest argument into the call argument list, which may
10205       // mean appending it.  Likewise for attributes.
10206
10207       // Add any result attributes.
10208       if (Attributes Attr = Attrs.getRetAttributes())
10209         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10210
10211       {
10212         unsigned Idx = 1;
10213         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10214         do {
10215           if (Idx == NestIdx) {
10216             // Add the chain argument and attributes.
10217             Value *NestVal = Tramp->getOperand(3);
10218             if (NestVal->getType() != NestTy)
10219               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10220             NewArgs.push_back(NestVal);
10221             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10222           }
10223
10224           if (I == E)
10225             break;
10226
10227           // Add the original argument and attributes.
10228           NewArgs.push_back(*I);
10229           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10230             NewAttrs.push_back
10231               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10232
10233           ++Idx, ++I;
10234         } while (1);
10235       }
10236
10237       // Add any function attributes.
10238       if (Attributes Attr = Attrs.getFnAttributes())
10239         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10240
10241       // The trampoline may have been bitcast to a bogus type (FTy).
10242       // Handle this by synthesizing a new function type, equal to FTy
10243       // with the chain parameter inserted.
10244
10245       std::vector<const Type*> NewTypes;
10246       NewTypes.reserve(FTy->getNumParams()+1);
10247
10248       // Insert the chain's type into the list of parameter types, which may
10249       // mean appending it.
10250       {
10251         unsigned Idx = 1;
10252         FunctionType::param_iterator I = FTy->param_begin(),
10253           E = FTy->param_end();
10254
10255         do {
10256           if (Idx == NestIdx)
10257             // Add the chain's type.
10258             NewTypes.push_back(NestTy);
10259
10260           if (I == E)
10261             break;
10262
10263           // Add the original type.
10264           NewTypes.push_back(*I);
10265
10266           ++Idx, ++I;
10267         } while (1);
10268       }
10269
10270       // Replace the trampoline call with a direct call.  Let the generic
10271       // code sort out any function type mismatches.
10272       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 
10273                                                 FTy->isVarArg());
10274       Constant *NewCallee =
10275         NestF->getType() == PointerType::getUnqual(NewFTy) ?
10276         NestF : ConstantExpr::getBitCast(NestF, 
10277                                          PointerType::getUnqual(NewFTy));
10278       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10279                                                    NewAttrs.end());
10280
10281       Instruction *NewCaller;
10282       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10283         NewCaller = InvokeInst::Create(NewCallee,
10284                                        II->getNormalDest(), II->getUnwindDest(),
10285                                        NewArgs.begin(), NewArgs.end(),
10286                                        Caller->getName(), Caller);
10287         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10288         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10289       } else {
10290         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10291                                      Caller->getName(), Caller);
10292         if (cast<CallInst>(Caller)->isTailCall())
10293           cast<CallInst>(NewCaller)->setTailCall();
10294         cast<CallInst>(NewCaller)->
10295           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10296         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10297       }
10298       if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
10299         Caller->replaceAllUsesWith(NewCaller);
10300       Caller->eraseFromParent();
10301       Worklist.Remove(Caller);
10302       return 0;
10303     }
10304   }
10305
10306   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10307   // parameter, there is no need to adjust the argument list.  Let the generic
10308   // code sort out any function type mismatches.
10309   Constant *NewCallee =
10310     NestF->getType() == PTy ? NestF : 
10311                               ConstantExpr::getBitCast(NestF, PTy);
10312   CS.setCalledFunction(NewCallee);
10313   return CS.getInstruction();
10314 }
10315
10316 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10317 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10318 /// and a single binop.
10319 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10320   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10321   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10322   unsigned Opc = FirstInst->getOpcode();
10323   Value *LHSVal = FirstInst->getOperand(0);
10324   Value *RHSVal = FirstInst->getOperand(1);
10325     
10326   const Type *LHSType = LHSVal->getType();
10327   const Type *RHSType = RHSVal->getType();
10328   
10329   // Scan to see if all operands are the same opcode, all have one use, and all
10330   // kill their operands (i.e. the operands have one use).
10331   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10332     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10333     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10334         // Verify type of the LHS matches so we don't fold cmp's of different
10335         // types or GEP's with different index types.
10336         I->getOperand(0)->getType() != LHSType ||
10337         I->getOperand(1)->getType() != RHSType)
10338       return 0;
10339
10340     // If they are CmpInst instructions, check their predicates
10341     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10342       if (cast<CmpInst>(I)->getPredicate() !=
10343           cast<CmpInst>(FirstInst)->getPredicate())
10344         return 0;
10345     
10346     // Keep track of which operand needs a phi node.
10347     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10348     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10349   }
10350   
10351   // Otherwise, this is safe to transform!
10352   
10353   Value *InLHS = FirstInst->getOperand(0);
10354   Value *InRHS = FirstInst->getOperand(1);
10355   PHINode *NewLHS = 0, *NewRHS = 0;
10356   if (LHSVal == 0) {
10357     NewLHS = PHINode::Create(LHSType,
10358                              FirstInst->getOperand(0)->getName() + ".pn");
10359     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10360     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10361     InsertNewInstBefore(NewLHS, PN);
10362     LHSVal = NewLHS;
10363   }
10364   
10365   if (RHSVal == 0) {
10366     NewRHS = PHINode::Create(RHSType,
10367                              FirstInst->getOperand(1)->getName() + ".pn");
10368     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10369     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10370     InsertNewInstBefore(NewRHS, PN);
10371     RHSVal = NewRHS;
10372   }
10373   
10374   // Add all operands to the new PHIs.
10375   if (NewLHS || NewRHS) {
10376     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10377       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10378       if (NewLHS) {
10379         Value *NewInLHS = InInst->getOperand(0);
10380         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10381       }
10382       if (NewRHS) {
10383         Value *NewInRHS = InInst->getOperand(1);
10384         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10385       }
10386     }
10387   }
10388     
10389   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10390     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10391   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10392   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10393                          LHSVal, RHSVal);
10394 }
10395
10396 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10397   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10398   
10399   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10400                                         FirstInst->op_end());
10401   // This is true if all GEP bases are allocas and if all indices into them are
10402   // constants.
10403   bool AllBasePointersAreAllocas = true;
10404   
10405   // Scan to see if all operands are the same opcode, all have one use, and all
10406   // kill their operands (i.e. the operands have one use).
10407   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10408     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10409     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10410       GEP->getNumOperands() != FirstInst->getNumOperands())
10411       return 0;
10412
10413     // Keep track of whether or not all GEPs are of alloca pointers.
10414     if (AllBasePointersAreAllocas &&
10415         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10416          !GEP->hasAllConstantIndices()))
10417       AllBasePointersAreAllocas = false;
10418     
10419     // Compare the operand lists.
10420     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10421       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10422         continue;
10423       
10424       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10425       // if one of the PHIs has a constant for the index.  The index may be
10426       // substantially cheaper to compute for the constants, so making it a
10427       // variable index could pessimize the path.  This also handles the case
10428       // for struct indices, which must always be constant.
10429       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10430           isa<ConstantInt>(GEP->getOperand(op)))
10431         return 0;
10432       
10433       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10434         return 0;
10435       FixedOperands[op] = 0;  // Needs a PHI.
10436     }
10437   }
10438   
10439   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10440   // bother doing this transformation.  At best, this will just save a bit of
10441   // offset calculation, but all the predecessors will have to materialize the
10442   // stack address into a register anyway.  We'd actually rather *clone* the
10443   // load up into the predecessors so that we have a load of a gep of an alloca,
10444   // which can usually all be folded into the load.
10445   if (AllBasePointersAreAllocas)
10446     return 0;
10447   
10448   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10449   // that is variable.
10450   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10451   
10452   bool HasAnyPHIs = false;
10453   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10454     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10455     Value *FirstOp = FirstInst->getOperand(i);
10456     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10457                                      FirstOp->getName()+".pn");
10458     InsertNewInstBefore(NewPN, PN);
10459     
10460     NewPN->reserveOperandSpace(e);
10461     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10462     OperandPhis[i] = NewPN;
10463     FixedOperands[i] = NewPN;
10464     HasAnyPHIs = true;
10465   }
10466
10467   
10468   // Add all operands to the new PHIs.
10469   if (HasAnyPHIs) {
10470     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10471       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10472       BasicBlock *InBB = PN.getIncomingBlock(i);
10473       
10474       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10475         if (PHINode *OpPhi = OperandPhis[op])
10476           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10477     }
10478   }
10479   
10480   Value *Base = FixedOperands[0];
10481   GetElementPtrInst *GEP =
10482     GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10483                               FixedOperands.end());
10484   if (cast<GEPOperator>(FirstInst)->isInBounds())
10485     cast<GEPOperator>(GEP)->setIsInBounds(true);
10486   return GEP;
10487 }
10488
10489
10490 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10491 /// sink the load out of the block that defines it.  This means that it must be
10492 /// obvious the value of the load is not changed from the point of the load to
10493 /// the end of the block it is in.
10494 ///
10495 /// Finally, it is safe, but not profitable, to sink a load targetting a
10496 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10497 /// to a register.
10498 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10499   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10500   
10501   for (++BBI; BBI != E; ++BBI)
10502     if (BBI->mayWriteToMemory())
10503       return false;
10504   
10505   // Check for non-address taken alloca.  If not address-taken already, it isn't
10506   // profitable to do this xform.
10507   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10508     bool isAddressTaken = false;
10509     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10510          UI != E; ++UI) {
10511       if (isa<LoadInst>(UI)) continue;
10512       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10513         // If storing TO the alloca, then the address isn't taken.
10514         if (SI->getOperand(1) == AI) continue;
10515       }
10516       isAddressTaken = true;
10517       break;
10518     }
10519     
10520     if (!isAddressTaken && AI->isStaticAlloca())
10521       return false;
10522   }
10523   
10524   // If this load is a load from a GEP with a constant offset from an alloca,
10525   // then we don't want to sink it.  In its present form, it will be
10526   // load [constant stack offset].  Sinking it will cause us to have to
10527   // materialize the stack addresses in each predecessor in a register only to
10528   // do a shared load from register in the successor.
10529   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10530     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10531       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10532         return false;
10533   
10534   return true;
10535 }
10536
10537
10538 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10539 // operator and they all are only used by the PHI, PHI together their
10540 // inputs, and do the operation once, to the result of the PHI.
10541 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10542   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10543
10544   // Scan the instruction, looking for input operations that can be folded away.
10545   // If all input operands to the phi are the same instruction (e.g. a cast from
10546   // the same type or "+42") we can pull the operation through the PHI, reducing
10547   // code size and simplifying code.
10548   Constant *ConstantOp = 0;
10549   const Type *CastSrcTy = 0;
10550   bool isVolatile = false;
10551   if (isa<CastInst>(FirstInst)) {
10552     CastSrcTy = FirstInst->getOperand(0)->getType();
10553   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10554     // Can fold binop, compare or shift here if the RHS is a constant, 
10555     // otherwise call FoldPHIArgBinOpIntoPHI.
10556     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10557     if (ConstantOp == 0)
10558       return FoldPHIArgBinOpIntoPHI(PN);
10559   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10560     isVolatile = LI->isVolatile();
10561     // We can't sink the load if the loaded value could be modified between the
10562     // load and the PHI.
10563     if (LI->getParent() != PN.getIncomingBlock(0) ||
10564         !isSafeAndProfitableToSinkLoad(LI))
10565       return 0;
10566     
10567     // If the PHI is of volatile loads and the load block has multiple
10568     // successors, sinking it would remove a load of the volatile value from
10569     // the path through the other successor.
10570     if (isVolatile &&
10571         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10572       return 0;
10573     
10574   } else if (isa<GetElementPtrInst>(FirstInst)) {
10575     return FoldPHIArgGEPIntoPHI(PN);
10576   } else {
10577     return 0;  // Cannot fold this operation.
10578   }
10579
10580   // Check to see if all arguments are the same operation.
10581   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10582     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10583     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10584     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10585       return 0;
10586     if (CastSrcTy) {
10587       if (I->getOperand(0)->getType() != CastSrcTy)
10588         return 0;  // Cast operation must match.
10589     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10590       // We can't sink the load if the loaded value could be modified between 
10591       // the load and the PHI.
10592       if (LI->isVolatile() != isVolatile ||
10593           LI->getParent() != PN.getIncomingBlock(i) ||
10594           !isSafeAndProfitableToSinkLoad(LI))
10595         return 0;
10596       
10597       // If the PHI is of volatile loads and the load block has multiple
10598       // successors, sinking it would remove a load of the volatile value from
10599       // the path through the other successor.
10600       if (isVolatile &&
10601           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10602         return 0;
10603       
10604     } else if (I->getOperand(1) != ConstantOp) {
10605       return 0;
10606     }
10607   }
10608
10609   // Okay, they are all the same operation.  Create a new PHI node of the
10610   // correct type, and PHI together all of the LHS's of the instructions.
10611   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10612                                    PN.getName()+".in");
10613   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10614
10615   Value *InVal = FirstInst->getOperand(0);
10616   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10617
10618   // Add all operands to the new PHI.
10619   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10620     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10621     if (NewInVal != InVal)
10622       InVal = 0;
10623     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10624   }
10625
10626   Value *PhiVal;
10627   if (InVal) {
10628     // The new PHI unions all of the same values together.  This is really
10629     // common, so we handle it intelligently here for compile-time speed.
10630     PhiVal = InVal;
10631     delete NewPN;
10632   } else {
10633     InsertNewInstBefore(NewPN, PN);
10634     PhiVal = NewPN;
10635   }
10636
10637   // Insert and return the new operation.
10638   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10639     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10640   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10641     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10642   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10643     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10644                            PhiVal, ConstantOp);
10645   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10646   
10647   // If this was a volatile load that we are merging, make sure to loop through
10648   // and mark all the input loads as non-volatile.  If we don't do this, we will
10649   // insert a new volatile load and the old ones will not be deletable.
10650   if (isVolatile)
10651     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10652       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10653   
10654   return new LoadInst(PhiVal, "", isVolatile);
10655 }
10656
10657 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10658 /// that is dead.
10659 static bool DeadPHICycle(PHINode *PN,
10660                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10661   if (PN->use_empty()) return true;
10662   if (!PN->hasOneUse()) return false;
10663
10664   // Remember this node, and if we find the cycle, return.
10665   if (!PotentiallyDeadPHIs.insert(PN))
10666     return true;
10667   
10668   // Don't scan crazily complex things.
10669   if (PotentiallyDeadPHIs.size() == 16)
10670     return false;
10671
10672   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10673     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10674
10675   return false;
10676 }
10677
10678 /// PHIsEqualValue - Return true if this phi node is always equal to
10679 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10680 ///   z = some value; x = phi (y, z); y = phi (x, z)
10681 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10682                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10683   // See if we already saw this PHI node.
10684   if (!ValueEqualPHIs.insert(PN))
10685     return true;
10686   
10687   // Don't scan crazily complex things.
10688   if (ValueEqualPHIs.size() == 16)
10689     return false;
10690  
10691   // Scan the operands to see if they are either phi nodes or are equal to
10692   // the value.
10693   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10694     Value *Op = PN->getIncomingValue(i);
10695     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10696       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10697         return false;
10698     } else if (Op != NonPhiInVal)
10699       return false;
10700   }
10701   
10702   return true;
10703 }
10704
10705
10706 // PHINode simplification
10707 //
10708 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10709   // If LCSSA is around, don't mess with Phi nodes
10710   if (MustPreserveLCSSA) return 0;
10711   
10712   if (Value *V = PN.hasConstantValue())
10713     return ReplaceInstUsesWith(PN, V);
10714
10715   // If all PHI operands are the same operation, pull them through the PHI,
10716   // reducing code size.
10717   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10718       isa<Instruction>(PN.getIncomingValue(1)) &&
10719       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10720       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10721       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10722       // than themselves more than once.
10723       PN.getIncomingValue(0)->hasOneUse())
10724     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10725       return Result;
10726
10727   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10728   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10729   // PHI)... break the cycle.
10730   if (PN.hasOneUse()) {
10731     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10732     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10733       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10734       PotentiallyDeadPHIs.insert(&PN);
10735       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10736         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10737     }
10738    
10739     // If this phi has a single use, and if that use just computes a value for
10740     // the next iteration of a loop, delete the phi.  This occurs with unused
10741     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10742     // common case here is good because the only other things that catch this
10743     // are induction variable analysis (sometimes) and ADCE, which is only run
10744     // late.
10745     if (PHIUser->hasOneUse() &&
10746         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10747         PHIUser->use_back() == &PN) {
10748       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10749     }
10750   }
10751
10752   // We sometimes end up with phi cycles that non-obviously end up being the
10753   // same value, for example:
10754   //   z = some value; x = phi (y, z); y = phi (x, z)
10755   // where the phi nodes don't necessarily need to be in the same block.  Do a
10756   // quick check to see if the PHI node only contains a single non-phi value, if
10757   // so, scan to see if the phi cycle is actually equal to that value.
10758   {
10759     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10760     // Scan for the first non-phi operand.
10761     while (InValNo != NumOperandVals && 
10762            isa<PHINode>(PN.getIncomingValue(InValNo)))
10763       ++InValNo;
10764
10765     if (InValNo != NumOperandVals) {
10766       Value *NonPhiInVal = PN.getOperand(InValNo);
10767       
10768       // Scan the rest of the operands to see if there are any conflicts, if so
10769       // there is no need to recursively scan other phis.
10770       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10771         Value *OpVal = PN.getIncomingValue(InValNo);
10772         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10773           break;
10774       }
10775       
10776       // If we scanned over all operands, then we have one unique value plus
10777       // phi values.  Scan PHI nodes to see if they all merge in each other or
10778       // the value.
10779       if (InValNo == NumOperandVals) {
10780         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10781         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10782           return ReplaceInstUsesWith(PN, NonPhiInVal);
10783       }
10784     }
10785   }
10786   return 0;
10787 }
10788
10789 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10790   Value *PtrOp = GEP.getOperand(0);
10791   // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
10792   if (GEP.getNumOperands() == 1)
10793     return ReplaceInstUsesWith(GEP, PtrOp);
10794
10795   if (isa<UndefValue>(GEP.getOperand(0)))
10796     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10797
10798   bool HasZeroPointerIndex = false;
10799   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10800     HasZeroPointerIndex = C->isNullValue();
10801
10802   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10803     return ReplaceInstUsesWith(GEP, PtrOp);
10804
10805   // Eliminate unneeded casts for indices.
10806   if (TD) {
10807     bool MadeChange = false;
10808     unsigned PtrSize = TD->getPointerSizeInBits();
10809     
10810     gep_type_iterator GTI = gep_type_begin(GEP);
10811     for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10812          I != E; ++I, ++GTI) {
10813       if (!isa<SequentialType>(*GTI)) continue;
10814       
10815       // If we are using a wider index than needed for this platform, shrink it
10816       // to what we need.  If narrower, sign-extend it to what we need.  This
10817       // explicit cast can make subsequent optimizations more obvious.
10818       unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
10819       if (OpBits == PtrSize)
10820         continue;
10821       
10822       *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
10823       MadeChange = true;
10824     }
10825     if (MadeChange) return &GEP;
10826   }
10827
10828   // Combine Indices - If the source pointer to this getelementptr instruction
10829   // is a getelementptr instruction, combine the indices of the two
10830   // getelementptr instructions into a single instruction.
10831   //
10832   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
10833     // Note that if our source is a gep chain itself that we wait for that
10834     // chain to be resolved before we perform this transformation.  This
10835     // avoids us creating a TON of code in some cases.
10836     //
10837     if (GetElementPtrInst *SrcGEP =
10838           dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10839       if (SrcGEP->getNumOperands() == 2)
10840         return 0;   // Wait until our source is folded to completion.
10841
10842     SmallVector<Value*, 8> Indices;
10843
10844     // Find out whether the last index in the source GEP is a sequential idx.
10845     bool EndsWithSequential = false;
10846     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
10847          I != E; ++I)
10848       EndsWithSequential = !isa<StructType>(*I);
10849
10850     // Can we combine the two pointer arithmetics offsets?
10851     if (EndsWithSequential) {
10852       // Replace: gep (gep %P, long B), long A, ...
10853       // With:    T = long A+B; gep %P, T, ...
10854       //
10855       Value *Sum;
10856       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
10857       Value *GO1 = GEP.getOperand(1);
10858       if (SO1 == Constant::getNullValue(SO1->getType())) {
10859         Sum = GO1;
10860       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10861         Sum = SO1;
10862       } else {
10863         // If they aren't the same type, then the input hasn't been processed
10864         // by the loop above yet (which canonicalizes sequential index types to
10865         // intptr_t).  Just avoid transforming this until the input has been
10866         // normalized.
10867         if (SO1->getType() != GO1->getType())
10868           return 0;
10869         Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10870       }
10871
10872       // Update the GEP in place if possible.
10873       if (Src->getNumOperands() == 2) {
10874         GEP.setOperand(0, Src->getOperand(0));
10875         GEP.setOperand(1, Sum);
10876         return &GEP;
10877       }
10878       Indices.append(Src->op_begin()+1, Src->op_end()-1);
10879       Indices.push_back(Sum);
10880       Indices.append(GEP.op_begin()+2, GEP.op_end());
10881     } else if (isa<Constant>(*GEP.idx_begin()) &&
10882                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10883                Src->getNumOperands() != 1) {
10884       // Otherwise we can do the fold if the first index of the GEP is a zero
10885       Indices.append(Src->op_begin()+1, Src->op_end());
10886       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
10887     }
10888
10889     if (!Indices.empty()) {
10890       GetElementPtrInst *NewGEP =
10891         GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
10892                                   Indices.end(), GEP.getName());
10893       if (cast<GEPOperator>(&GEP)->isInBounds() && Src->isInBounds())
10894         cast<GEPOperator>(NewGEP)->setIsInBounds(true);
10895       return NewGEP;
10896     }
10897   }
10898   
10899   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
10900   if (Value *X = getBitCastOperand(PtrOp)) {
10901     assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
10902
10903     // If the input bitcast is actually "bitcast(bitcast(x))", then we don't 
10904     // want to change the gep until the bitcasts are eliminated.
10905     if (getBitCastOperand(X)) {
10906       Worklist.AddValue(PtrOp);
10907       return 0;
10908     }
10909     
10910     // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10911     // into     : GEP [10 x i8]* X, i32 0, ...
10912     //
10913     // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
10914     //           into     : GEP i8* X, ...
10915     // 
10916     // This occurs when the program declares an array extern like "int X[];"
10917     if (HasZeroPointerIndex) {
10918       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10919       const PointerType *XTy = cast<PointerType>(X->getType());
10920       if (const ArrayType *CATy =
10921           dyn_cast<ArrayType>(CPTy->getElementType())) {
10922         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
10923         if (CATy->getElementType() == XTy->getElementType()) {
10924           // -> GEP i8* X, ...
10925           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
10926           GetElementPtrInst *NewGEP =
10927             GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
10928                                       GEP.getName());
10929           if (cast<GEPOperator>(&GEP)->isInBounds())
10930             cast<GEPOperator>(NewGEP)->setIsInBounds(true);
10931           return NewGEP;
10932         }
10933         
10934         if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
10935           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
10936           if (CATy->getElementType() == XATy->getElementType()) {
10937             // -> GEP [10 x i8]* X, i32 0, ...
10938             // At this point, we know that the cast source type is a pointer
10939             // to an array of the same type as the destination pointer
10940             // array.  Because the array type is never stepped over (there
10941             // is a leading zero) we can fold the cast into this GEP.
10942             GEP.setOperand(0, X);
10943             return &GEP;
10944           }
10945         }
10946       }
10947     } else if (GEP.getNumOperands() == 2) {
10948       // Transform things like:
10949       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10950       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
10951       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10952       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10953       if (TD && isa<ArrayType>(SrcElTy) &&
10954           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10955           TD->getTypeAllocSize(ResElTy)) {
10956         Value *Idx[2];
10957         Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
10958         Idx[1] = GEP.getOperand(1);
10959         Value *NewGEP =
10960           Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
10961         if (cast<GEPOperator>(&GEP)->isInBounds())
10962           cast<GEPOperator>(NewGEP)->setIsInBounds(true);
10963         // V and GEP are both pointer types --> BitCast
10964         return new BitCastInst(NewGEP, GEP.getType());
10965       }
10966       
10967       // Transform things like:
10968       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
10969       //   (where tmp = 8*tmp2) into:
10970       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
10971       
10972       if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
10973         uint64_t ArrayEltSize =
10974             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
10975         
10976         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
10977         // allow either a mul, shift, or constant here.
10978         Value *NewIdx = 0;
10979         ConstantInt *Scale = 0;
10980         if (ArrayEltSize == 1) {
10981           NewIdx = GEP.getOperand(1);
10982           Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
10983         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10984           NewIdx = ConstantInt::get(CI->getType(), 1);
10985           Scale = CI;
10986         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10987           if (Inst->getOpcode() == Instruction::Shl &&
10988               isa<ConstantInt>(Inst->getOperand(1))) {
10989             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10990             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10991             Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
10992                                      1ULL << ShAmtVal);
10993             NewIdx = Inst->getOperand(0);
10994           } else if (Inst->getOpcode() == Instruction::Mul &&
10995                      isa<ConstantInt>(Inst->getOperand(1))) {
10996             Scale = cast<ConstantInt>(Inst->getOperand(1));
10997             NewIdx = Inst->getOperand(0);
10998           }
10999         }
11000         
11001         // If the index will be to exactly the right offset with the scale taken
11002         // out, perform the transformation. Note, we don't know whether Scale is
11003         // signed or not. We'll use unsigned version of division/modulo
11004         // operation after making sure Scale doesn't have the sign bit set.
11005         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11006             Scale->getZExtValue() % ArrayEltSize == 0) {
11007           Scale = ConstantInt::get(Scale->getType(),
11008                                    Scale->getZExtValue() / ArrayEltSize);
11009           if (Scale->getZExtValue() != 1) {
11010             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11011                                                        false /*ZExt*/);
11012             NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
11013           }
11014
11015           // Insert the new GEP instruction.
11016           Value *Idx[2];
11017           Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11018           Idx[1] = NewIdx;
11019           Value *NewGEP = Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11020           if (cast<GEPOperator>(&GEP)->isInBounds())
11021             cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11022           // The NewGEP must be pointer typed, so must the old one -> BitCast
11023           return new BitCastInst(NewGEP, GEP.getType());
11024         }
11025       }
11026     }
11027   }
11028   
11029   /// See if we can simplify:
11030   ///   X = bitcast A* to B*
11031   ///   Y = gep X, <...constant indices...>
11032   /// into a gep of the original struct.  This is important for SROA and alias
11033   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11034   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11035     if (TD &&
11036         !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11037       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11038       // a constant back from EmitGEPOffset.
11039       ConstantInt *OffsetV =
11040                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11041       int64_t Offset = OffsetV->getSExtValue();
11042       
11043       // If this GEP instruction doesn't move the pointer, just replace the GEP
11044       // with a bitcast of the real input to the dest type.
11045       if (Offset == 0) {
11046         // If the bitcast is of an allocation, and the allocation will be
11047         // converted to match the type of the cast, don't touch this.
11048         if (isa<AllocationInst>(BCI->getOperand(0))) {
11049           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11050           if (Instruction *I = visitBitCast(*BCI)) {
11051             if (I != BCI) {
11052               I->takeName(BCI);
11053               BCI->getParent()->getInstList().insert(BCI, I);
11054               ReplaceInstUsesWith(*BCI, I);
11055             }
11056             return &GEP;
11057           }
11058         }
11059         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11060       }
11061       
11062       // Otherwise, if the offset is non-zero, we need to find out if there is a
11063       // field at Offset in 'A's type.  If so, we can pull the cast through the
11064       // GEP.
11065       SmallVector<Value*, 8> NewIndices;
11066       const Type *InTy =
11067         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11068       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11069         Value *NGEP = Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11070                                          NewIndices.end());
11071         if (cast<GEPOperator>(&GEP)->isInBounds())
11072           cast<GEPOperator>(NGEP)->setIsInBounds(true);
11073         
11074         if (NGEP->getType() == GEP.getType())
11075           return ReplaceInstUsesWith(GEP, NGEP);
11076         NGEP->takeName(&GEP);
11077         return new BitCastInst(NGEP, GEP.getType());
11078       }
11079     }
11080   }    
11081     
11082   return 0;
11083 }
11084
11085 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11086   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11087   if (AI.isArrayAllocation()) {  // Check C != 1
11088     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11089       const Type *NewTy = 
11090         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11091       AllocationInst *New = 0;
11092
11093       // Create and insert the replacement instruction...
11094       if (isa<MallocInst>(AI))
11095         New = Builder->CreateMalloc(NewTy, 0, AI.getName());
11096       else {
11097         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11098         New = Builder->CreateAlloca(NewTy, 0, AI.getName());
11099       }
11100       New->setAlignment(AI.getAlignment());
11101
11102       // Scan to the end of the allocation instructions, to skip over a block of
11103       // allocas if possible...also skip interleaved debug info
11104       //
11105       BasicBlock::iterator It = New;
11106       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11107
11108       // Now that I is pointing to the first non-allocation-inst in the block,
11109       // insert our getelementptr instruction...
11110       //
11111       Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
11112       Value *Idx[2];
11113       Idx[0] = NullIdx;
11114       Idx[1] = NullIdx;
11115       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11116                                            New->getName()+".sub", It);
11117       cast<GEPOperator>(V)->setIsInBounds(true);
11118
11119       // Now make everything use the getelementptr instead of the original
11120       // allocation.
11121       return ReplaceInstUsesWith(AI, V);
11122     } else if (isa<UndefValue>(AI.getArraySize())) {
11123       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11124     }
11125   }
11126
11127   if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11128     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11129     // Note that we only do this for alloca's, because malloc should allocate
11130     // and return a unique pointer, even for a zero byte allocation.
11131     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11132       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11133
11134     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11135     if (AI.getAlignment() == 0)
11136       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11137   }
11138
11139   return 0;
11140 }
11141
11142 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11143   Value *Op = FI.getOperand(0);
11144
11145   // free undef -> unreachable.
11146   if (isa<UndefValue>(Op)) {
11147     // Insert a new store to null because we cannot modify the CFG here.
11148     new StoreInst(ConstantInt::getTrue(*Context),
11149            UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), &FI);
11150     return EraseInstFromFunction(FI);
11151   }
11152   
11153   // If we have 'free null' delete the instruction.  This can happen in stl code
11154   // when lots of inlining happens.
11155   if (isa<ConstantPointerNull>(Op))
11156     return EraseInstFromFunction(FI);
11157   
11158   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11159   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11160     FI.setOperand(0, CI->getOperand(0));
11161     return &FI;
11162   }
11163   
11164   // Change free (gep X, 0,0,0,0) into free(X)
11165   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11166     if (GEPI->hasAllZeroIndices()) {
11167       Worklist.Add(GEPI);
11168       FI.setOperand(0, GEPI->getOperand(0));
11169       return &FI;
11170     }
11171   }
11172   
11173   // Change free(malloc) into nothing, if the malloc has a single use.
11174   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11175     if (MI->hasOneUse()) {
11176       EraseInstFromFunction(FI);
11177       return EraseInstFromFunction(*MI);
11178     }
11179
11180   return 0;
11181 }
11182
11183
11184 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11185 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11186                                         const TargetData *TD) {
11187   User *CI = cast<User>(LI.getOperand(0));
11188   Value *CastOp = CI->getOperand(0);
11189   LLVMContext *Context = IC.getContext();
11190
11191   if (TD) {
11192     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11193       // Instead of loading constant c string, use corresponding integer value
11194       // directly if string length is small enough.
11195       std::string Str;
11196       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11197         unsigned len = Str.length();
11198         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11199         unsigned numBits = Ty->getPrimitiveSizeInBits();
11200         // Replace LI with immediate integer store.
11201         if ((numBits >> 3) == len + 1) {
11202           APInt StrVal(numBits, 0);
11203           APInt SingleChar(numBits, 0);
11204           if (TD->isLittleEndian()) {
11205             for (signed i = len-1; i >= 0; i--) {
11206               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11207               StrVal = (StrVal << 8) | SingleChar;
11208             }
11209           } else {
11210             for (unsigned i = 0; i < len; i++) {
11211               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11212               StrVal = (StrVal << 8) | SingleChar;
11213             }
11214             // Append NULL at the end.
11215             SingleChar = 0;
11216             StrVal = (StrVal << 8) | SingleChar;
11217           }
11218           Value *NL = ConstantInt::get(*Context, StrVal);
11219           return IC.ReplaceInstUsesWith(LI, NL);
11220         }
11221       }
11222     }
11223   }
11224
11225   const PointerType *DestTy = cast<PointerType>(CI->getType());
11226   const Type *DestPTy = DestTy->getElementType();
11227   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11228
11229     // If the address spaces don't match, don't eliminate the cast.
11230     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11231       return 0;
11232
11233     const Type *SrcPTy = SrcTy->getElementType();
11234
11235     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11236          isa<VectorType>(DestPTy)) {
11237       // If the source is an array, the code below will not succeed.  Check to
11238       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11239       // constants.
11240       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11241         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11242           if (ASrcTy->getNumElements() != 0) {
11243             Value *Idxs[2];
11244             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
11245             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11246             SrcTy = cast<PointerType>(CastOp->getType());
11247             SrcPTy = SrcTy->getElementType();
11248           }
11249
11250       if (IC.getTargetData() &&
11251           (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11252             isa<VectorType>(SrcPTy)) &&
11253           // Do not allow turning this into a load of an integer, which is then
11254           // casted to a pointer, this pessimizes pointer analysis a lot.
11255           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11256           IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11257                IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11258
11259         // Okay, we are casting from one integer or pointer type to another of
11260         // the same size.  Instead of casting the pointer before the load, cast
11261         // the result of the loaded value.
11262         Value *NewLoad = 
11263           IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
11264         // Now cast the result of the load.
11265         return new BitCastInst(NewLoad, LI.getType());
11266       }
11267     }
11268   }
11269   return 0;
11270 }
11271
11272 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11273   Value *Op = LI.getOperand(0);
11274
11275   // Attempt to improve the alignment.
11276   if (TD) {
11277     unsigned KnownAlign =
11278       GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11279     if (KnownAlign >
11280         (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11281                                   LI.getAlignment()))
11282       LI.setAlignment(KnownAlign);
11283   }
11284
11285   // load (cast X) --> cast (load X) iff safe.
11286   if (isa<CastInst>(Op))
11287     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11288       return Res;
11289
11290   // None of the following transforms are legal for volatile loads.
11291   if (LI.isVolatile()) return 0;
11292   
11293   // Do really simple store-to-load forwarding and load CSE, to catch cases
11294   // where there are several consequtive memory accesses to the same location,
11295   // separated by a few arithmetic operations.
11296   BasicBlock::iterator BBI = &LI;
11297   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11298     return ReplaceInstUsesWith(LI, AvailableVal);
11299
11300   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11301     const Value *GEPI0 = GEPI->getOperand(0);
11302     // TODO: Consider a target hook for valid address spaces for this xform.
11303     if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
11304       // Insert a new store to null instruction before the load to indicate
11305       // that this code is not reachable.  We do this instead of inserting
11306       // an unreachable instruction directly because we cannot modify the
11307       // CFG.
11308       new StoreInst(UndefValue::get(LI.getType()),
11309                     Constant::getNullValue(Op->getType()), &LI);
11310       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11311     }
11312   } 
11313
11314   if (Constant *C = dyn_cast<Constant>(Op)) {
11315     // load null/undef -> undef
11316     // TODO: Consider a target hook for valid address spaces for this xform.
11317     if (isa<UndefValue>(C) ||
11318         (C->isNullValue() && LI.getPointerAddressSpace() == 0)) {
11319       // Insert a new store to null instruction before the load to indicate that
11320       // this code is not reachable.  We do this instead of inserting an
11321       // unreachable instruction directly because we cannot modify the CFG.
11322       new StoreInst(UndefValue::get(LI.getType()),
11323                     Constant::getNullValue(Op->getType()), &LI);
11324       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11325     }
11326
11327     // Instcombine load (constant global) into the value loaded.
11328     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11329       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11330         return ReplaceInstUsesWith(LI, GV->getInitializer());
11331
11332     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11333     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11334       if (CE->getOpcode() == Instruction::GetElementPtr) {
11335         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11336           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11337             if (Constant *V = 
11338                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE, 
11339                                                       *Context))
11340               return ReplaceInstUsesWith(LI, V);
11341         if (CE->getOperand(0)->isNullValue()) {
11342           // Insert a new store to null instruction before the load to indicate
11343           // that this code is not reachable.  We do this instead of inserting
11344           // an unreachable instruction directly because we cannot modify the
11345           // CFG.
11346           new StoreInst(UndefValue::get(LI.getType()),
11347                         Constant::getNullValue(Op->getType()), &LI);
11348           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11349         }
11350
11351       } else if (CE->isCast()) {
11352         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11353           return Res;
11354       }
11355     }
11356   }
11357     
11358   // If this load comes from anywhere in a constant global, and if the global
11359   // is all undef or zero, we know what it loads.
11360   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11361     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11362       if (GV->getInitializer()->isNullValue())
11363         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11364       else if (isa<UndefValue>(GV->getInitializer()))
11365         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11366     }
11367   }
11368
11369   if (Op->hasOneUse()) {
11370     // Change select and PHI nodes to select values instead of addresses: this
11371     // helps alias analysis out a lot, allows many others simplifications, and
11372     // exposes redundancy in the code.
11373     //
11374     // Note that we cannot do the transformation unless we know that the
11375     // introduced loads cannot trap!  Something like this is valid as long as
11376     // the condition is always false: load (select bool %C, int* null, int* %G),
11377     // but it would not be valid if we transformed it to load from null
11378     // unconditionally.
11379     //
11380     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11381       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11382       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11383           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11384         Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11385                                         SI->getOperand(1)->getName()+".val");
11386         Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11387                                         SI->getOperand(2)->getName()+".val");
11388         return SelectInst::Create(SI->getCondition(), V1, V2);
11389       }
11390
11391       // load (select (cond, null, P)) -> load P
11392       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11393         if (C->isNullValue()) {
11394           LI.setOperand(0, SI->getOperand(2));
11395           return &LI;
11396         }
11397
11398       // load (select (cond, P, null)) -> load P
11399       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11400         if (C->isNullValue()) {
11401           LI.setOperand(0, SI->getOperand(1));
11402           return &LI;
11403         }
11404     }
11405   }
11406   return 0;
11407 }
11408
11409 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11410 /// when possible.  This makes it generally easy to do alias analysis and/or
11411 /// SROA/mem2reg of the memory object.
11412 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11413   User *CI = cast<User>(SI.getOperand(1));
11414   Value *CastOp = CI->getOperand(0);
11415
11416   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11417   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11418   if (SrcTy == 0) return 0;
11419   
11420   const Type *SrcPTy = SrcTy->getElementType();
11421
11422   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11423     return 0;
11424   
11425   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11426   /// to its first element.  This allows us to handle things like:
11427   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11428   /// on 32-bit hosts.
11429   SmallVector<Value*, 4> NewGEPIndices;
11430   
11431   // If the source is an array, the code below will not succeed.  Check to
11432   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11433   // constants.
11434   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11435     // Index through pointer.
11436     Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
11437     NewGEPIndices.push_back(Zero);
11438     
11439     while (1) {
11440       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11441         if (!STy->getNumElements()) /* Struct can be empty {} */
11442           break;
11443         NewGEPIndices.push_back(Zero);
11444         SrcPTy = STy->getElementType(0);
11445       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11446         NewGEPIndices.push_back(Zero);
11447         SrcPTy = ATy->getElementType();
11448       } else {
11449         break;
11450       }
11451     }
11452     
11453     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11454   }
11455
11456   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11457     return 0;
11458   
11459   // If the pointers point into different address spaces or if they point to
11460   // values with different sizes, we can't do the transformation.
11461   if (!IC.getTargetData() ||
11462       SrcTy->getAddressSpace() != 
11463         cast<PointerType>(CI->getType())->getAddressSpace() ||
11464       IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11465       IC.getTargetData()->getTypeSizeInBits(DestPTy))
11466     return 0;
11467
11468   // Okay, we are casting from one integer or pointer type to another of
11469   // the same size.  Instead of casting the pointer before 
11470   // the store, cast the value to be stored.
11471   Value *NewCast;
11472   Value *SIOp0 = SI.getOperand(0);
11473   Instruction::CastOps opcode = Instruction::BitCast;
11474   const Type* CastSrcTy = SIOp0->getType();
11475   const Type* CastDstTy = SrcPTy;
11476   if (isa<PointerType>(CastDstTy)) {
11477     if (CastSrcTy->isInteger())
11478       opcode = Instruction::IntToPtr;
11479   } else if (isa<IntegerType>(CastDstTy)) {
11480     if (isa<PointerType>(SIOp0->getType()))
11481       opcode = Instruction::PtrToInt;
11482   }
11483   
11484   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11485   // emit a GEP to index into its first field.
11486   if (!NewGEPIndices.empty()) {
11487     CastOp = IC.Builder->CreateGEP(CastOp, NewGEPIndices.begin(),
11488                                    NewGEPIndices.end());
11489     cast<GEPOperator>(CastOp)->setIsInBounds(true);
11490   }
11491   
11492   NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11493                                    SIOp0->getName()+".c");
11494   return new StoreInst(NewCast, CastOp);
11495 }
11496
11497 /// equivalentAddressValues - Test if A and B will obviously have the same
11498 /// value. This includes recognizing that %t0 and %t1 will have the same
11499 /// value in code like this:
11500 ///   %t0 = getelementptr \@a, 0, 3
11501 ///   store i32 0, i32* %t0
11502 ///   %t1 = getelementptr \@a, 0, 3
11503 ///   %t2 = load i32* %t1
11504 ///
11505 static bool equivalentAddressValues(Value *A, Value *B) {
11506   // Test if the values are trivially equivalent.
11507   if (A == B) return true;
11508   
11509   // Test if the values come form identical arithmetic instructions.
11510   // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11511   // its only used to compare two uses within the same basic block, which
11512   // means that they'll always either have the same value or one of them
11513   // will have an undefined value.
11514   if (isa<BinaryOperator>(A) ||
11515       isa<CastInst>(A) ||
11516       isa<PHINode>(A) ||
11517       isa<GetElementPtrInst>(A))
11518     if (Instruction *BI = dyn_cast<Instruction>(B))
11519       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
11520         return true;
11521   
11522   // Otherwise they may not be equivalent.
11523   return false;
11524 }
11525
11526 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11527 // return the llvm.dbg.declare.
11528 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11529   if (!V->hasNUses(2))
11530     return 0;
11531   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11532        UI != E; ++UI) {
11533     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11534       return DI;
11535     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11536       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11537         return DI;
11538       }
11539   }
11540   return 0;
11541 }
11542
11543 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11544   Value *Val = SI.getOperand(0);
11545   Value *Ptr = SI.getOperand(1);
11546
11547   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11548     EraseInstFromFunction(SI);
11549     ++NumCombined;
11550     return 0;
11551   }
11552   
11553   // If the RHS is an alloca with a single use, zapify the store, making the
11554   // alloca dead.
11555   // If the RHS is an alloca with a two uses, the other one being a 
11556   // llvm.dbg.declare, zapify the store and the declare, making the
11557   // alloca dead.  We must do this to prevent declare's from affecting
11558   // codegen.
11559   if (!SI.isVolatile()) {
11560     if (Ptr->hasOneUse()) {
11561       if (isa<AllocaInst>(Ptr)) {
11562         EraseInstFromFunction(SI);
11563         ++NumCombined;
11564         return 0;
11565       }
11566       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11567         if (isa<AllocaInst>(GEP->getOperand(0))) {
11568           if (GEP->getOperand(0)->hasOneUse()) {
11569             EraseInstFromFunction(SI);
11570             ++NumCombined;
11571             return 0;
11572           }
11573           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11574             EraseInstFromFunction(*DI);
11575             EraseInstFromFunction(SI);
11576             ++NumCombined;
11577             return 0;
11578           }
11579         }
11580       }
11581     }
11582     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11583       EraseInstFromFunction(*DI);
11584       EraseInstFromFunction(SI);
11585       ++NumCombined;
11586       return 0;
11587     }
11588   }
11589
11590   // Attempt to improve the alignment.
11591   if (TD) {
11592     unsigned KnownAlign =
11593       GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11594     if (KnownAlign >
11595         (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11596                                   SI.getAlignment()))
11597       SI.setAlignment(KnownAlign);
11598   }
11599
11600   // Do really simple DSE, to catch cases where there are several consecutive
11601   // stores to the same location, separated by a few arithmetic operations. This
11602   // situation often occurs with bitfield accesses.
11603   BasicBlock::iterator BBI = &SI;
11604   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11605        --ScanInsts) {
11606     --BBI;
11607     // Don't count debug info directives, lest they affect codegen,
11608     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11609     // It is necessary for correctness to skip those that feed into a
11610     // llvm.dbg.declare, as these are not present when debugging is off.
11611     if (isa<DbgInfoIntrinsic>(BBI) ||
11612         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11613       ScanInsts++;
11614       continue;
11615     }    
11616     
11617     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11618       // Prev store isn't volatile, and stores to the same location?
11619       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11620                                                           SI.getOperand(1))) {
11621         ++NumDeadStore;
11622         ++BBI;
11623         EraseInstFromFunction(*PrevSI);
11624         continue;
11625       }
11626       break;
11627     }
11628     
11629     // If this is a load, we have to stop.  However, if the loaded value is from
11630     // the pointer we're loading and is producing the pointer we're storing,
11631     // then *this* store is dead (X = load P; store X -> P).
11632     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11633       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11634           !SI.isVolatile()) {
11635         EraseInstFromFunction(SI);
11636         ++NumCombined;
11637         return 0;
11638       }
11639       // Otherwise, this is a load from some other location.  Stores before it
11640       // may not be dead.
11641       break;
11642     }
11643     
11644     // Don't skip over loads or things that can modify memory.
11645     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11646       break;
11647   }
11648   
11649   
11650   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11651
11652   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11653   if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
11654     if (!isa<UndefValue>(Val)) {
11655       SI.setOperand(0, UndefValue::get(Val->getType()));
11656       if (Instruction *U = dyn_cast<Instruction>(Val))
11657         Worklist.Add(U);  // Dropped a use.
11658       ++NumCombined;
11659     }
11660     return 0;  // Do not modify these!
11661   }
11662
11663   // store undef, Ptr -> noop
11664   if (isa<UndefValue>(Val)) {
11665     EraseInstFromFunction(SI);
11666     ++NumCombined;
11667     return 0;
11668   }
11669
11670   // If the pointer destination is a cast, see if we can fold the cast into the
11671   // source instead.
11672   if (isa<CastInst>(Ptr))
11673     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11674       return Res;
11675   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11676     if (CE->isCast())
11677       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11678         return Res;
11679
11680   
11681   // If this store is the last instruction in the basic block (possibly
11682   // excepting debug info instructions and the pointer bitcasts that feed
11683   // into them), and if the block ends with an unconditional branch, try
11684   // to move it to the successor block.
11685   BBI = &SI; 
11686   do {
11687     ++BBI;
11688   } while (isa<DbgInfoIntrinsic>(BBI) ||
11689            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11690   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11691     if (BI->isUnconditional())
11692       if (SimplifyStoreAtEndOfBlock(SI))
11693         return 0;  // xform done!
11694   
11695   return 0;
11696 }
11697
11698 /// SimplifyStoreAtEndOfBlock - Turn things like:
11699 ///   if () { *P = v1; } else { *P = v2 }
11700 /// into a phi node with a store in the successor.
11701 ///
11702 /// Simplify things like:
11703 ///   *P = v1; if () { *P = v2; }
11704 /// into a phi node with a store in the successor.
11705 ///
11706 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11707   BasicBlock *StoreBB = SI.getParent();
11708   
11709   // Check to see if the successor block has exactly two incoming edges.  If
11710   // so, see if the other predecessor contains a store to the same location.
11711   // if so, insert a PHI node (if needed) and move the stores down.
11712   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11713   
11714   // Determine whether Dest has exactly two predecessors and, if so, compute
11715   // the other predecessor.
11716   pred_iterator PI = pred_begin(DestBB);
11717   BasicBlock *OtherBB = 0;
11718   if (*PI != StoreBB)
11719     OtherBB = *PI;
11720   ++PI;
11721   if (PI == pred_end(DestBB))
11722     return false;
11723   
11724   if (*PI != StoreBB) {
11725     if (OtherBB)
11726       return false;
11727     OtherBB = *PI;
11728   }
11729   if (++PI != pred_end(DestBB))
11730     return false;
11731
11732   // Bail out if all the relevant blocks aren't distinct (this can happen,
11733   // for example, if SI is in an infinite loop)
11734   if (StoreBB == DestBB || OtherBB == DestBB)
11735     return false;
11736
11737   // Verify that the other block ends in a branch and is not otherwise empty.
11738   BasicBlock::iterator BBI = OtherBB->getTerminator();
11739   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11740   if (!OtherBr || BBI == OtherBB->begin())
11741     return false;
11742   
11743   // If the other block ends in an unconditional branch, check for the 'if then
11744   // else' case.  there is an instruction before the branch.
11745   StoreInst *OtherStore = 0;
11746   if (OtherBr->isUnconditional()) {
11747     --BBI;
11748     // Skip over debugging info.
11749     while (isa<DbgInfoIntrinsic>(BBI) ||
11750            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11751       if (BBI==OtherBB->begin())
11752         return false;
11753       --BBI;
11754     }
11755     // If this isn't a store, or isn't a store to the same location, bail out.
11756     OtherStore = dyn_cast<StoreInst>(BBI);
11757     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11758       return false;
11759   } else {
11760     // Otherwise, the other block ended with a conditional branch. If one of the
11761     // destinations is StoreBB, then we have the if/then case.
11762     if (OtherBr->getSuccessor(0) != StoreBB && 
11763         OtherBr->getSuccessor(1) != StoreBB)
11764       return false;
11765     
11766     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11767     // if/then triangle.  See if there is a store to the same ptr as SI that
11768     // lives in OtherBB.
11769     for (;; --BBI) {
11770       // Check to see if we find the matching store.
11771       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11772         if (OtherStore->getOperand(1) != SI.getOperand(1))
11773           return false;
11774         break;
11775       }
11776       // If we find something that may be using or overwriting the stored
11777       // value, or if we run out of instructions, we can't do the xform.
11778       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11779           BBI == OtherBB->begin())
11780         return false;
11781     }
11782     
11783     // In order to eliminate the store in OtherBr, we have to
11784     // make sure nothing reads or overwrites the stored value in
11785     // StoreBB.
11786     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11787       // FIXME: This should really be AA driven.
11788       if (I->mayReadFromMemory() || I->mayWriteToMemory())
11789         return false;
11790     }
11791   }
11792   
11793   // Insert a PHI node now if we need it.
11794   Value *MergedVal = OtherStore->getOperand(0);
11795   if (MergedVal != SI.getOperand(0)) {
11796     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11797     PN->reserveOperandSpace(2);
11798     PN->addIncoming(SI.getOperand(0), SI.getParent());
11799     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11800     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11801   }
11802   
11803   // Advance to a place where it is safe to insert the new store and
11804   // insert it.
11805   BBI = DestBB->getFirstNonPHI();
11806   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11807                                     OtherStore->isVolatile()), *BBI);
11808   
11809   // Nuke the old stores.
11810   EraseInstFromFunction(SI);
11811   EraseInstFromFunction(*OtherStore);
11812   ++NumCombined;
11813   return true;
11814 }
11815
11816
11817 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11818   // Change br (not X), label True, label False to: br X, label False, True
11819   Value *X = 0;
11820   BasicBlock *TrueDest;
11821   BasicBlock *FalseDest;
11822   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11823       !isa<Constant>(X)) {
11824     // Swap Destinations and condition...
11825     BI.setCondition(X);
11826     BI.setSuccessor(0, FalseDest);
11827     BI.setSuccessor(1, TrueDest);
11828     return &BI;
11829   }
11830
11831   // Cannonicalize fcmp_one -> fcmp_oeq
11832   FCmpInst::Predicate FPred; Value *Y;
11833   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
11834                              TrueDest, FalseDest)) &&
11835       BI.getCondition()->hasOneUse())
11836     if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11837         FPred == FCmpInst::FCMP_OGE) {
11838       FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11839       Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11840       
11841       // Swap Destinations and condition.
11842       BI.setSuccessor(0, FalseDest);
11843       BI.setSuccessor(1, TrueDest);
11844       Worklist.Add(Cond);
11845       return &BI;
11846     }
11847
11848   // Cannonicalize icmp_ne -> icmp_eq
11849   ICmpInst::Predicate IPred;
11850   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11851                       TrueDest, FalseDest)) &&
11852       BI.getCondition()->hasOneUse())
11853     if (IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
11854         IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11855         IPred == ICmpInst::ICMP_SGE) {
11856       ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11857       Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11858       // Swap Destinations and condition.
11859       BI.setSuccessor(0, FalseDest);
11860       BI.setSuccessor(1, TrueDest);
11861       Worklist.Add(Cond);
11862       return &BI;
11863     }
11864
11865   return 0;
11866 }
11867
11868 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11869   Value *Cond = SI.getCondition();
11870   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11871     if (I->getOpcode() == Instruction::Add)
11872       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11873         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11874         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11875           SI.setOperand(i,
11876                    ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11877                                                 AddRHS));
11878         SI.setOperand(0, I->getOperand(0));
11879         Worklist.Add(I);
11880         return &SI;
11881       }
11882   }
11883   return 0;
11884 }
11885
11886 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
11887   Value *Agg = EV.getAggregateOperand();
11888
11889   if (!EV.hasIndices())
11890     return ReplaceInstUsesWith(EV, Agg);
11891
11892   if (Constant *C = dyn_cast<Constant>(Agg)) {
11893     if (isa<UndefValue>(C))
11894       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11895       
11896     if (isa<ConstantAggregateZero>(C))
11897       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11898
11899     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11900       // Extract the element indexed by the first index out of the constant
11901       Value *V = C->getOperand(*EV.idx_begin());
11902       if (EV.getNumIndices() > 1)
11903         // Extract the remaining indices out of the constant indexed by the
11904         // first index
11905         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11906       else
11907         return ReplaceInstUsesWith(EV, V);
11908     }
11909     return 0; // Can't handle other constants
11910   } 
11911   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11912     // We're extracting from an insertvalue instruction, compare the indices
11913     const unsigned *exti, *exte, *insi, *inse;
11914     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11915          exte = EV.idx_end(), inse = IV->idx_end();
11916          exti != exte && insi != inse;
11917          ++exti, ++insi) {
11918       if (*insi != *exti)
11919         // The insert and extract both reference distinctly different elements.
11920         // This means the extract is not influenced by the insert, and we can
11921         // replace the aggregate operand of the extract with the aggregate
11922         // operand of the insert. i.e., replace
11923         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11924         // %E = extractvalue { i32, { i32 } } %I, 0
11925         // with
11926         // %E = extractvalue { i32, { i32 } } %A, 0
11927         return ExtractValueInst::Create(IV->getAggregateOperand(),
11928                                         EV.idx_begin(), EV.idx_end());
11929     }
11930     if (exti == exte && insi == inse)
11931       // Both iterators are at the end: Index lists are identical. Replace
11932       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11933       // %C = extractvalue { i32, { i32 } } %B, 1, 0
11934       // with "i32 42"
11935       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11936     if (exti == exte) {
11937       // The extract list is a prefix of the insert list. i.e. replace
11938       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11939       // %E = extractvalue { i32, { i32 } } %I, 1
11940       // with
11941       // %X = extractvalue { i32, { i32 } } %A, 1
11942       // %E = insertvalue { i32 } %X, i32 42, 0
11943       // by switching the order of the insert and extract (though the
11944       // insertvalue should be left in, since it may have other uses).
11945       Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
11946                                                  EV.idx_begin(), EV.idx_end());
11947       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11948                                      insi, inse);
11949     }
11950     if (insi == inse)
11951       // The insert list is a prefix of the extract list
11952       // We can simply remove the common indices from the extract and make it
11953       // operate on the inserted value instead of the insertvalue result.
11954       // i.e., replace
11955       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11956       // %E = extractvalue { i32, { i32 } } %I, 1, 0
11957       // with
11958       // %E extractvalue { i32 } { i32 42 }, 0
11959       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
11960                                       exti, exte);
11961   }
11962   // Can't simplify extracts from other values. Note that nested extracts are
11963   // already simplified implicitely by the above (extract ( extract (insert) )
11964   // will be translated into extract ( insert ( extract ) ) first and then just
11965   // the value inserted, if appropriate).
11966   return 0;
11967 }
11968
11969 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11970 /// is to leave as a vector operation.
11971 static bool CheapToScalarize(Value *V, bool isConstant) {
11972   if (isa<ConstantAggregateZero>(V)) 
11973     return true;
11974   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
11975     if (isConstant) return true;
11976     // If all elts are the same, we can extract.
11977     Constant *Op0 = C->getOperand(0);
11978     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11979       if (C->getOperand(i) != Op0)
11980         return false;
11981     return true;
11982   }
11983   Instruction *I = dyn_cast<Instruction>(V);
11984   if (!I) return false;
11985   
11986   // Insert element gets simplified to the inserted element or is deleted if
11987   // this is constant idx extract element and its a constant idx insertelt.
11988   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11989       isa<ConstantInt>(I->getOperand(2)))
11990     return true;
11991   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11992     return true;
11993   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11994     if (BO->hasOneUse() &&
11995         (CheapToScalarize(BO->getOperand(0), isConstant) ||
11996          CheapToScalarize(BO->getOperand(1), isConstant)))
11997       return true;
11998   if (CmpInst *CI = dyn_cast<CmpInst>(I))
11999     if (CI->hasOneUse() &&
12000         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12001          CheapToScalarize(CI->getOperand(1), isConstant)))
12002       return true;
12003   
12004   return false;
12005 }
12006
12007 /// Read and decode a shufflevector mask.
12008 ///
12009 /// It turns undef elements into values that are larger than the number of
12010 /// elements in the input.
12011 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12012   unsigned NElts = SVI->getType()->getNumElements();
12013   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12014     return std::vector<unsigned>(NElts, 0);
12015   if (isa<UndefValue>(SVI->getOperand(2)))
12016     return std::vector<unsigned>(NElts, 2*NElts);
12017
12018   std::vector<unsigned> Result;
12019   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12020   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12021     if (isa<UndefValue>(*i))
12022       Result.push_back(NElts*2);  // undef -> 8
12023     else
12024       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12025   return Result;
12026 }
12027
12028 /// FindScalarElement - Given a vector and an element number, see if the scalar
12029 /// value is already around as a register, for example if it were inserted then
12030 /// extracted from the vector.
12031 static Value *FindScalarElement(Value *V, unsigned EltNo,
12032                                 LLVMContext *Context) {
12033   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12034   const VectorType *PTy = cast<VectorType>(V->getType());
12035   unsigned Width = PTy->getNumElements();
12036   if (EltNo >= Width)  // Out of range access.
12037     return UndefValue::get(PTy->getElementType());
12038   
12039   if (isa<UndefValue>(V))
12040     return UndefValue::get(PTy->getElementType());
12041   else if (isa<ConstantAggregateZero>(V))
12042     return Constant::getNullValue(PTy->getElementType());
12043   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12044     return CP->getOperand(EltNo);
12045   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12046     // If this is an insert to a variable element, we don't know what it is.
12047     if (!isa<ConstantInt>(III->getOperand(2))) 
12048       return 0;
12049     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12050     
12051     // If this is an insert to the element we are looking for, return the
12052     // inserted value.
12053     if (EltNo == IIElt) 
12054       return III->getOperand(1);
12055     
12056     // Otherwise, the insertelement doesn't modify the value, recurse on its
12057     // vector input.
12058     return FindScalarElement(III->getOperand(0), EltNo, Context);
12059   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12060     unsigned LHSWidth =
12061       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12062     unsigned InEl = getShuffleMask(SVI)[EltNo];
12063     if (InEl < LHSWidth)
12064       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12065     else if (InEl < LHSWidth*2)
12066       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12067     else
12068       return UndefValue::get(PTy->getElementType());
12069   }
12070   
12071   // Otherwise, we don't know.
12072   return 0;
12073 }
12074
12075 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12076   // If vector val is undef, replace extract with scalar undef.
12077   if (isa<UndefValue>(EI.getOperand(0)))
12078     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12079
12080   // If vector val is constant 0, replace extract with scalar 0.
12081   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12082     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12083   
12084   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12085     // If vector val is constant with all elements the same, replace EI with
12086     // that element. When the elements are not identical, we cannot replace yet
12087     // (we do that below, but only when the index is constant).
12088     Constant *op0 = C->getOperand(0);
12089     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12090       if (C->getOperand(i) != op0) {
12091         op0 = 0; 
12092         break;
12093       }
12094     if (op0)
12095       return ReplaceInstUsesWith(EI, op0);
12096   }
12097   
12098   // If extracting a specified index from the vector, see if we can recursively
12099   // find a previously computed scalar that was inserted into the vector.
12100   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12101     unsigned IndexVal = IdxC->getZExtValue();
12102     unsigned VectorWidth = 
12103       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12104       
12105     // If this is extracting an invalid index, turn this into undef, to avoid
12106     // crashing the code below.
12107     if (IndexVal >= VectorWidth)
12108       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12109     
12110     // This instruction only demands the single element from the input vector.
12111     // If the input vector has a single use, simplify it based on this use
12112     // property.
12113     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12114       APInt UndefElts(VectorWidth, 0);
12115       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12116       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12117                                                 DemandedMask, UndefElts)) {
12118         EI.setOperand(0, V);
12119         return &EI;
12120       }
12121     }
12122     
12123     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12124       return ReplaceInstUsesWith(EI, Elt);
12125     
12126     // If the this extractelement is directly using a bitcast from a vector of
12127     // the same number of elements, see if we can find the source element from
12128     // it.  In this case, we will end up needing to bitcast the scalars.
12129     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12130       if (const VectorType *VT = 
12131               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12132         if (VT->getNumElements() == VectorWidth)
12133           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12134                                              IndexVal, Context))
12135             return new BitCastInst(Elt, EI.getType());
12136     }
12137   }
12138   
12139   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12140     if (I->hasOneUse()) {
12141       // Push extractelement into predecessor operation if legal and
12142       // profitable to do so
12143       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12144         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12145         if (CheapToScalarize(BO, isConstantElt)) {
12146           Value *newEI0 =
12147             Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12148                                           EI.getName()+".lhs");
12149           Value *newEI1 =
12150             Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12151                                           EI.getName()+".rhs");
12152           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12153         }
12154       } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
12155         unsigned AS = LI->getPointerAddressSpace();
12156         Value *Ptr = Builder->CreateBitCast(I->getOperand(0),
12157                                             PointerType::get(EI.getType(), AS),
12158                                             I->getOperand(0)->getName());
12159         Value *GEP =
12160           Builder->CreateGEP(Ptr, EI.getOperand(1), I->getName()+".gep");
12161         cast<GEPOperator>(GEP)->setIsInBounds(true);
12162         
12163         LoadInst *Load = Builder->CreateLoad(GEP, "tmp");
12164
12165         // Make sure the Load goes before the load instruction in the source,
12166         // not wherever the extract happens to be.
12167         if (Instruction *P = dyn_cast<Instruction>(Ptr))
12168           P->moveBefore(I);
12169         if (Instruction *G = dyn_cast<Instruction>(GEP))
12170           G->moveBefore(I);
12171         Load->moveBefore(I);
12172         
12173         return ReplaceInstUsesWith(EI, Load);
12174       }
12175     }
12176     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12177       // Extracting the inserted element?
12178       if (IE->getOperand(2) == EI.getOperand(1))
12179         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12180       // If the inserted and extracted elements are constants, they must not
12181       // be the same value, extract from the pre-inserted value instead.
12182       if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
12183         Worklist.AddValue(EI.getOperand(0));
12184         EI.setOperand(0, IE->getOperand(0));
12185         return &EI;
12186       }
12187     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12188       // If this is extracting an element from a shufflevector, figure out where
12189       // it came from and extract from the appropriate input element instead.
12190       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12191         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12192         Value *Src;
12193         unsigned LHSWidth =
12194           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12195
12196         if (SrcIdx < LHSWidth)
12197           Src = SVI->getOperand(0);
12198         else if (SrcIdx < LHSWidth*2) {
12199           SrcIdx -= LHSWidth;
12200           Src = SVI->getOperand(1);
12201         } else {
12202           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12203         }
12204         return ExtractElementInst::Create(Src,
12205                          ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12206                                           false));
12207       }
12208     }
12209     // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12210   }
12211   return 0;
12212 }
12213
12214 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12215 /// elements from either LHS or RHS, return the shuffle mask and true. 
12216 /// Otherwise, return false.
12217 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12218                                          std::vector<Constant*> &Mask,
12219                                          LLVMContext *Context) {
12220   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12221          "Invalid CollectSingleShuffleElements");
12222   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12223
12224   if (isa<UndefValue>(V)) {
12225     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12226     return true;
12227   } else if (V == LHS) {
12228     for (unsigned i = 0; i != NumElts; ++i)
12229       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12230     return true;
12231   } else if (V == RHS) {
12232     for (unsigned i = 0; i != NumElts; ++i)
12233       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
12234     return true;
12235   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12236     // If this is an insert of an extract from some other vector, include it.
12237     Value *VecOp    = IEI->getOperand(0);
12238     Value *ScalarOp = IEI->getOperand(1);
12239     Value *IdxOp    = IEI->getOperand(2);
12240     
12241     if (!isa<ConstantInt>(IdxOp))
12242       return false;
12243     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12244     
12245     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12246       // Okay, we can handle this if the vector we are insertinting into is
12247       // transitively ok.
12248       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12249         // If so, update the mask to reflect the inserted undef.
12250         Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
12251         return true;
12252       }      
12253     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12254       if (isa<ConstantInt>(EI->getOperand(1)) &&
12255           EI->getOperand(0)->getType() == V->getType()) {
12256         unsigned ExtractedIdx =
12257           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12258         
12259         // This must be extracting from either LHS or RHS.
12260         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12261           // Okay, we can handle this if the vector we are insertinting into is
12262           // transitively ok.
12263           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12264             // If so, update the mask to reflect the inserted value.
12265             if (EI->getOperand(0) == LHS) {
12266               Mask[InsertedIdx % NumElts] = 
12267                  ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12268             } else {
12269               assert(EI->getOperand(0) == RHS);
12270               Mask[InsertedIdx % NumElts] = 
12271                 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
12272               
12273             }
12274             return true;
12275           }
12276         }
12277       }
12278     }
12279   }
12280   // TODO: Handle shufflevector here!
12281   
12282   return false;
12283 }
12284
12285 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12286 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12287 /// that computes V and the LHS value of the shuffle.
12288 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12289                                      Value *&RHS, LLVMContext *Context) {
12290   assert(isa<VectorType>(V->getType()) && 
12291          (RHS == 0 || V->getType() == RHS->getType()) &&
12292          "Invalid shuffle!");
12293   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12294
12295   if (isa<UndefValue>(V)) {
12296     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12297     return V;
12298   } else if (isa<ConstantAggregateZero>(V)) {
12299     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
12300     return V;
12301   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12302     // If this is an insert of an extract from some other vector, include it.
12303     Value *VecOp    = IEI->getOperand(0);
12304     Value *ScalarOp = IEI->getOperand(1);
12305     Value *IdxOp    = IEI->getOperand(2);
12306     
12307     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12308       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12309           EI->getOperand(0)->getType() == V->getType()) {
12310         unsigned ExtractedIdx =
12311           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12312         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12313         
12314         // Either the extracted from or inserted into vector must be RHSVec,
12315         // otherwise we'd end up with a shuffle of three inputs.
12316         if (EI->getOperand(0) == RHS || RHS == 0) {
12317           RHS = EI->getOperand(0);
12318           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12319           Mask[InsertedIdx % NumElts] = 
12320             ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
12321           return V;
12322         }
12323         
12324         if (VecOp == RHS) {
12325           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12326                                             RHS, Context);
12327           // Everything but the extracted element is replaced with the RHS.
12328           for (unsigned i = 0; i != NumElts; ++i) {
12329             if (i != InsertedIdx)
12330               Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
12331           }
12332           return V;
12333         }
12334         
12335         // If this insertelement is a chain that comes from exactly these two
12336         // vectors, return the vector and the effective shuffle.
12337         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12338                                          Context))
12339           return EI->getOperand(0);
12340         
12341       }
12342     }
12343   }
12344   // TODO: Handle shufflevector here!
12345   
12346   // Otherwise, can't do anything fancy.  Return an identity vector.
12347   for (unsigned i = 0; i != NumElts; ++i)
12348     Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12349   return V;
12350 }
12351
12352 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12353   Value *VecOp    = IE.getOperand(0);
12354   Value *ScalarOp = IE.getOperand(1);
12355   Value *IdxOp    = IE.getOperand(2);
12356   
12357   // Inserting an undef or into an undefined place, remove this.
12358   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12359     ReplaceInstUsesWith(IE, VecOp);
12360   
12361   // If the inserted element was extracted from some other vector, and if the 
12362   // indexes are constant, try to turn this into a shufflevector operation.
12363   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12364     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12365         EI->getOperand(0)->getType() == IE.getType()) {
12366       unsigned NumVectorElts = IE.getType()->getNumElements();
12367       unsigned ExtractedIdx =
12368         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12369       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12370       
12371       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12372         return ReplaceInstUsesWith(IE, VecOp);
12373       
12374       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12375         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12376       
12377       // If we are extracting a value from a vector, then inserting it right
12378       // back into the same place, just use the input vector.
12379       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12380         return ReplaceInstUsesWith(IE, VecOp);      
12381       
12382       // We could theoretically do this for ANY input.  However, doing so could
12383       // turn chains of insertelement instructions into a chain of shufflevector
12384       // instructions, and right now we do not merge shufflevectors.  As such,
12385       // only do this in a situation where it is clear that there is benefit.
12386       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12387         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12388         // the values of VecOp, except then one read from EIOp0.
12389         // Build a new shuffle mask.
12390         std::vector<Constant*> Mask;
12391         if (isa<UndefValue>(VecOp))
12392           Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
12393         else {
12394           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12395           Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
12396                                                        NumVectorElts));
12397         } 
12398         Mask[InsertedIdx] = 
12399                            ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12400         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12401                                      ConstantVector::get(Mask));
12402       }
12403       
12404       // If this insertelement isn't used by some other insertelement, turn it
12405       // (and any insertelements it points to), into one big shuffle.
12406       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12407         std::vector<Constant*> Mask;
12408         Value *RHS = 0;
12409         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12410         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12411         // We now have a shuffle of LHS, RHS, Mask.
12412         return new ShuffleVectorInst(LHS, RHS,
12413                                      ConstantVector::get(Mask));
12414       }
12415     }
12416   }
12417
12418   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12419   APInt UndefElts(VWidth, 0);
12420   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12421   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12422     return &IE;
12423
12424   return 0;
12425 }
12426
12427
12428 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12429   Value *LHS = SVI.getOperand(0);
12430   Value *RHS = SVI.getOperand(1);
12431   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12432
12433   bool MadeChange = false;
12434
12435   // Undefined shuffle mask -> undefined value.
12436   if (isa<UndefValue>(SVI.getOperand(2)))
12437     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12438
12439   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12440
12441   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12442     return 0;
12443
12444   APInt UndefElts(VWidth, 0);
12445   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12446   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12447     LHS = SVI.getOperand(0);
12448     RHS = SVI.getOperand(1);
12449     MadeChange = true;
12450   }
12451   
12452   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12453   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12454   if (LHS == RHS || isa<UndefValue>(LHS)) {
12455     if (isa<UndefValue>(LHS) && LHS == RHS) {
12456       // shuffle(undef,undef,mask) -> undef.
12457       return ReplaceInstUsesWith(SVI, LHS);
12458     }
12459     
12460     // Remap any references to RHS to use LHS.
12461     std::vector<Constant*> Elts;
12462     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12463       if (Mask[i] >= 2*e)
12464         Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12465       else {
12466         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12467             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12468           Mask[i] = 2*e;     // Turn into undef.
12469           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12470         } else {
12471           Mask[i] = Mask[i] % e;  // Force to LHS.
12472           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
12473         }
12474       }
12475     }
12476     SVI.setOperand(0, SVI.getOperand(1));
12477     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12478     SVI.setOperand(2, ConstantVector::get(Elts));
12479     LHS = SVI.getOperand(0);
12480     RHS = SVI.getOperand(1);
12481     MadeChange = true;
12482   }
12483   
12484   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12485   bool isLHSID = true, isRHSID = true;
12486     
12487   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12488     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12489     // Is this an identity shuffle of the LHS value?
12490     isLHSID &= (Mask[i] == i);
12491       
12492     // Is this an identity shuffle of the RHS value?
12493     isRHSID &= (Mask[i]-e == i);
12494   }
12495
12496   // Eliminate identity shuffles.
12497   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12498   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12499   
12500   // If the LHS is a shufflevector itself, see if we can combine it with this
12501   // one without producing an unusual shuffle.  Here we are really conservative:
12502   // we are absolutely afraid of producing a shuffle mask not in the input
12503   // program, because the code gen may not be smart enough to turn a merged
12504   // shuffle into two specific shuffles: it may produce worse code.  As such,
12505   // we only merge two shuffles if the result is one of the two input shuffle
12506   // masks.  In this case, merging the shuffles just removes one instruction,
12507   // which we know is safe.  This is good for things like turning:
12508   // (splat(splat)) -> splat.
12509   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12510     if (isa<UndefValue>(RHS)) {
12511       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12512
12513       std::vector<unsigned> NewMask;
12514       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12515         if (Mask[i] >= 2*e)
12516           NewMask.push_back(2*e);
12517         else
12518           NewMask.push_back(LHSMask[Mask[i]]);
12519       
12520       // If the result mask is equal to the src shuffle or this shuffle mask, do
12521       // the replacement.
12522       if (NewMask == LHSMask || NewMask == Mask) {
12523         unsigned LHSInNElts =
12524           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12525         std::vector<Constant*> Elts;
12526         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12527           if (NewMask[i] >= LHSInNElts*2) {
12528             Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12529           } else {
12530             Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
12531           }
12532         }
12533         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12534                                      LHSSVI->getOperand(1),
12535                                      ConstantVector::get(Elts));
12536       }
12537     }
12538   }
12539
12540   return MadeChange ? &SVI : 0;
12541 }
12542
12543
12544
12545
12546 /// TryToSinkInstruction - Try to move the specified instruction from its
12547 /// current block into the beginning of DestBlock, which can only happen if it's
12548 /// safe to move the instruction past all of the instructions between it and the
12549 /// end of its block.
12550 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12551   assert(I->hasOneUse() && "Invariants didn't hold!");
12552
12553   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12554   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12555     return false;
12556
12557   // Do not sink alloca instructions out of the entry block.
12558   if (isa<AllocaInst>(I) && I->getParent() ==
12559         &DestBlock->getParent()->getEntryBlock())
12560     return false;
12561
12562   // We can only sink load instructions if there is nothing between the load and
12563   // the end of block that could change the value.
12564   if (I->mayReadFromMemory()) {
12565     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12566          Scan != E; ++Scan)
12567       if (Scan->mayWriteToMemory())
12568         return false;
12569   }
12570
12571   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12572
12573   CopyPrecedingStopPoint(I, InsertPos);
12574   I->moveBefore(InsertPos);
12575   ++NumSunkInst;
12576   return true;
12577 }
12578
12579
12580 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12581 /// all reachable code to the worklist.
12582 ///
12583 /// This has a couple of tricks to make the code faster and more powerful.  In
12584 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12585 /// them to the worklist (this significantly speeds up instcombine on code where
12586 /// many instructions are dead or constant).  Additionally, if we find a branch
12587 /// whose condition is a known constant, we only visit the reachable successors.
12588 ///
12589 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12590                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12591                                        InstCombiner &IC,
12592                                        const TargetData *TD) {
12593   SmallVector<BasicBlock*, 256> Worklist;
12594   Worklist.push_back(BB);
12595
12596   while (!Worklist.empty()) {
12597     BB = Worklist.back();
12598     Worklist.pop_back();
12599     
12600     // We have now visited this block!  If we've already been here, ignore it.
12601     if (!Visited.insert(BB)) continue;
12602
12603     DbgInfoIntrinsic *DBI_Prev = NULL;
12604     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12605       Instruction *Inst = BBI++;
12606       
12607       // DCE instruction if trivially dead.
12608       if (isInstructionTriviallyDead(Inst)) {
12609         ++NumDeadInst;
12610         DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
12611         Inst->eraseFromParent();
12612         continue;
12613       }
12614       
12615       // ConstantProp instruction if trivially constant.
12616       if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12617         DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12618                      << *Inst << '\n');
12619         Inst->replaceAllUsesWith(C);
12620         ++NumConstProp;
12621         Inst->eraseFromParent();
12622         continue;
12623       }
12624      
12625       // If there are two consecutive llvm.dbg.stoppoint calls then
12626       // it is likely that the optimizer deleted code in between these
12627       // two intrinsics. 
12628       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12629       if (DBI_Next) {
12630         if (DBI_Prev
12631             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12632             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12633           IC.Worklist.Remove(DBI_Prev);
12634           DBI_Prev->eraseFromParent();
12635         }
12636         DBI_Prev = DBI_Next;
12637       } else {
12638         DBI_Prev = 0;
12639       }
12640
12641       IC.Worklist.Add(Inst);
12642     }
12643
12644     // Recursively visit successors.  If this is a branch or switch on a
12645     // constant, only visit the reachable successor.
12646     TerminatorInst *TI = BB->getTerminator();
12647     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12648       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12649         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12650         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12651         Worklist.push_back(ReachableBB);
12652         continue;
12653       }
12654     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12655       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12656         // See if this is an explicit destination.
12657         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12658           if (SI->getCaseValue(i) == Cond) {
12659             BasicBlock *ReachableBB = SI->getSuccessor(i);
12660             Worklist.push_back(ReachableBB);
12661             continue;
12662           }
12663         
12664         // Otherwise it is the default destination.
12665         Worklist.push_back(SI->getSuccessor(0));
12666         continue;
12667       }
12668     }
12669     
12670     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12671       Worklist.push_back(TI->getSuccessor(i));
12672   }
12673 }
12674
12675 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12676   bool Changed = false;
12677   TD = getAnalysisIfAvailable<TargetData>();
12678   
12679   DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12680         << F.getNameStr() << "\n");
12681
12682   {
12683     // Do a depth-first traversal of the function, populate the worklist with
12684     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12685     // track of which blocks we visit.
12686     SmallPtrSet<BasicBlock*, 64> Visited;
12687     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12688
12689     // Do a quick scan over the function.  If we find any blocks that are
12690     // unreachable, remove any instructions inside of them.  This prevents
12691     // the instcombine code from having to deal with some bad special cases.
12692     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12693       if (!Visited.count(BB)) {
12694         Instruction *Term = BB->getTerminator();
12695         while (Term != BB->begin()) {   // Remove instrs bottom-up
12696           BasicBlock::iterator I = Term; --I;
12697
12698           DEBUG(errs() << "IC: DCE: " << *I << '\n');
12699           // A debug intrinsic shouldn't force another iteration if we weren't
12700           // going to do one without it.
12701           if (!isa<DbgInfoIntrinsic>(I)) {
12702             ++NumDeadInst;
12703             Changed = true;
12704           }
12705           if (!I->use_empty())
12706             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12707           I->eraseFromParent();
12708         }
12709       }
12710   }
12711
12712   while (!Worklist.isEmpty()) {
12713     Instruction *I = Worklist.RemoveOne();
12714     if (I == 0) continue;  // skip null values.
12715
12716     // Check to see if we can DCE the instruction.
12717     if (isInstructionTriviallyDead(I)) {
12718       DEBUG(errs() << "IC: DCE: " << *I << '\n');
12719       EraseInstFromFunction(*I);
12720       ++NumDeadInst;
12721       Changed = true;
12722       continue;
12723     }
12724
12725     // Instruction isn't dead, see if we can constant propagate it.
12726     if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12727       DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
12728
12729       // Add operands to the worklist.
12730       ReplaceInstUsesWith(*I, C);
12731       ++NumConstProp;
12732       EraseInstFromFunction(*I);
12733       Changed = true;
12734       continue;
12735     }
12736
12737     if (TD) {
12738       // See if we can constant fold its operands.
12739       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12740         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
12741           if (Constant *NewC = ConstantFoldConstantExpression(CE,   
12742                                   F.getContext(), TD))
12743             if (NewC != CE) {
12744               i->set(NewC);
12745               Changed = true;
12746             }
12747     }
12748
12749     // See if we can trivially sink this instruction to a successor basic block.
12750     if (I->hasOneUse()) {
12751       BasicBlock *BB = I->getParent();
12752       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12753       if (UserParent != BB) {
12754         bool UserIsSuccessor = false;
12755         // See if the user is one of our successors.
12756         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12757           if (*SI == UserParent) {
12758             UserIsSuccessor = true;
12759             break;
12760           }
12761
12762         // If the user is one of our immediate successors, and if that successor
12763         // only has us as a predecessors (we'd have to split the critical edge
12764         // otherwise), we can keep going.
12765         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12766             next(pred_begin(UserParent)) == pred_end(UserParent))
12767           // Okay, the CFG is simple enough, try to sink this instruction.
12768           Changed |= TryToSinkInstruction(I, UserParent);
12769       }
12770     }
12771
12772     // Now that we have an instruction, try combining it to simplify it.
12773     Builder->SetInsertPoint(I->getParent(), I);
12774     
12775 #ifndef NDEBUG
12776     std::string OrigI;
12777 #endif
12778     DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
12779     
12780     if (Instruction *Result = visit(*I)) {
12781       ++NumCombined;
12782       // Should we replace the old instruction with a new one?
12783       if (Result != I) {
12784         DEBUG(errs() << "IC: Old = " << *I << '\n'
12785                      << "    New = " << *Result << '\n');
12786
12787         // Everything uses the new instruction now.
12788         I->replaceAllUsesWith(Result);
12789
12790         // Push the new instruction and any users onto the worklist.
12791         Worklist.Add(Result);
12792         Worklist.AddUsersToWorkList(*Result);
12793
12794         // Move the name to the new instruction first.
12795         Result->takeName(I);
12796
12797         // Insert the new instruction into the basic block...
12798         BasicBlock *InstParent = I->getParent();
12799         BasicBlock::iterator InsertPos = I;
12800
12801         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
12802           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12803             ++InsertPos;
12804
12805         InstParent->getInstList().insert(InsertPos, Result);
12806
12807         EraseInstFromFunction(*I);
12808       } else {
12809 #ifndef NDEBUG
12810         DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12811                      << "    New = " << *I << '\n');
12812 #endif
12813
12814         // If the instruction was modified, it's possible that it is now dead.
12815         // if so, remove it.
12816         if (isInstructionTriviallyDead(I)) {
12817           EraseInstFromFunction(*I);
12818         } else {
12819           Worklist.Add(I);
12820           Worklist.AddUsersToWorkList(*I);
12821         }
12822       }
12823       Changed = true;
12824     }
12825   }
12826
12827   Worklist.Zap();
12828   return Changed;
12829 }
12830
12831
12832 bool InstCombiner::runOnFunction(Function &F) {
12833   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12834   Context = &F.getContext();
12835   
12836   
12837   /// Builder - This is an IRBuilder that automatically inserts new
12838   /// instructions into the worklist when they are created.
12839   IRBuilder<true, ConstantFolder, InstCombineIRInserter> 
12840     TheBuilder(F.getContext(), ConstantFolder(F.getContext()),
12841                InstCombineIRInserter(Worklist));
12842   Builder = &TheBuilder;
12843   
12844   bool EverMadeChange = false;
12845
12846   // Iterate while there is work to do.
12847   unsigned Iteration = 0;
12848   while (DoOneIteration(F, Iteration++))
12849     EverMadeChange = true;
12850   
12851   Builder = 0;
12852   return EverMadeChange;
12853 }
12854
12855 FunctionPass *llvm::createInstructionCombiningPass() {
12856   return new InstCombiner();
12857 }