Fix PR5262: when folding select into PHI, make sure all operands are available
[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/MallocHelper.h"
46 #include "llvm/Analysis/ValueTracking.h"
47 #include "llvm/Target/TargetData.h"
48 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
49 #include "llvm/Transforms/Utils/Local.h"
50 #include "llvm/Support/CallSite.h"
51 #include "llvm/Support/ConstantRange.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/ErrorHandling.h"
54 #include "llvm/Support/GetElementPtrTypeIterator.h"
55 #include "llvm/Support/InstVisitor.h"
56 #include "llvm/Support/IRBuilder.h"
57 #include "llvm/Support/MathExtras.h"
58 #include "llvm/Support/PatternMatch.h"
59 #include "llvm/Support/TargetFolder.h"
60 #include "llvm/Support/raw_ostream.h"
61 #include "llvm/ADT/DenseMap.h"
62 #include "llvm/ADT/SmallVector.h"
63 #include "llvm/ADT/SmallPtrSet.h"
64 #include "llvm/ADT/Statistic.h"
65 #include "llvm/ADT/STLExtras.h"
66 #include <algorithm>
67 #include <climits>
68 using namespace llvm;
69 using namespace llvm::PatternMatch;
70
71 STATISTIC(NumCombined , "Number of insts combined");
72 STATISTIC(NumConstProp, "Number of constant folds");
73 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
74 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
75 STATISTIC(NumSunkInst , "Number of instructions sunk");
76
77 namespace {
78   /// InstCombineWorklist - This is the worklist management logic for
79   /// InstCombine.
80   class InstCombineWorklist {
81     SmallVector<Instruction*, 256> Worklist;
82     DenseMap<Instruction*, unsigned> WorklistMap;
83     
84     void operator=(const InstCombineWorklist&RHS);   // DO NOT IMPLEMENT
85     InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
86   public:
87     InstCombineWorklist() {}
88     
89     bool isEmpty() const { return Worklist.empty(); }
90     
91     /// Add - Add the specified instruction to the worklist if it isn't already
92     /// in it.
93     void Add(Instruction *I) {
94       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second) {
95         DEBUG(errs() << "IC: ADD: " << *I << '\n');
96         Worklist.push_back(I);
97       }
98     }
99     
100     void AddValue(Value *V) {
101       if (Instruction *I = dyn_cast<Instruction>(V))
102         Add(I);
103     }
104     
105     /// AddInitialGroup - Add the specified batch of stuff in reverse order.
106     /// which should only be done when the worklist is empty and when the group
107     /// has no duplicates.
108     void AddInitialGroup(Instruction *const *List, unsigned NumEntries) {
109       assert(Worklist.empty() && "Worklist must be empty to add initial group");
110       Worklist.reserve(NumEntries+16);
111       DEBUG(errs() << "IC: ADDING: " << NumEntries << " instrs to worklist\n");
112       for (; NumEntries; --NumEntries) {
113         Instruction *I = List[NumEntries-1];
114         WorklistMap.insert(std::make_pair(I, Worklist.size()));
115         Worklist.push_back(I);
116       }
117     }
118     
119     // Remove - remove I from the worklist if it exists.
120     void Remove(Instruction *I) {
121       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
122       if (It == WorklistMap.end()) return; // Not in worklist.
123       
124       // Don't bother moving everything down, just null out the slot.
125       Worklist[It->second] = 0;
126       
127       WorklistMap.erase(It);
128     }
129     
130     Instruction *RemoveOne() {
131       Instruction *I = Worklist.back();
132       Worklist.pop_back();
133       WorklistMap.erase(I);
134       return I;
135     }
136
137     /// AddUsersToWorkList - When an instruction is simplified, add all users of
138     /// the instruction to the work lists because they might get more simplified
139     /// now.
140     ///
141     void AddUsersToWorkList(Instruction &I) {
142       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
143            UI != UE; ++UI)
144         Add(cast<Instruction>(*UI));
145     }
146     
147     
148     /// Zap - check that the worklist is empty and nuke the backing store for
149     /// the map if it is large.
150     void Zap() {
151       assert(WorklistMap.empty() && "Worklist empty, but map not?");
152       
153       // Do an explicit clear, this shrinks the map if needed.
154       WorklistMap.clear();
155     }
156   };
157 } // end anonymous namespace.
158
159
160 namespace {
161   /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
162   /// just like the normal insertion helper, but also adds any new instructions
163   /// to the instcombine worklist.
164   class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
165     InstCombineWorklist &Worklist;
166   public:
167     InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
168     
169     void InsertHelper(Instruction *I, const Twine &Name,
170                       BasicBlock *BB, BasicBlock::iterator InsertPt) const {
171       IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
172       Worklist.Add(I);
173     }
174   };
175 } // end anonymous namespace
176
177
178 namespace {
179   class InstCombiner : public FunctionPass,
180                        public InstVisitor<InstCombiner, Instruction*> {
181     TargetData *TD;
182     bool MustPreserveLCSSA;
183     bool MadeIRChange;
184   public:
185     /// Worklist - All of the instructions that need to be simplified.
186     InstCombineWorklist Worklist;
187
188     /// Builder - This is an IRBuilder that automatically inserts new
189     /// instructions into the worklist when they are created.
190     typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
191     BuilderTy *Builder;
192         
193     static char ID; // Pass identification, replacement for typeid
194     InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
195
196     LLVMContext *Context;
197     LLVMContext *getContext() const { return Context; }
198
199   public:
200     virtual bool runOnFunction(Function &F);
201     
202     bool DoOneIteration(Function &F, unsigned ItNum);
203
204     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
205       AU.addPreservedID(LCSSAID);
206       AU.setPreservesCFG();
207     }
208
209     TargetData *getTargetData() const { return TD; }
210
211     // Visitation implementation - Implement instruction combining for different
212     // instruction types.  The semantics are as follows:
213     // Return Value:
214     //    null        - No change was made
215     //     I          - Change was made, I is still valid, I may be dead though
216     //   otherwise    - Change was made, replace I with returned instruction
217     //
218     Instruction *visitAdd(BinaryOperator &I);
219     Instruction *visitFAdd(BinaryOperator &I);
220     Instruction *visitSub(BinaryOperator &I);
221     Instruction *visitFSub(BinaryOperator &I);
222     Instruction *visitMul(BinaryOperator &I);
223     Instruction *visitFMul(BinaryOperator &I);
224     Instruction *visitURem(BinaryOperator &I);
225     Instruction *visitSRem(BinaryOperator &I);
226     Instruction *visitFRem(BinaryOperator &I);
227     bool SimplifyDivRemOfSelect(BinaryOperator &I);
228     Instruction *commonRemTransforms(BinaryOperator &I);
229     Instruction *commonIRemTransforms(BinaryOperator &I);
230     Instruction *commonDivTransforms(BinaryOperator &I);
231     Instruction *commonIDivTransforms(BinaryOperator &I);
232     Instruction *visitUDiv(BinaryOperator &I);
233     Instruction *visitSDiv(BinaryOperator &I);
234     Instruction *visitFDiv(BinaryOperator &I);
235     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
236     Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
237     Instruction *visitAnd(BinaryOperator &I);
238     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
239     Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
240     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
241                                      Value *A, Value *B, Value *C);
242     Instruction *visitOr (BinaryOperator &I);
243     Instruction *visitXor(BinaryOperator &I);
244     Instruction *visitShl(BinaryOperator &I);
245     Instruction *visitAShr(BinaryOperator &I);
246     Instruction *visitLShr(BinaryOperator &I);
247     Instruction *commonShiftTransforms(BinaryOperator &I);
248     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
249                                       Constant *RHSC);
250     Instruction *visitFCmpInst(FCmpInst &I);
251     Instruction *visitICmpInst(ICmpInst &I);
252     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
253     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
254                                                 Instruction *LHS,
255                                                 ConstantInt *RHS);
256     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
257                                 ConstantInt *DivRHS);
258
259     Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
260                              ICmpInst::Predicate Cond, Instruction &I);
261     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
262                                      BinaryOperator &I);
263     Instruction *commonCastTransforms(CastInst &CI);
264     Instruction *commonIntCastTransforms(CastInst &CI);
265     Instruction *commonPointerCastTransforms(CastInst &CI);
266     Instruction *visitTrunc(TruncInst &CI);
267     Instruction *visitZExt(ZExtInst &CI);
268     Instruction *visitSExt(SExtInst &CI);
269     Instruction *visitFPTrunc(FPTruncInst &CI);
270     Instruction *visitFPExt(CastInst &CI);
271     Instruction *visitFPToUI(FPToUIInst &FI);
272     Instruction *visitFPToSI(FPToSIInst &FI);
273     Instruction *visitUIToFP(CastInst &CI);
274     Instruction *visitSIToFP(CastInst &CI);
275     Instruction *visitPtrToInt(PtrToIntInst &CI);
276     Instruction *visitIntToPtr(IntToPtrInst &CI);
277     Instruction *visitBitCast(BitCastInst &CI);
278     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
279                                 Instruction *FI);
280     Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
281     Instruction *visitSelectInst(SelectInst &SI);
282     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
283     Instruction *visitCallInst(CallInst &CI);
284     Instruction *visitInvokeInst(InvokeInst &II);
285     Instruction *visitPHINode(PHINode &PN);
286     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
287     Instruction *visitAllocationInst(AllocationInst &AI);
288     Instruction *visitFreeInst(FreeInst &FI);
289     Instruction *visitLoadInst(LoadInst &LI);
290     Instruction *visitStoreInst(StoreInst &SI);
291     Instruction *visitBranchInst(BranchInst &BI);
292     Instruction *visitSwitchInst(SwitchInst &SI);
293     Instruction *visitInsertElementInst(InsertElementInst &IE);
294     Instruction *visitExtractElementInst(ExtractElementInst &EI);
295     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
296     Instruction *visitExtractValueInst(ExtractValueInst &EV);
297
298     // visitInstruction - Specify what to return for unhandled instructions...
299     Instruction *visitInstruction(Instruction &I) { return 0; }
300
301   private:
302     Instruction *visitCallSite(CallSite CS);
303     bool transformConstExprCastCall(CallSite CS);
304     Instruction *transformCallThroughTrampoline(CallSite CS);
305     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
306                                    bool DoXform = true);
307     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
308     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
309
310
311   public:
312     // InsertNewInstBefore - insert an instruction New before instruction Old
313     // in the program.  Add the new instruction to the worklist.
314     //
315     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
316       assert(New && New->getParent() == 0 &&
317              "New instruction already inserted into a basic block!");
318       BasicBlock *BB = Old.getParent();
319       BB->getInstList().insert(&Old, New);  // Insert inst
320       Worklist.Add(New);
321       return New;
322     }
323         
324     // ReplaceInstUsesWith - This method is to be used when an instruction is
325     // found to be dead, replacable with another preexisting expression.  Here
326     // we add all uses of I to the worklist, replace all uses of I with the new
327     // value, then return I, so that the inst combiner will know that I was
328     // modified.
329     //
330     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
331       Worklist.AddUsersToWorkList(I);   // Add all modified instrs to worklist.
332       
333       // If we are replacing the instruction with itself, this must be in a
334       // segment of unreachable code, so just clobber the instruction.
335       if (&I == V) 
336         V = UndefValue::get(I.getType());
337         
338       I.replaceAllUsesWith(V);
339       return &I;
340     }
341
342     // EraseInstFromFunction - When dealing with an instruction that has side
343     // effects or produces a void value, we can't rely on DCE to delete the
344     // instruction.  Instead, visit methods should return the value returned by
345     // this function.
346     Instruction *EraseInstFromFunction(Instruction &I) {
347       DEBUG(errs() << "IC: ERASE " << I << '\n');
348
349       assert(I.use_empty() && "Cannot erase instruction that is used!");
350       // Make sure that we reprocess all operands now that we reduced their
351       // use counts.
352       if (I.getNumOperands() < 8) {
353         for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
354           if (Instruction *Op = dyn_cast<Instruction>(*i))
355             Worklist.Add(Op);
356       }
357       Worklist.Remove(&I);
358       I.eraseFromParent();
359       MadeIRChange = true;
360       return 0;  // Don't do anything with FI
361     }
362         
363     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
364                            APInt &KnownOne, unsigned Depth = 0) const {
365       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
366     }
367     
368     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
369                            unsigned Depth = 0) const {
370       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
371     }
372     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
373       return llvm::ComputeNumSignBits(Op, TD, Depth);
374     }
375
376   private:
377
378     /// SimplifyCommutative - This performs a few simplifications for 
379     /// commutative operators.
380     bool SimplifyCommutative(BinaryOperator &I);
381
382     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
383     /// most-complex to least-complex order.
384     bool SimplifyCompare(CmpInst &I);
385
386     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
387     /// based on the demanded bits.
388     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
389                                    APInt& KnownZero, APInt& KnownOne,
390                                    unsigned Depth);
391     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
392                               APInt& KnownZero, APInt& KnownOne,
393                               unsigned Depth=0);
394         
395     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
396     /// SimplifyDemandedBits knows about.  See if the instruction has any
397     /// properties that allow us to simplify its operands.
398     bool SimplifyDemandedInstructionBits(Instruction &Inst);
399         
400     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
401                                       APInt& UndefElts, unsigned Depth = 0);
402       
403     // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
404     // which has a PHI node as operand #0, see if we can fold the instruction
405     // into the PHI (which is only possible if all operands to the PHI are
406     // constants).
407     //
408     // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
409     // that would normally be unprofitable because they strongly encourage jump
410     // threading.
411     Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
412
413     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
414     // operator and they all are only used by the PHI, PHI together their
415     // inputs, and do the operation once, to the result of the PHI.
416     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
417     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
418     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
419
420     
421     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
422                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
423     
424     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
425                               bool isSub, Instruction &I);
426     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
427                                  bool isSigned, bool Inside, Instruction &IB);
428     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
429     Instruction *MatchBSwap(BinaryOperator &I);
430     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
431     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
432     Instruction *SimplifyMemSet(MemSetInst *MI);
433
434
435     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
436
437     bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
438                                     unsigned CastOpc, int &NumCastsRemoved);
439     unsigned GetOrEnforceKnownAlignment(Value *V,
440                                         unsigned PrefAlign = 0);
441
442   };
443 } // end anonymous namespace
444
445 char InstCombiner::ID = 0;
446 static RegisterPass<InstCombiner>
447 X("instcombine", "Combine redundant instructions");
448
449 // getComplexity:  Assign a complexity or rank value to LLVM Values...
450 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
451 static unsigned getComplexity(Value *V) {
452   if (isa<Instruction>(V)) {
453     if (BinaryOperator::isNeg(V) ||
454         BinaryOperator::isFNeg(V) ||
455         BinaryOperator::isNot(V))
456       return 3;
457     return 4;
458   }
459   if (isa<Argument>(V)) return 3;
460   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
461 }
462
463 // isOnlyUse - Return true if this instruction will be deleted if we stop using
464 // it.
465 static bool isOnlyUse(Value *V) {
466   return V->hasOneUse() || isa<Constant>(V);
467 }
468
469 // getPromotedType - Return the specified type promoted as it would be to pass
470 // though a va_arg area...
471 static const Type *getPromotedType(const Type *Ty) {
472   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
473     if (ITy->getBitWidth() < 32)
474       return Type::getInt32Ty(Ty->getContext());
475   }
476   return Ty;
477 }
478
479 /// getBitCastOperand - If the specified operand is a CastInst, a constant
480 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
481 /// operand value, otherwise return null.
482 static Value *getBitCastOperand(Value *V) {
483   if (Operator *O = dyn_cast<Operator>(V)) {
484     if (O->getOpcode() == Instruction::BitCast)
485       return O->getOperand(0);
486     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
487       if (GEP->hasAllZeroIndices())
488         return GEP->getPointerOperand();
489   }
490   return 0;
491 }
492
493 /// This function is a wrapper around CastInst::isEliminableCastPair. It
494 /// simply extracts arguments and returns what that function returns.
495 static Instruction::CastOps 
496 isEliminableCastPair(
497   const CastInst *CI, ///< The first cast instruction
498   unsigned opcode,       ///< The opcode of the second cast instruction
499   const Type *DstTy,     ///< The target type for the second cast instruction
500   TargetData *TD         ///< The target data for pointer size
501 ) {
502
503   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
504   const Type *MidTy = CI->getType();                  // B from above
505
506   // Get the opcodes of the two Cast instructions
507   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
508   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
509
510   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
511                                                 DstTy,
512                                   TD ? TD->getIntPtrType(CI->getContext()) : 0);
513   
514   // We don't want to form an inttoptr or ptrtoint that converts to an integer
515   // type that differs from the pointer size.
516   if ((Res == Instruction::IntToPtr &&
517           (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
518       (Res == Instruction::PtrToInt &&
519           (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
520     Res = 0;
521   
522   return Instruction::CastOps(Res);
523 }
524
525 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
526 /// in any code being generated.  It does not require codegen if V is simple
527 /// enough or if the cast can be folded into other casts.
528 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
529                               const Type *Ty, TargetData *TD) {
530   if (V->getType() == Ty || isa<Constant>(V)) return false;
531   
532   // If this is another cast that can be eliminated, it isn't codegen either.
533   if (const CastInst *CI = dyn_cast<CastInst>(V))
534     if (isEliminableCastPair(CI, opcode, Ty, TD))
535       return false;
536   return true;
537 }
538
539 // SimplifyCommutative - This performs a few simplifications for commutative
540 // operators:
541 //
542 //  1. Order operands such that they are listed from right (least complex) to
543 //     left (most complex).  This puts constants before unary operators before
544 //     binary operators.
545 //
546 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
547 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
548 //
549 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
550   bool Changed = false;
551   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
552     Changed = !I.swapOperands();
553
554   if (!I.isAssociative()) return Changed;
555   Instruction::BinaryOps Opcode = I.getOpcode();
556   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
557     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
558       if (isa<Constant>(I.getOperand(1))) {
559         Constant *Folded = ConstantExpr::get(I.getOpcode(),
560                                              cast<Constant>(I.getOperand(1)),
561                                              cast<Constant>(Op->getOperand(1)));
562         I.setOperand(0, Op->getOperand(0));
563         I.setOperand(1, Folded);
564         return true;
565       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
566         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
567             isOnlyUse(Op) && isOnlyUse(Op1)) {
568           Constant *C1 = cast<Constant>(Op->getOperand(1));
569           Constant *C2 = cast<Constant>(Op1->getOperand(1));
570
571           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
572           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
573           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
574                                                     Op1->getOperand(0),
575                                                     Op1->getName(), &I);
576           Worklist.Add(New);
577           I.setOperand(0, New);
578           I.setOperand(1, Folded);
579           return true;
580         }
581     }
582   return Changed;
583 }
584
585 /// SimplifyCompare - For a CmpInst this function just orders the operands
586 /// so that theyare listed from right (least complex) to left (most complex).
587 /// This puts constants before unary operators before binary operators.
588 bool InstCombiner::SimplifyCompare(CmpInst &I) {
589   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
590     return false;
591   I.swapOperands();
592   // Compare instructions are not associative so there's nothing else we can do.
593   return true;
594 }
595
596 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
597 // if the LHS is a constant zero (which is the 'negate' form).
598 //
599 static inline Value *dyn_castNegVal(Value *V) {
600   if (BinaryOperator::isNeg(V))
601     return BinaryOperator::getNegArgument(V);
602
603   // Constants can be considered to be negated values if they can be folded.
604   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
605     return ConstantExpr::getNeg(C);
606
607   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
608     if (C->getType()->getElementType()->isInteger())
609       return ConstantExpr::getNeg(C);
610
611   return 0;
612 }
613
614 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
615 // instruction if the LHS is a constant negative zero (which is the 'negate'
616 // form).
617 //
618 static inline Value *dyn_castFNegVal(Value *V) {
619   if (BinaryOperator::isFNeg(V))
620     return BinaryOperator::getFNegArgument(V);
621
622   // Constants can be considered to be negated values if they can be folded.
623   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
624     return ConstantExpr::getFNeg(C);
625
626   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
627     if (C->getType()->getElementType()->isFloatingPoint())
628       return ConstantExpr::getFNeg(C);
629
630   return 0;
631 }
632
633 static inline Value *dyn_castNotVal(Value *V) {
634   if (BinaryOperator::isNot(V))
635     return BinaryOperator::getNotArgument(V);
636
637   // Constants can be considered to be not'ed values...
638   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
639     return ConstantInt::get(C->getType(), ~C->getValue());
640   return 0;
641 }
642
643 // dyn_castFoldableMul - If this value is a multiply that can be folded into
644 // other computations (because it has a constant operand), return the
645 // non-constant operand of the multiply, and set CST to point to the multiplier.
646 // Otherwise, return null.
647 //
648 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
649   if (V->hasOneUse() && V->getType()->isInteger())
650     if (Instruction *I = dyn_cast<Instruction>(V)) {
651       if (I->getOpcode() == Instruction::Mul)
652         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
653           return I->getOperand(0);
654       if (I->getOpcode() == Instruction::Shl)
655         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
656           // The multiplier is really 1 << CST.
657           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
658           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
659           CST = ConstantInt::get(V->getType()->getContext(),
660                                  APInt(BitWidth, 1).shl(CSTVal));
661           return I->getOperand(0);
662         }
663     }
664   return 0;
665 }
666
667 /// AddOne - Add one to a ConstantInt
668 static Constant *AddOne(Constant *C) {
669   return ConstantExpr::getAdd(C, 
670     ConstantInt::get(C->getType(), 1));
671 }
672 /// SubOne - Subtract one from a ConstantInt
673 static Constant *SubOne(ConstantInt *C) {
674   return ConstantExpr::getSub(C, 
675     ConstantInt::get(C->getType(), 1));
676 }
677 /// MultiplyOverflows - True if the multiply can not be expressed in an int
678 /// this size.
679 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
680   uint32_t W = C1->getBitWidth();
681   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
682   if (sign) {
683     LHSExt.sext(W * 2);
684     RHSExt.sext(W * 2);
685   } else {
686     LHSExt.zext(W * 2);
687     RHSExt.zext(W * 2);
688   }
689
690   APInt MulExt = LHSExt * RHSExt;
691
692   if (sign) {
693     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
694     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
695     return MulExt.slt(Min) || MulExt.sgt(Max);
696   } else 
697     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
698 }
699
700
701 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
702 /// specified instruction is a constant integer.  If so, check to see if there
703 /// are any bits set in the constant that are not demanded.  If so, shrink the
704 /// constant and return true.
705 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
706                                    APInt Demanded) {
707   assert(I && "No instruction?");
708   assert(OpNo < I->getNumOperands() && "Operand index too large");
709
710   // If the operand is not a constant integer, nothing to do.
711   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
712   if (!OpC) return false;
713
714   // If there are no bits set that aren't demanded, nothing to do.
715   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
716   if ((~Demanded & OpC->getValue()) == 0)
717     return false;
718
719   // This instruction is producing bits that are not demanded. Shrink the RHS.
720   Demanded &= OpC->getValue();
721   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
722   return true;
723 }
724
725 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
726 // set of known zero and one bits, compute the maximum and minimum values that
727 // could have the specified known zero and known one bits, returning them in
728 // min/max.
729 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
730                                                    const APInt& KnownOne,
731                                                    APInt& Min, APInt& Max) {
732   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
733          KnownZero.getBitWidth() == Min.getBitWidth() &&
734          KnownZero.getBitWidth() == Max.getBitWidth() &&
735          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
736   APInt UnknownBits = ~(KnownZero|KnownOne);
737
738   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
739   // bit if it is unknown.
740   Min = KnownOne;
741   Max = KnownOne|UnknownBits;
742   
743   if (UnknownBits.isNegative()) { // Sign bit is unknown
744     Min.set(Min.getBitWidth()-1);
745     Max.clear(Max.getBitWidth()-1);
746   }
747 }
748
749 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
750 // a set of known zero and one bits, compute the maximum and minimum values that
751 // could have the specified known zero and known one bits, returning them in
752 // min/max.
753 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
754                                                      const APInt &KnownOne,
755                                                      APInt &Min, APInt &Max) {
756   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
757          KnownZero.getBitWidth() == Min.getBitWidth() &&
758          KnownZero.getBitWidth() == Max.getBitWidth() &&
759          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
760   APInt UnknownBits = ~(KnownZero|KnownOne);
761   
762   // The minimum value is when the unknown bits are all zeros.
763   Min = KnownOne;
764   // The maximum value is when the unknown bits are all ones.
765   Max = KnownOne|UnknownBits;
766 }
767
768 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
769 /// SimplifyDemandedBits knows about.  See if the instruction has any
770 /// properties that allow us to simplify its operands.
771 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
772   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
773   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
774   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
775   
776   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
777                                      KnownZero, KnownOne, 0);
778   if (V == 0) return false;
779   if (V == &Inst) return true;
780   ReplaceInstUsesWith(Inst, V);
781   return true;
782 }
783
784 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
785 /// specified instruction operand if possible, updating it in place.  It returns
786 /// true if it made any change and false otherwise.
787 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
788                                         APInt &KnownZero, APInt &KnownOne,
789                                         unsigned Depth) {
790   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
791                                           KnownZero, KnownOne, Depth);
792   if (NewVal == 0) return false;
793   U = NewVal;
794   return true;
795 }
796
797
798 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
799 /// value based on the demanded bits.  When this function is called, it is known
800 /// that only the bits set in DemandedMask of the result of V are ever used
801 /// downstream. Consequently, depending on the mask and V, it may be possible
802 /// to replace V with a constant or one of its operands. In such cases, this
803 /// function does the replacement and returns true. In all other cases, it
804 /// returns false after analyzing the expression and setting KnownOne and known
805 /// to be one in the expression.  KnownZero contains all the bits that are known
806 /// to be zero in the expression. These are provided to potentially allow the
807 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
808 /// the expression. KnownOne and KnownZero always follow the invariant that 
809 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
810 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
811 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
812 /// and KnownOne must all be the same.
813 ///
814 /// This returns null if it did not change anything and it permits no
815 /// simplification.  This returns V itself if it did some simplification of V's
816 /// operands based on the information about what bits are demanded. This returns
817 /// some other non-null value if it found out that V is equal to another value
818 /// in the context where the specified bits are demanded, but not for all users.
819 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
820                                              APInt &KnownZero, APInt &KnownOne,
821                                              unsigned Depth) {
822   assert(V != 0 && "Null pointer of Value???");
823   assert(Depth <= 6 && "Limit Search Depth");
824   uint32_t BitWidth = DemandedMask.getBitWidth();
825   const Type *VTy = V->getType();
826   assert((TD || !isa<PointerType>(VTy)) &&
827          "SimplifyDemandedBits needs to know bit widths!");
828   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
829          (!VTy->isIntOrIntVector() ||
830           VTy->getScalarSizeInBits() == BitWidth) &&
831          KnownZero.getBitWidth() == BitWidth &&
832          KnownOne.getBitWidth() == BitWidth &&
833          "Value *V, DemandedMask, KnownZero and KnownOne "
834          "must have same BitWidth");
835   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
836     // We know all of the bits for a constant!
837     KnownOne = CI->getValue() & DemandedMask;
838     KnownZero = ~KnownOne & DemandedMask;
839     return 0;
840   }
841   if (isa<ConstantPointerNull>(V)) {
842     // We know all of the bits for a constant!
843     KnownOne.clear();
844     KnownZero = DemandedMask;
845     return 0;
846   }
847
848   KnownZero.clear();
849   KnownOne.clear();
850   if (DemandedMask == 0) {   // Not demanding any bits from V.
851     if (isa<UndefValue>(V))
852       return 0;
853     return UndefValue::get(VTy);
854   }
855   
856   if (Depth == 6)        // Limit search depth.
857     return 0;
858   
859   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
860   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
861
862   Instruction *I = dyn_cast<Instruction>(V);
863   if (!I) {
864     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
865     return 0;        // Only analyze instructions.
866   }
867
868   // If there are multiple uses of this value and we aren't at the root, then
869   // we can't do any simplifications of the operands, because DemandedMask
870   // only reflects the bits demanded by *one* of the users.
871   if (Depth != 0 && !I->hasOneUse()) {
872     // Despite the fact that we can't simplify this instruction in all User's
873     // context, we can at least compute the knownzero/knownone bits, and we can
874     // do simplifications that apply to *just* the one user if we know that
875     // this instruction has a simpler value in that context.
876     if (I->getOpcode() == Instruction::And) {
877       // If either the LHS or the RHS are Zero, the result is zero.
878       ComputeMaskedBits(I->getOperand(1), DemandedMask,
879                         RHSKnownZero, RHSKnownOne, Depth+1);
880       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
881                         LHSKnownZero, LHSKnownOne, Depth+1);
882       
883       // If all of the demanded bits are known 1 on one side, return the other.
884       // These bits cannot contribute to the result of the 'and' in this
885       // context.
886       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
887           (DemandedMask & ~LHSKnownZero))
888         return I->getOperand(0);
889       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
890           (DemandedMask & ~RHSKnownZero))
891         return I->getOperand(1);
892       
893       // If all of the demanded bits in the inputs are known zeros, return zero.
894       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
895         return Constant::getNullValue(VTy);
896       
897     } else if (I->getOpcode() == Instruction::Or) {
898       // We can simplify (X|Y) -> X or Y in the user's context if we know that
899       // only bits from X or Y are demanded.
900       
901       // If either the LHS or the RHS are One, the result is One.
902       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
903                         RHSKnownZero, RHSKnownOne, Depth+1);
904       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
905                         LHSKnownZero, LHSKnownOne, Depth+1);
906       
907       // If all of the demanded bits are known zero on one side, return the
908       // other.  These bits cannot contribute to the result of the 'or' in this
909       // context.
910       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
911           (DemandedMask & ~LHSKnownOne))
912         return I->getOperand(0);
913       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
914           (DemandedMask & ~RHSKnownOne))
915         return I->getOperand(1);
916       
917       // If all of the potentially set bits on one side are known to be set on
918       // the other side, just use the 'other' side.
919       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
920           (DemandedMask & (~RHSKnownZero)))
921         return I->getOperand(0);
922       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
923           (DemandedMask & (~LHSKnownZero)))
924         return I->getOperand(1);
925     }
926     
927     // Compute the KnownZero/KnownOne bits to simplify things downstream.
928     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
929     return 0;
930   }
931   
932   // If this is the root being simplified, allow it to have multiple uses,
933   // just set the DemandedMask to all bits so that we can try to simplify the
934   // operands.  This allows visitTruncInst (for example) to simplify the
935   // operand of a trunc without duplicating all the logic below.
936   if (Depth == 0 && !V->hasOneUse())
937     DemandedMask = APInt::getAllOnesValue(BitWidth);
938   
939   switch (I->getOpcode()) {
940   default:
941     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
942     break;
943   case Instruction::And:
944     // If either the LHS or the RHS are Zero, the result is zero.
945     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
946                              RHSKnownZero, RHSKnownOne, Depth+1) ||
947         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
948                              LHSKnownZero, LHSKnownOne, Depth+1))
949       return I;
950     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
951     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
952
953     // If all of the demanded bits are known 1 on one side, return the other.
954     // These bits cannot contribute to the result of the 'and'.
955     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
956         (DemandedMask & ~LHSKnownZero))
957       return I->getOperand(0);
958     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
959         (DemandedMask & ~RHSKnownZero))
960       return I->getOperand(1);
961     
962     // If all of the demanded bits in the inputs are known zeros, return zero.
963     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
964       return Constant::getNullValue(VTy);
965       
966     // If the RHS is a constant, see if we can simplify it.
967     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
968       return I;
969       
970     // Output known-1 bits are only known if set in both the LHS & RHS.
971     RHSKnownOne &= LHSKnownOne;
972     // Output known-0 are known to be clear if zero in either the LHS | RHS.
973     RHSKnownZero |= LHSKnownZero;
974     break;
975   case Instruction::Or:
976     // If either the LHS or the RHS are One, the result is One.
977     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
978                              RHSKnownZero, RHSKnownOne, Depth+1) ||
979         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
980                              LHSKnownZero, LHSKnownOne, Depth+1))
981       return I;
982     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
983     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
984     
985     // If all of the demanded bits are known zero on one side, return the other.
986     // These bits cannot contribute to the result of the 'or'.
987     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
988         (DemandedMask & ~LHSKnownOne))
989       return I->getOperand(0);
990     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
991         (DemandedMask & ~RHSKnownOne))
992       return I->getOperand(1);
993
994     // If all of the potentially set bits on one side are known to be set on
995     // the other side, just use the 'other' side.
996     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
997         (DemandedMask & (~RHSKnownZero)))
998       return I->getOperand(0);
999     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
1000         (DemandedMask & (~LHSKnownZero)))
1001       return I->getOperand(1);
1002         
1003     // If the RHS is a constant, see if we can simplify it.
1004     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1005       return I;
1006           
1007     // Output known-0 bits are only known if clear in both the LHS & RHS.
1008     RHSKnownZero &= LHSKnownZero;
1009     // Output known-1 are known to be set if set in either the LHS | RHS.
1010     RHSKnownOne |= LHSKnownOne;
1011     break;
1012   case Instruction::Xor: {
1013     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1014                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1015         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1016                              LHSKnownZero, LHSKnownOne, Depth+1))
1017       return I;
1018     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1019     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1020     
1021     // If all of the demanded bits are known zero on one side, return the other.
1022     // These bits cannot contribute to the result of the 'xor'.
1023     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1024       return I->getOperand(0);
1025     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1026       return I->getOperand(1);
1027     
1028     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1029     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1030                          (RHSKnownOne & LHSKnownOne);
1031     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1032     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1033                         (RHSKnownOne & LHSKnownZero);
1034     
1035     // If all of the demanded bits are known to be zero on one side or the
1036     // other, turn this into an *inclusive* or.
1037     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1038     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1039       Instruction *Or = 
1040         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1041                                  I->getName());
1042       return InsertNewInstBefore(Or, *I);
1043     }
1044     
1045     // If all of the demanded bits on one side are known, and all of the set
1046     // bits on that side are also known to be set on the other side, turn this
1047     // into an AND, as we know the bits will be cleared.
1048     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1049     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1050       // all known
1051       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1052         Constant *AndC = Constant::getIntegerValue(VTy,
1053                                                    ~RHSKnownOne & DemandedMask);
1054         Instruction *And = 
1055           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1056         return InsertNewInstBefore(And, *I);
1057       }
1058     }
1059     
1060     // If the RHS is a constant, see if we can simplify it.
1061     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1062     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1063       return I;
1064     
1065     // If our LHS is an 'and' and if it has one use, and if any of the bits we
1066     // are flipping are known to be set, then the xor is just resetting those
1067     // bits to zero.  We can just knock out bits from the 'and' and the 'xor',
1068     // simplifying both of them.
1069     if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1070       if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1071           isa<ConstantInt>(I->getOperand(1)) &&
1072           isa<ConstantInt>(LHSInst->getOperand(1)) &&
1073           (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1074         ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1075         ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1076         APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1077         
1078         Constant *AndC =
1079           ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1080         Instruction *NewAnd = 
1081           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1082         InsertNewInstBefore(NewAnd, *I);
1083         
1084         Constant *XorC =
1085           ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1086         Instruction *NewXor =
1087           BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1088         return InsertNewInstBefore(NewXor, *I);
1089       }
1090           
1091           
1092     RHSKnownZero = KnownZeroOut;
1093     RHSKnownOne  = KnownOneOut;
1094     break;
1095   }
1096   case Instruction::Select:
1097     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1098                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1099         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1100                              LHSKnownZero, LHSKnownOne, Depth+1))
1101       return I;
1102     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1103     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1104     
1105     // If the operands are constants, see if we can simplify them.
1106     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1107         ShrinkDemandedConstant(I, 2, DemandedMask))
1108       return I;
1109     
1110     // Only known if known in both the LHS and RHS.
1111     RHSKnownOne &= LHSKnownOne;
1112     RHSKnownZero &= LHSKnownZero;
1113     break;
1114   case Instruction::Trunc: {
1115     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1116     DemandedMask.zext(truncBf);
1117     RHSKnownZero.zext(truncBf);
1118     RHSKnownOne.zext(truncBf);
1119     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1120                              RHSKnownZero, RHSKnownOne, Depth+1))
1121       return I;
1122     DemandedMask.trunc(BitWidth);
1123     RHSKnownZero.trunc(BitWidth);
1124     RHSKnownOne.trunc(BitWidth);
1125     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1126     break;
1127   }
1128   case Instruction::BitCast:
1129     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1130       return false;  // vector->int or fp->int?
1131
1132     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1133       if (const VectorType *SrcVTy =
1134             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1135         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1136           // Don't touch a bitcast between vectors of different element counts.
1137           return false;
1138       } else
1139         // Don't touch a scalar-to-vector bitcast.
1140         return false;
1141     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1142       // Don't touch a vector-to-scalar bitcast.
1143       return false;
1144
1145     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1146                              RHSKnownZero, RHSKnownOne, Depth+1))
1147       return I;
1148     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1149     break;
1150   case Instruction::ZExt: {
1151     // Compute the bits in the result that are not present in the input.
1152     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1153     
1154     DemandedMask.trunc(SrcBitWidth);
1155     RHSKnownZero.trunc(SrcBitWidth);
1156     RHSKnownOne.trunc(SrcBitWidth);
1157     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1158                              RHSKnownZero, RHSKnownOne, Depth+1))
1159       return I;
1160     DemandedMask.zext(BitWidth);
1161     RHSKnownZero.zext(BitWidth);
1162     RHSKnownOne.zext(BitWidth);
1163     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1164     // The top bits are known to be zero.
1165     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1166     break;
1167   }
1168   case Instruction::SExt: {
1169     // Compute the bits in the result that are not present in the input.
1170     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1171     
1172     APInt InputDemandedBits = DemandedMask & 
1173                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1174
1175     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1176     // If any of the sign extended bits are demanded, we know that the sign
1177     // bit is demanded.
1178     if ((NewBits & DemandedMask) != 0)
1179       InputDemandedBits.set(SrcBitWidth-1);
1180       
1181     InputDemandedBits.trunc(SrcBitWidth);
1182     RHSKnownZero.trunc(SrcBitWidth);
1183     RHSKnownOne.trunc(SrcBitWidth);
1184     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1185                              RHSKnownZero, RHSKnownOne, Depth+1))
1186       return I;
1187     InputDemandedBits.zext(BitWidth);
1188     RHSKnownZero.zext(BitWidth);
1189     RHSKnownOne.zext(BitWidth);
1190     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1191       
1192     // If the sign bit of the input is known set or clear, then we know the
1193     // top bits of the result.
1194
1195     // If the input sign bit is known zero, or if the NewBits are not demanded
1196     // convert this into a zero extension.
1197     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1198       // Convert to ZExt cast
1199       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1200       return InsertNewInstBefore(NewCast, *I);
1201     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1202       RHSKnownOne |= NewBits;
1203     }
1204     break;
1205   }
1206   case Instruction::Add: {
1207     // Figure out what the input bits are.  If the top bits of the and result
1208     // are not demanded, then the add doesn't demand them from its input
1209     // either.
1210     unsigned NLZ = DemandedMask.countLeadingZeros();
1211       
1212     // If there is a constant on the RHS, there are a variety of xformations
1213     // we can do.
1214     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1215       // If null, this should be simplified elsewhere.  Some of the xforms here
1216       // won't work if the RHS is zero.
1217       if (RHS->isZero())
1218         break;
1219       
1220       // If the top bit of the output is demanded, demand everything from the
1221       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1222       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1223
1224       // Find information about known zero/one bits in the input.
1225       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1226                                LHSKnownZero, LHSKnownOne, Depth+1))
1227         return I;
1228
1229       // If the RHS of the add has bits set that can't affect the input, reduce
1230       // the constant.
1231       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1232         return I;
1233       
1234       // Avoid excess work.
1235       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1236         break;
1237       
1238       // Turn it into OR if input bits are zero.
1239       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1240         Instruction *Or =
1241           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1242                                    I->getName());
1243         return InsertNewInstBefore(Or, *I);
1244       }
1245       
1246       // We can say something about the output known-zero and known-one bits,
1247       // depending on potential carries from the input constant and the
1248       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1249       // bits set and the RHS constant is 0x01001, then we know we have a known
1250       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1251       
1252       // To compute this, we first compute the potential carry bits.  These are
1253       // the bits which may be modified.  I'm not aware of a better way to do
1254       // this scan.
1255       const APInt &RHSVal = RHS->getValue();
1256       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1257       
1258       // Now that we know which bits have carries, compute the known-1/0 sets.
1259       
1260       // Bits are known one if they are known zero in one operand and one in the
1261       // other, and there is no input carry.
1262       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1263                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1264       
1265       // Bits are known zero if they are known zero in both operands and there
1266       // is no input carry.
1267       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1268     } else {
1269       // If the high-bits of this ADD are not demanded, then it does not demand
1270       // the high bits of its LHS or RHS.
1271       if (DemandedMask[BitWidth-1] == 0) {
1272         // Right fill the mask of bits for this ADD to demand the most
1273         // significant bit and all those below it.
1274         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1275         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1276                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1277             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1278                                  LHSKnownZero, LHSKnownOne, Depth+1))
1279           return I;
1280       }
1281     }
1282     break;
1283   }
1284   case Instruction::Sub:
1285     // If the high-bits of this SUB are not demanded, then it does not demand
1286     // the high bits of its LHS or RHS.
1287     if (DemandedMask[BitWidth-1] == 0) {
1288       // Right fill the mask of bits for this SUB to demand the most
1289       // significant bit and all those below it.
1290       uint32_t NLZ = DemandedMask.countLeadingZeros();
1291       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1292       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1293                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1294           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1295                                LHSKnownZero, LHSKnownOne, Depth+1))
1296         return I;
1297     }
1298     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1299     // the known zeros and ones.
1300     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1301     break;
1302   case Instruction::Shl:
1303     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1304       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1305       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1306       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1307                                RHSKnownZero, RHSKnownOne, Depth+1))
1308         return I;
1309       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1310       RHSKnownZero <<= ShiftAmt;
1311       RHSKnownOne  <<= ShiftAmt;
1312       // low bits known zero.
1313       if (ShiftAmt)
1314         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1315     }
1316     break;
1317   case Instruction::LShr:
1318     // For a logical shift right
1319     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1320       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1321       
1322       // Unsigned shift right.
1323       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1324       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1325                                RHSKnownZero, RHSKnownOne, Depth+1))
1326         return I;
1327       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1328       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1329       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1330       if (ShiftAmt) {
1331         // Compute the new bits that are at the top now.
1332         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1333         RHSKnownZero |= HighBits;  // high bits known zero.
1334       }
1335     }
1336     break;
1337   case Instruction::AShr:
1338     // If this is an arithmetic shift right and only the low-bit is set, we can
1339     // always convert this into a logical shr, even if the shift amount is
1340     // variable.  The low bit of the shift cannot be an input sign bit unless
1341     // the shift amount is >= the size of the datatype, which is undefined.
1342     if (DemandedMask == 1) {
1343       // Perform the logical shift right.
1344       Instruction *NewVal = BinaryOperator::CreateLShr(
1345                         I->getOperand(0), I->getOperand(1), I->getName());
1346       return InsertNewInstBefore(NewVal, *I);
1347     }    
1348
1349     // If the sign bit is the only bit demanded by this ashr, then there is no
1350     // need to do it, the shift doesn't change the high bit.
1351     if (DemandedMask.isSignBit())
1352       return I->getOperand(0);
1353     
1354     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1355       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1356       
1357       // Signed shift right.
1358       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1359       // If any of the "high bits" are demanded, we should set the sign bit as
1360       // demanded.
1361       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1362         DemandedMaskIn.set(BitWidth-1);
1363       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1364                                RHSKnownZero, RHSKnownOne, Depth+1))
1365         return I;
1366       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1367       // Compute the new bits that are at the top now.
1368       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1369       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1370       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1371         
1372       // Handle the sign bits.
1373       APInt SignBit(APInt::getSignBit(BitWidth));
1374       // Adjust to where it is now in the mask.
1375       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1376         
1377       // If the input sign bit is known to be zero, or if none of the top bits
1378       // are demanded, turn this into an unsigned shift right.
1379       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1380           (HighBits & ~DemandedMask) == HighBits) {
1381         // Perform the logical shift right.
1382         Instruction *NewVal = BinaryOperator::CreateLShr(
1383                           I->getOperand(0), SA, I->getName());
1384         return InsertNewInstBefore(NewVal, *I);
1385       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1386         RHSKnownOne |= HighBits;
1387       }
1388     }
1389     break;
1390   case Instruction::SRem:
1391     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1392       APInt RA = Rem->getValue().abs();
1393       if (RA.isPowerOf2()) {
1394         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1395           return I->getOperand(0);
1396
1397         APInt LowBits = RA - 1;
1398         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1399         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1400                                  LHSKnownZero, LHSKnownOne, Depth+1))
1401           return I;
1402
1403         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1404           LHSKnownZero |= ~LowBits;
1405
1406         KnownZero |= LHSKnownZero & DemandedMask;
1407
1408         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1409       }
1410     }
1411     break;
1412   case Instruction::URem: {
1413     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1414     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1415     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1416                              KnownZero2, KnownOne2, Depth+1) ||
1417         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1418                              KnownZero2, KnownOne2, Depth+1))
1419       return I;
1420
1421     unsigned Leaders = KnownZero2.countLeadingOnes();
1422     Leaders = std::max(Leaders,
1423                        KnownZero2.countLeadingOnes());
1424     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1425     break;
1426   }
1427   case Instruction::Call:
1428     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1429       switch (II->getIntrinsicID()) {
1430       default: break;
1431       case Intrinsic::bswap: {
1432         // If the only bits demanded come from one byte of the bswap result,
1433         // just shift the input byte into position to eliminate the bswap.
1434         unsigned NLZ = DemandedMask.countLeadingZeros();
1435         unsigned NTZ = DemandedMask.countTrailingZeros();
1436           
1437         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1438         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1439         // have 14 leading zeros, round to 8.
1440         NLZ &= ~7;
1441         NTZ &= ~7;
1442         // If we need exactly one byte, we can do this transformation.
1443         if (BitWidth-NLZ-NTZ == 8) {
1444           unsigned ResultBit = NTZ;
1445           unsigned InputBit = BitWidth-NTZ-8;
1446           
1447           // Replace this with either a left or right shift to get the byte into
1448           // the right place.
1449           Instruction *NewVal;
1450           if (InputBit > ResultBit)
1451             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1452                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1453           else
1454             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1455                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1456           NewVal->takeName(I);
1457           return InsertNewInstBefore(NewVal, *I);
1458         }
1459           
1460         // TODO: Could compute known zero/one bits based on the input.
1461         break;
1462       }
1463       }
1464     }
1465     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1466     break;
1467   }
1468   
1469   // If the client is only demanding bits that we know, return the known
1470   // constant.
1471   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1472     return Constant::getIntegerValue(VTy, RHSKnownOne);
1473   return false;
1474 }
1475
1476
1477 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1478 /// any number of elements. DemandedElts contains the set of elements that are
1479 /// actually used by the caller.  This method analyzes which elements of the
1480 /// operand are undef and returns that information in UndefElts.
1481 ///
1482 /// If the information about demanded elements can be used to simplify the
1483 /// operation, the operation is simplified, then the resultant value is
1484 /// returned.  This returns null if no change was made.
1485 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1486                                                 APInt& UndefElts,
1487                                                 unsigned Depth) {
1488   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1489   APInt EltMask(APInt::getAllOnesValue(VWidth));
1490   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1491
1492   if (isa<UndefValue>(V)) {
1493     // If the entire vector is undefined, just return this info.
1494     UndefElts = EltMask;
1495     return 0;
1496   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1497     UndefElts = EltMask;
1498     return UndefValue::get(V->getType());
1499   }
1500
1501   UndefElts = 0;
1502   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1503     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1504     Constant *Undef = UndefValue::get(EltTy);
1505
1506     std::vector<Constant*> Elts;
1507     for (unsigned i = 0; i != VWidth; ++i)
1508       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1509         Elts.push_back(Undef);
1510         UndefElts.set(i);
1511       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1512         Elts.push_back(Undef);
1513         UndefElts.set(i);
1514       } else {                               // Otherwise, defined.
1515         Elts.push_back(CP->getOperand(i));
1516       }
1517
1518     // If we changed the constant, return it.
1519     Constant *NewCP = ConstantVector::get(Elts);
1520     return NewCP != CP ? NewCP : 0;
1521   } else if (isa<ConstantAggregateZero>(V)) {
1522     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1523     // set to undef.
1524     
1525     // Check if this is identity. If so, return 0 since we are not simplifying
1526     // anything.
1527     if (DemandedElts == ((1ULL << VWidth) -1))
1528       return 0;
1529     
1530     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1531     Constant *Zero = Constant::getNullValue(EltTy);
1532     Constant *Undef = UndefValue::get(EltTy);
1533     std::vector<Constant*> Elts;
1534     for (unsigned i = 0; i != VWidth; ++i) {
1535       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1536       Elts.push_back(Elt);
1537     }
1538     UndefElts = DemandedElts ^ EltMask;
1539     return ConstantVector::get(Elts);
1540   }
1541   
1542   // Limit search depth.
1543   if (Depth == 10)
1544     return 0;
1545
1546   // If multiple users are using the root value, procede with
1547   // simplification conservatively assuming that all elements
1548   // are needed.
1549   if (!V->hasOneUse()) {
1550     // Quit if we find multiple users of a non-root value though.
1551     // They'll be handled when it's their turn to be visited by
1552     // the main instcombine process.
1553     if (Depth != 0)
1554       // TODO: Just compute the UndefElts information recursively.
1555       return 0;
1556
1557     // Conservatively assume that all elements are needed.
1558     DemandedElts = EltMask;
1559   }
1560   
1561   Instruction *I = dyn_cast<Instruction>(V);
1562   if (!I) return 0;        // Only analyze instructions.
1563   
1564   bool MadeChange = false;
1565   APInt UndefElts2(VWidth, 0);
1566   Value *TmpV;
1567   switch (I->getOpcode()) {
1568   default: break;
1569     
1570   case Instruction::InsertElement: {
1571     // If this is a variable index, we don't know which element it overwrites.
1572     // demand exactly the same input as we produce.
1573     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1574     if (Idx == 0) {
1575       // Note that we can't propagate undef elt info, because we don't know
1576       // which elt is getting updated.
1577       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1578                                         UndefElts2, Depth+1);
1579       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1580       break;
1581     }
1582     
1583     // If this is inserting an element that isn't demanded, remove this
1584     // insertelement.
1585     unsigned IdxNo = Idx->getZExtValue();
1586     if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1587       Worklist.Add(I);
1588       return I->getOperand(0);
1589     }
1590     
1591     // Otherwise, the element inserted overwrites whatever was there, so the
1592     // input demanded set is simpler than the output set.
1593     APInt DemandedElts2 = DemandedElts;
1594     DemandedElts2.clear(IdxNo);
1595     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1596                                       UndefElts, Depth+1);
1597     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1598
1599     // The inserted element is defined.
1600     UndefElts.clear(IdxNo);
1601     break;
1602   }
1603   case Instruction::ShuffleVector: {
1604     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1605     uint64_t LHSVWidth =
1606       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1607     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1608     for (unsigned i = 0; i < VWidth; i++) {
1609       if (DemandedElts[i]) {
1610         unsigned MaskVal = Shuffle->getMaskValue(i);
1611         if (MaskVal != -1u) {
1612           assert(MaskVal < LHSVWidth * 2 &&
1613                  "shufflevector mask index out of range!");
1614           if (MaskVal < LHSVWidth)
1615             LeftDemanded.set(MaskVal);
1616           else
1617             RightDemanded.set(MaskVal - LHSVWidth);
1618         }
1619       }
1620     }
1621
1622     APInt UndefElts4(LHSVWidth, 0);
1623     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1624                                       UndefElts4, Depth+1);
1625     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1626
1627     APInt UndefElts3(LHSVWidth, 0);
1628     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1629                                       UndefElts3, Depth+1);
1630     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1631
1632     bool NewUndefElts = false;
1633     for (unsigned i = 0; i < VWidth; i++) {
1634       unsigned MaskVal = Shuffle->getMaskValue(i);
1635       if (MaskVal == -1u) {
1636         UndefElts.set(i);
1637       } else if (MaskVal < LHSVWidth) {
1638         if (UndefElts4[MaskVal]) {
1639           NewUndefElts = true;
1640           UndefElts.set(i);
1641         }
1642       } else {
1643         if (UndefElts3[MaskVal - LHSVWidth]) {
1644           NewUndefElts = true;
1645           UndefElts.set(i);
1646         }
1647       }
1648     }
1649
1650     if (NewUndefElts) {
1651       // Add additional discovered undefs.
1652       std::vector<Constant*> Elts;
1653       for (unsigned i = 0; i < VWidth; ++i) {
1654         if (UndefElts[i])
1655           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
1656         else
1657           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
1658                                           Shuffle->getMaskValue(i)));
1659       }
1660       I->setOperand(2, ConstantVector::get(Elts));
1661       MadeChange = true;
1662     }
1663     break;
1664   }
1665   case Instruction::BitCast: {
1666     // Vector->vector casts only.
1667     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1668     if (!VTy) break;
1669     unsigned InVWidth = VTy->getNumElements();
1670     APInt InputDemandedElts(InVWidth, 0);
1671     unsigned Ratio;
1672
1673     if (VWidth == InVWidth) {
1674       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1675       // elements as are demanded of us.
1676       Ratio = 1;
1677       InputDemandedElts = DemandedElts;
1678     } else if (VWidth > InVWidth) {
1679       // Untested so far.
1680       break;
1681       
1682       // If there are more elements in the result than there are in the source,
1683       // then an input element is live if any of the corresponding output
1684       // elements are live.
1685       Ratio = VWidth/InVWidth;
1686       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1687         if (DemandedElts[OutIdx])
1688           InputDemandedElts.set(OutIdx/Ratio);
1689       }
1690     } else {
1691       // Untested so far.
1692       break;
1693       
1694       // If there are more elements in the source than there are in the result,
1695       // then an input element is live if the corresponding output element is
1696       // live.
1697       Ratio = InVWidth/VWidth;
1698       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1699         if (DemandedElts[InIdx/Ratio])
1700           InputDemandedElts.set(InIdx);
1701     }
1702     
1703     // div/rem demand all inputs, because they don't want divide by zero.
1704     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1705                                       UndefElts2, Depth+1);
1706     if (TmpV) {
1707       I->setOperand(0, TmpV);
1708       MadeChange = true;
1709     }
1710     
1711     UndefElts = UndefElts2;
1712     if (VWidth > InVWidth) {
1713       llvm_unreachable("Unimp");
1714       // If there are more elements in the result than there are in the source,
1715       // then an output element is undef if the corresponding input element is
1716       // undef.
1717       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1718         if (UndefElts2[OutIdx/Ratio])
1719           UndefElts.set(OutIdx);
1720     } else if (VWidth < InVWidth) {
1721       llvm_unreachable("Unimp");
1722       // If there are more elements in the source than there are in the result,
1723       // then a result element is undef if all of the corresponding input
1724       // elements are undef.
1725       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1726       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1727         if (!UndefElts2[InIdx])            // Not undef?
1728           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1729     }
1730     break;
1731   }
1732   case Instruction::And:
1733   case Instruction::Or:
1734   case Instruction::Xor:
1735   case Instruction::Add:
1736   case Instruction::Sub:
1737   case Instruction::Mul:
1738     // div/rem demand all inputs, because they don't want divide by zero.
1739     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1740                                       UndefElts, Depth+1);
1741     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1742     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1743                                       UndefElts2, Depth+1);
1744     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1745       
1746     // Output elements are undefined if both are undefined.  Consider things
1747     // like undef&0.  The result is known zero, not undef.
1748     UndefElts &= UndefElts2;
1749     break;
1750     
1751   case Instruction::Call: {
1752     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1753     if (!II) break;
1754     switch (II->getIntrinsicID()) {
1755     default: break;
1756       
1757     // Binary vector operations that work column-wise.  A dest element is a
1758     // function of the corresponding input elements from the two inputs.
1759     case Intrinsic::x86_sse_sub_ss:
1760     case Intrinsic::x86_sse_mul_ss:
1761     case Intrinsic::x86_sse_min_ss:
1762     case Intrinsic::x86_sse_max_ss:
1763     case Intrinsic::x86_sse2_sub_sd:
1764     case Intrinsic::x86_sse2_mul_sd:
1765     case Intrinsic::x86_sse2_min_sd:
1766     case Intrinsic::x86_sse2_max_sd:
1767       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1768                                         UndefElts, Depth+1);
1769       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1770       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1771                                         UndefElts2, Depth+1);
1772       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1773
1774       // If only the low elt is demanded and this is a scalarizable intrinsic,
1775       // scalarize it now.
1776       if (DemandedElts == 1) {
1777         switch (II->getIntrinsicID()) {
1778         default: break;
1779         case Intrinsic::x86_sse_sub_ss:
1780         case Intrinsic::x86_sse_mul_ss:
1781         case Intrinsic::x86_sse2_sub_sd:
1782         case Intrinsic::x86_sse2_mul_sd:
1783           // TODO: Lower MIN/MAX/ABS/etc
1784           Value *LHS = II->getOperand(1);
1785           Value *RHS = II->getOperand(2);
1786           // Extract the element as scalars.
1787           LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS, 
1788             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1789           RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1790             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1791           
1792           switch (II->getIntrinsicID()) {
1793           default: llvm_unreachable("Case stmts out of sync!");
1794           case Intrinsic::x86_sse_sub_ss:
1795           case Intrinsic::x86_sse2_sub_sd:
1796             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1797                                                         II->getName()), *II);
1798             break;
1799           case Intrinsic::x86_sse_mul_ss:
1800           case Intrinsic::x86_sse2_mul_sd:
1801             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1802                                                          II->getName()), *II);
1803             break;
1804           }
1805           
1806           Instruction *New =
1807             InsertElementInst::Create(
1808               UndefValue::get(II->getType()), TmpV,
1809               ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
1810           InsertNewInstBefore(New, *II);
1811           return New;
1812         }            
1813       }
1814         
1815       // Output elements are undefined if both are undefined.  Consider things
1816       // like undef&0.  The result is known zero, not undef.
1817       UndefElts &= UndefElts2;
1818       break;
1819     }
1820     break;
1821   }
1822   }
1823   return MadeChange ? I : 0;
1824 }
1825
1826
1827 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1828 /// function is designed to check a chain of associative operators for a
1829 /// potential to apply a certain optimization.  Since the optimization may be
1830 /// applicable if the expression was reassociated, this checks the chain, then
1831 /// reassociates the expression as necessary to expose the optimization
1832 /// opportunity.  This makes use of a special Functor, which must define
1833 /// 'shouldApply' and 'apply' methods.
1834 ///
1835 template<typename Functor>
1836 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1837   unsigned Opcode = Root.getOpcode();
1838   Value *LHS = Root.getOperand(0);
1839
1840   // Quick check, see if the immediate LHS matches...
1841   if (F.shouldApply(LHS))
1842     return F.apply(Root);
1843
1844   // Otherwise, if the LHS is not of the same opcode as the root, return.
1845   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1846   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1847     // Should we apply this transform to the RHS?
1848     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1849
1850     // If not to the RHS, check to see if we should apply to the LHS...
1851     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1852       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1853       ShouldApply = true;
1854     }
1855
1856     // If the functor wants to apply the optimization to the RHS of LHSI,
1857     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1858     if (ShouldApply) {
1859       // Now all of the instructions are in the current basic block, go ahead
1860       // and perform the reassociation.
1861       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1862
1863       // First move the selected RHS to the LHS of the root...
1864       Root.setOperand(0, LHSI->getOperand(1));
1865
1866       // Make what used to be the LHS of the root be the user of the root...
1867       Value *ExtraOperand = TmpLHSI->getOperand(1);
1868       if (&Root == TmpLHSI) {
1869         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1870         return 0;
1871       }
1872       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1873       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1874       BasicBlock::iterator ARI = &Root; ++ARI;
1875       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1876       ARI = Root;
1877
1878       // Now propagate the ExtraOperand down the chain of instructions until we
1879       // get to LHSI.
1880       while (TmpLHSI != LHSI) {
1881         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1882         // Move the instruction to immediately before the chain we are
1883         // constructing to avoid breaking dominance properties.
1884         NextLHSI->moveBefore(ARI);
1885         ARI = NextLHSI;
1886
1887         Value *NextOp = NextLHSI->getOperand(1);
1888         NextLHSI->setOperand(1, ExtraOperand);
1889         TmpLHSI = NextLHSI;
1890         ExtraOperand = NextOp;
1891       }
1892
1893       // Now that the instructions are reassociated, have the functor perform
1894       // the transformation...
1895       return F.apply(Root);
1896     }
1897
1898     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1899   }
1900   return 0;
1901 }
1902
1903 namespace {
1904
1905 // AddRHS - Implements: X + X --> X << 1
1906 struct AddRHS {
1907   Value *RHS;
1908   explicit AddRHS(Value *rhs) : RHS(rhs) {}
1909   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1910   Instruction *apply(BinaryOperator &Add) const {
1911     return BinaryOperator::CreateShl(Add.getOperand(0),
1912                                      ConstantInt::get(Add.getType(), 1));
1913   }
1914 };
1915
1916 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1917 //                 iff C1&C2 == 0
1918 struct AddMaskingAnd {
1919   Constant *C2;
1920   explicit AddMaskingAnd(Constant *c) : C2(c) {}
1921   bool shouldApply(Value *LHS) const {
1922     ConstantInt *C1;
1923     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1924            ConstantExpr::getAnd(C1, C2)->isNullValue();
1925   }
1926   Instruction *apply(BinaryOperator &Add) const {
1927     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1928   }
1929 };
1930
1931 }
1932
1933 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1934                                              InstCombiner *IC) {
1935   if (CastInst *CI = dyn_cast<CastInst>(&I))
1936     return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
1937
1938   // Figure out if the constant is the left or the right argument.
1939   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1940   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1941
1942   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1943     if (ConstIsRHS)
1944       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1945     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1946   }
1947
1948   Value *Op0 = SO, *Op1 = ConstOperand;
1949   if (!ConstIsRHS)
1950     std::swap(Op0, Op1);
1951   
1952   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1953     return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1954                                     SO->getName()+".op");
1955   if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1956     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1957                                    SO->getName()+".cmp");
1958   if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1959     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1960                                    SO->getName()+".cmp");
1961   llvm_unreachable("Unknown binary instruction type!");
1962 }
1963
1964 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1965 // constant as the other operand, try to fold the binary operator into the
1966 // select arguments.  This also works for Cast instructions, which obviously do
1967 // not have a second operand.
1968 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1969                                      InstCombiner *IC) {
1970   // Don't modify shared select instructions
1971   if (!SI->hasOneUse()) return 0;
1972   Value *TV = SI->getOperand(1);
1973   Value *FV = SI->getOperand(2);
1974
1975   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1976     // Bool selects with constant operands can be folded to logical ops.
1977     if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
1978
1979     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1980     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1981
1982     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1983                               SelectFalseVal);
1984   }
1985   return 0;
1986 }
1987
1988 // Check whether all the operands of the PHI dominate the PHI node,
1989 // knowing that the PHI's operands either dominate BB, or are defined in the BB.
1990 static bool checkPHI(PHINode *PN, BasicBlock *BB)
1991 {
1992   BasicBlock *phiBB = PN->getParent();
1993   for (unsigned i=0;i<PN->getNumIncomingValues();i++) {
1994     Instruction *I = dyn_cast<Instruction>(PN->getIncomingValue(i));
1995     if (!I)
1996       continue;
1997     BasicBlock *pBB = I->getParent();
1998     if (pBB == BB) {
1999       // another PHI in same BB is always before PN (PN is last phi).
2000       if (isa<PHINode>(I))
2001         continue;
2002       // An instruction in the same BB, and not a phi, this is after PN.
2003       return false;
2004     }
2005     if (phiBB == BB)
2006       continue;
2007     // We don't have dominator info, so just check that the instruction
2008     // is not defined in on of the BB on the unique path between BB and phiBB.
2009     // If there is no such unique path, or pBB equals to one of the BBs on that
2010     // path we know that this operand doesn't dominate the PHI node.
2011     BasicBlock *B = PN->getIncomingBlock(i);
2012     while ((B = B->getUniquePredecessor())) {
2013       if (pBB == B)
2014         return false;
2015       if (B == phiBB)
2016         break;
2017     }
2018     // No unique path -> doesn't dominate
2019     if (!B)
2020       return false;
2021   }
2022   return true;
2023 }
2024
2025 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
2026 /// has a PHI node as operand #0, see if we can fold the instruction into the
2027 /// PHI (which is only possible if all operands to the PHI are constants).
2028 ///
2029 /// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
2030 /// that would normally be unprofitable because they strongly encourage jump
2031 /// threading.
2032 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
2033                                          bool AllowAggressive) {
2034   AllowAggressive = false;
2035   PHINode *PN = cast<PHINode>(I.getOperand(0));
2036   unsigned NumPHIValues = PN->getNumIncomingValues();
2037   if (NumPHIValues == 0 ||
2038       // We normally only transform phis with a single use, unless we're trying
2039       // hard to make jump threading happen.
2040       (!PN->hasOneUse() && !AllowAggressive))
2041     return 0;
2042   
2043   
2044   // Check to see if all of the operands of the PHI are simple constants
2045   // (constantint/constantfp/undef).  If there is one non-constant value,
2046   // remember the BB it is in.  If there is more than one or if *it* is a PHI,
2047   // bail out.  We don't do arbitrary constant expressions here because moving
2048   // their computation can be expensive without a cost model.
2049   BasicBlock *NonConstBB = 0;
2050   for (unsigned i = 0; i != NumPHIValues; ++i)
2051     if (!isa<Constant>(PN->getIncomingValue(i)) ||
2052         isa<ConstantExpr>(PN->getIncomingValue(i))) {
2053       if (NonConstBB) return 0;  // More than one non-const value.
2054       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
2055       NonConstBB = PN->getIncomingBlock(i);
2056       
2057       // If the incoming non-constant value is in I's block, we have an infinite
2058       // loop.
2059       if (NonConstBB == I.getParent())
2060         return 0;
2061     }
2062   
2063   // If there is exactly one non-constant value, we can insert a copy of the
2064   // operation in that block.  However, if this is a critical edge, we would be
2065   // inserting the computation one some other paths (e.g. inside a loop).  Only
2066   // do this if the pred block is unconditionally branching into the phi block.
2067   if (NonConstBB != 0 && !AllowAggressive) {
2068     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2069     if (!BI || !BI->isUnconditional()) return 0;
2070   }
2071
2072   // Okay, we can do the transformation: create the new PHI node.
2073   PHINode *NewPN = PHINode::Create(I.getType(), "");
2074   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2075   // We must the PHI node as the last PHI, because it may use one of the other
2076   // PHIs.
2077   BasicBlock::iterator BBIt = PN;
2078   while (isa<PHINode>(BBIt)) ++BBIt;
2079   InsertNewInstBefore(NewPN, *BBIt);
2080
2081   SmallVector<Instruction*, 2> tmpWorklist;
2082   // Next, add all of the operands to the PHI.
2083   if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2084     // We only currently try to fold the condition of a select when it is a phi,
2085     // not the true/false values.
2086     Value *TrueV = SI->getTrueValue();
2087     Value *FalseV = SI->getFalseValue();
2088     BasicBlock *PhiTransBB = PN->getParent();
2089     for (unsigned i = 0; i != NumPHIValues; ++i) {
2090       BasicBlock *ThisBB = PN->getIncomingBlock(i);
2091       Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2092       Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
2093       Value *InV = 0;
2094       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2095         InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
2096       } else {
2097         assert(PN->getIncomingBlock(i) == NonConstBB);
2098         InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2099                                  FalseVInPred,
2100                                  "phitmp", NonConstBB->getTerminator());
2101         tmpWorklist.push_back(cast<Instruction>(InV));
2102       }
2103       NewPN->addIncoming(InV, ThisBB);
2104     }
2105   } else if (I.getNumOperands() == 2) {
2106     Constant *C = cast<Constant>(I.getOperand(1));
2107     for (unsigned i = 0; i != NumPHIValues; ++i) {
2108       Value *InV = 0;
2109       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2110         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2111           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2112         else
2113           InV = ConstantExpr::get(I.getOpcode(), InC, C);
2114       } else {
2115         assert(PN->getIncomingBlock(i) == NonConstBB);
2116         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
2117           InV = BinaryOperator::Create(BO->getOpcode(),
2118                                        PN->getIncomingValue(i), C, "phitmp",
2119                                        NonConstBB->getTerminator());
2120         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2121           InV = CmpInst::Create(CI->getOpcode(),
2122                                 CI->getPredicate(),
2123                                 PN->getIncomingValue(i), C, "phitmp",
2124                                 NonConstBB->getTerminator());
2125         else
2126           llvm_unreachable("Unknown binop!");
2127         tmpWorklist.push_back(cast<Instruction>(InV));
2128       }
2129       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2130     }
2131   } else { 
2132     CastInst *CI = cast<CastInst>(&I);
2133     const Type *RetTy = CI->getType();
2134     for (unsigned i = 0; i != NumPHIValues; ++i) {
2135       Value *InV;
2136       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2137         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2138       } else {
2139         assert(PN->getIncomingBlock(i) == NonConstBB);
2140         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2141                                I.getType(), "phitmp", 
2142                                NonConstBB->getTerminator());
2143         tmpWorklist.push_back(cast<Instruction>(InV));
2144       }
2145       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2146     }
2147   }
2148   // The PHI's operands must dominate the PHI, if we can't prove that
2149   // undo this transformation.
2150   if (!checkPHI(NewPN, I.getParent())) {
2151     Worklist.Remove(NewPN);
2152     NewPN->eraseFromParent();
2153     while (!tmpWorklist.empty()) {
2154       tmpWorklist.pop_back_val()->eraseFromParent();
2155     }
2156     return 0;
2157   }
2158   while (!tmpWorklist.empty()) {
2159     Worklist.Add(tmpWorklist.pop_back_val());
2160   }
2161   NewPN->takeName(PN);
2162   Worklist.Add(PN);
2163   return ReplaceInstUsesWith(I, NewPN);
2164 }
2165
2166
2167 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2168 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2169 /// This basically requires proving that the add in the original type would not
2170 /// overflow to change the sign bit or have a carry out.
2171 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2172   // There are different heuristics we can use for this.  Here are some simple
2173   // ones.
2174   
2175   // Add has the property that adding any two 2's complement numbers can only 
2176   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2177   // have at least two sign bits, we know that the addition of the two values will
2178   // sign extend fine.
2179   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2180     return true;
2181   
2182   
2183   // If one of the operands only has one non-zero bit, and if the other operand
2184   // has a known-zero bit in a more significant place than it (not including the
2185   // sign bit) the ripple may go up to and fill the zero, but won't change the
2186   // sign.  For example, (X & ~4) + 1.
2187   
2188   // TODO: Implement.
2189   
2190   return false;
2191 }
2192
2193
2194 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2195   bool Changed = SimplifyCommutative(I);
2196   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2197
2198   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2199     // X + undef -> undef
2200     if (isa<UndefValue>(RHS))
2201       return ReplaceInstUsesWith(I, RHS);
2202
2203     // X + 0 --> X
2204     if (RHSC->isNullValue())
2205       return ReplaceInstUsesWith(I, LHS);
2206
2207     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2208       // X + (signbit) --> X ^ signbit
2209       const APInt& Val = CI->getValue();
2210       uint32_t BitWidth = Val.getBitWidth();
2211       if (Val == APInt::getSignBit(BitWidth))
2212         return BinaryOperator::CreateXor(LHS, RHS);
2213       
2214       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2215       // (X & 254)+1 -> (X&254)|1
2216       if (SimplifyDemandedInstructionBits(I))
2217         return &I;
2218
2219       // zext(bool) + C -> bool ? C + 1 : C
2220       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2221         if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2222           return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
2223     }
2224
2225     if (isa<PHINode>(LHS))
2226       if (Instruction *NV = FoldOpIntoPhi(I))
2227         return NV;
2228     
2229     ConstantInt *XorRHS = 0;
2230     Value *XorLHS = 0;
2231     if (isa<ConstantInt>(RHSC) &&
2232         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2233       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2234       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2235       
2236       uint32_t Size = TySizeBits / 2;
2237       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2238       APInt CFF80Val(-C0080Val);
2239       do {
2240         if (TySizeBits > Size) {
2241           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2242           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2243           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2244               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2245             // This is a sign extend if the top bits are known zero.
2246             if (!MaskedValueIsZero(XorLHS, 
2247                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2248               Size = 0;  // Not a sign ext, but can't be any others either.
2249             break;
2250           }
2251         }
2252         Size >>= 1;
2253         C0080Val = APIntOps::lshr(C0080Val, Size);
2254         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2255       } while (Size >= 1);
2256       
2257       // FIXME: This shouldn't be necessary. When the backends can handle types
2258       // with funny bit widths then this switch statement should be removed. It
2259       // is just here to get the size of the "middle" type back up to something
2260       // that the back ends can handle.
2261       const Type *MiddleType = 0;
2262       switch (Size) {
2263         default: break;
2264         case 32: MiddleType = Type::getInt32Ty(*Context); break;
2265         case 16: MiddleType = Type::getInt16Ty(*Context); break;
2266         case  8: MiddleType = Type::getInt8Ty(*Context); break;
2267       }
2268       if (MiddleType) {
2269         Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
2270         return new SExtInst(NewTrunc, I.getType(), I.getName());
2271       }
2272     }
2273   }
2274
2275   if (I.getType() == Type::getInt1Ty(*Context))
2276     return BinaryOperator::CreateXor(LHS, RHS);
2277
2278   // X + X --> X << 1
2279   if (I.getType()->isInteger()) {
2280     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
2281       return Result;
2282
2283     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2284       if (RHSI->getOpcode() == Instruction::Sub)
2285         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2286           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2287     }
2288     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2289       if (LHSI->getOpcode() == Instruction::Sub)
2290         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2291           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2292     }
2293   }
2294
2295   // -A + B  -->  B - A
2296   // -A + -B  -->  -(A + B)
2297   if (Value *LHSV = dyn_castNegVal(LHS)) {
2298     if (LHS->getType()->isIntOrIntVector()) {
2299       if (Value *RHSV = dyn_castNegVal(RHS)) {
2300         Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
2301         return BinaryOperator::CreateNeg(NewAdd);
2302       }
2303     }
2304     
2305     return BinaryOperator::CreateSub(RHS, LHSV);
2306   }
2307
2308   // A + -B  -->  A - B
2309   if (!isa<Constant>(RHS))
2310     if (Value *V = dyn_castNegVal(RHS))
2311       return BinaryOperator::CreateSub(LHS, V);
2312
2313
2314   ConstantInt *C2;
2315   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2316     if (X == RHS)   // X*C + X --> X * (C+1)
2317       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2318
2319     // X*C1 + X*C2 --> X * (C1+C2)
2320     ConstantInt *C1;
2321     if (X == dyn_castFoldableMul(RHS, C1))
2322       return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2323   }
2324
2325   // X + X*C --> X * (C+1)
2326   if (dyn_castFoldableMul(RHS, C2) == LHS)
2327     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2328
2329   // X + ~X --> -1   since   ~X = -X-1
2330   if (dyn_castNotVal(LHS) == RHS ||
2331       dyn_castNotVal(RHS) == LHS)
2332     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2333   
2334
2335   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2336   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2337     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2338       return R;
2339   
2340   // A+B --> A|B iff A and B have no bits set in common.
2341   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2342     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2343     APInt LHSKnownOne(IT->getBitWidth(), 0);
2344     APInt LHSKnownZero(IT->getBitWidth(), 0);
2345     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2346     if (LHSKnownZero != 0) {
2347       APInt RHSKnownOne(IT->getBitWidth(), 0);
2348       APInt RHSKnownZero(IT->getBitWidth(), 0);
2349       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2350       
2351       // No bits in common -> bitwise or.
2352       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2353         return BinaryOperator::CreateOr(LHS, RHS);
2354     }
2355   }
2356
2357   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2358   if (I.getType()->isIntOrIntVector()) {
2359     Value *W, *X, *Y, *Z;
2360     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2361         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2362       if (W != Y) {
2363         if (W == Z) {
2364           std::swap(Y, Z);
2365         } else if (Y == X) {
2366           std::swap(W, X);
2367         } else if (X == Z) {
2368           std::swap(Y, Z);
2369           std::swap(W, X);
2370         }
2371       }
2372
2373       if (W == Y) {
2374         Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
2375         return BinaryOperator::CreateMul(W, NewAdd);
2376       }
2377     }
2378   }
2379
2380   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2381     Value *X = 0;
2382     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2383       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2384
2385     // (X & FF00) + xx00  -> (X+xx00) & FF00
2386     if (LHS->hasOneUse() &&
2387         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2388       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2389       if (Anded == CRHS) {
2390         // See if all bits from the first bit set in the Add RHS up are included
2391         // in the mask.  First, get the rightmost bit.
2392         const APInt& AddRHSV = CRHS->getValue();
2393
2394         // Form a mask of all bits from the lowest bit added through the top.
2395         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2396
2397         // See if the and mask includes all of these bits.
2398         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2399
2400         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2401           // Okay, the xform is safe.  Insert the new add pronto.
2402           Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
2403           return BinaryOperator::CreateAnd(NewAdd, C2);
2404         }
2405       }
2406     }
2407
2408     // Try to fold constant add into select arguments.
2409     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2410       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2411         return R;
2412   }
2413
2414   // add (select X 0 (sub n A)) A  -->  select X A n
2415   {
2416     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2417     Value *A = RHS;
2418     if (!SI) {
2419       SI = dyn_cast<SelectInst>(RHS);
2420       A = LHS;
2421     }
2422     if (SI && SI->hasOneUse()) {
2423       Value *TV = SI->getTrueValue();
2424       Value *FV = SI->getFalseValue();
2425       Value *N;
2426
2427       // Can we fold the add into the argument of the select?
2428       // We check both true and false select arguments for a matching subtract.
2429       if (match(FV, m_Zero()) &&
2430           match(TV, m_Sub(m_Value(N), m_Specific(A))))
2431         // Fold the add into the true select value.
2432         return SelectInst::Create(SI->getCondition(), N, A);
2433       if (match(TV, m_Zero()) &&
2434           match(FV, m_Sub(m_Value(N), m_Specific(A))))
2435         // Fold the add into the false select value.
2436         return SelectInst::Create(SI->getCondition(), A, N);
2437     }
2438   }
2439
2440   // Check for (add (sext x), y), see if we can merge this into an
2441   // integer add followed by a sext.
2442   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2443     // (add (sext x), cst) --> (sext (add x, cst'))
2444     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2445       Constant *CI = 
2446         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2447       if (LHSConv->hasOneUse() &&
2448           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2449           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2450         // Insert the new, smaller add.
2451         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0), 
2452                                            CI, "addconv");
2453         return new SExtInst(NewAdd, I.getType());
2454       }
2455     }
2456     
2457     // (add (sext x), (sext y)) --> (sext (add int x, y))
2458     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2459       // Only do this if x/y have the same type, if at last one of them has a
2460       // single use (so we don't increase the number of sexts), and if the
2461       // integer add will not overflow.
2462       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2463           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2464           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2465                                    RHSConv->getOperand(0))) {
2466         // Insert the new integer add.
2467         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0), 
2468                                            RHSConv->getOperand(0), "addconv");
2469         return new SExtInst(NewAdd, I.getType());
2470       }
2471     }
2472   }
2473
2474   return Changed ? &I : 0;
2475 }
2476
2477 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2478   bool Changed = SimplifyCommutative(I);
2479   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2480
2481   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2482     // X + 0 --> X
2483     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2484       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2485                               (I.getType())->getValueAPF()))
2486         return ReplaceInstUsesWith(I, LHS);
2487     }
2488
2489     if (isa<PHINode>(LHS))
2490       if (Instruction *NV = FoldOpIntoPhi(I))
2491         return NV;
2492   }
2493
2494   // -A + B  -->  B - A
2495   // -A + -B  -->  -(A + B)
2496   if (Value *LHSV = dyn_castFNegVal(LHS))
2497     return BinaryOperator::CreateFSub(RHS, LHSV);
2498
2499   // A + -B  -->  A - B
2500   if (!isa<Constant>(RHS))
2501     if (Value *V = dyn_castFNegVal(RHS))
2502       return BinaryOperator::CreateFSub(LHS, V);
2503
2504   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2505   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2506     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2507       return ReplaceInstUsesWith(I, LHS);
2508
2509   // Check for (add double (sitofp x), y), see if we can merge this into an
2510   // integer add followed by a promotion.
2511   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2512     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2513     // ... if the constant fits in the integer value.  This is useful for things
2514     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2515     // requires a constant pool load, and generally allows the add to be better
2516     // instcombined.
2517     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2518       Constant *CI = 
2519       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2520       if (LHSConv->hasOneUse() &&
2521           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2522           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2523         // Insert the new integer add.
2524         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2525                                            CI, "addconv");
2526         return new SIToFPInst(NewAdd, I.getType());
2527       }
2528     }
2529     
2530     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2531     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2532       // Only do this if x/y have the same type, if at last one of them has a
2533       // single use (so we don't increase the number of int->fp conversions),
2534       // and if the integer add will not overflow.
2535       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2536           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2537           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2538                                    RHSConv->getOperand(0))) {
2539         // Insert the new integer add.
2540         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0), 
2541                                            RHSConv->getOperand(0), "addconv");
2542         return new SIToFPInst(NewAdd, I.getType());
2543       }
2544     }
2545   }
2546   
2547   return Changed ? &I : 0;
2548 }
2549
2550 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2551   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2552
2553   if (Op0 == Op1)                        // sub X, X  -> 0
2554     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2555
2556   // If this is a 'B = x-(-A)', change to B = x+A...
2557   if (Value *V = dyn_castNegVal(Op1))
2558     return BinaryOperator::CreateAdd(Op0, V);
2559
2560   if (isa<UndefValue>(Op0))
2561     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2562   if (isa<UndefValue>(Op1))
2563     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2564
2565   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2566     // Replace (-1 - A) with (~A)...
2567     if (C->isAllOnesValue())
2568       return BinaryOperator::CreateNot(Op1);
2569
2570     // C - ~X == X + (1+C)
2571     Value *X = 0;
2572     if (match(Op1, m_Not(m_Value(X))))
2573       return BinaryOperator::CreateAdd(X, AddOne(C));
2574
2575     // -(X >>u 31) -> (X >>s 31)
2576     // -(X >>s 31) -> (X >>u 31)
2577     if (C->isZero()) {
2578       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2579         if (SI->getOpcode() == Instruction::LShr) {
2580           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2581             // Check to see if we are shifting out everything but the sign bit.
2582             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2583                 SI->getType()->getPrimitiveSizeInBits()-1) {
2584               // Ok, the transformation is safe.  Insert AShr.
2585               return BinaryOperator::Create(Instruction::AShr, 
2586                                           SI->getOperand(0), CU, SI->getName());
2587             }
2588           }
2589         }
2590         else if (SI->getOpcode() == Instruction::AShr) {
2591           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2592             // Check to see if we are shifting out everything but the sign bit.
2593             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2594                 SI->getType()->getPrimitiveSizeInBits()-1) {
2595               // Ok, the transformation is safe.  Insert LShr. 
2596               return BinaryOperator::CreateLShr(
2597                                           SI->getOperand(0), CU, SI->getName());
2598             }
2599           }
2600         }
2601       }
2602     }
2603
2604     // Try to fold constant sub into select arguments.
2605     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2606       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2607         return R;
2608
2609     // C - zext(bool) -> bool ? C - 1 : C
2610     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2611       if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2612         return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
2613   }
2614
2615   if (I.getType() == Type::getInt1Ty(*Context))
2616     return BinaryOperator::CreateXor(Op0, Op1);
2617
2618   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2619     if (Op1I->getOpcode() == Instruction::Add) {
2620       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2621         return BinaryOperator::CreateNeg(Op1I->getOperand(1),
2622                                          I.getName());
2623       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2624         return BinaryOperator::CreateNeg(Op1I->getOperand(0),
2625                                          I.getName());
2626       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2627         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2628           // C1-(X+C2) --> (C1-C2)-X
2629           return BinaryOperator::CreateSub(
2630             ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
2631       }
2632     }
2633
2634     if (Op1I->hasOneUse()) {
2635       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2636       // is not used by anyone else...
2637       //
2638       if (Op1I->getOpcode() == Instruction::Sub) {
2639         // Swap the two operands of the subexpr...
2640         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2641         Op1I->setOperand(0, IIOp1);
2642         Op1I->setOperand(1, IIOp0);
2643
2644         // Create the new top level add instruction...
2645         return BinaryOperator::CreateAdd(Op0, Op1);
2646       }
2647
2648       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2649       //
2650       if (Op1I->getOpcode() == Instruction::And &&
2651           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2652         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2653
2654         Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
2655         return BinaryOperator::CreateAnd(Op0, NewNot);
2656       }
2657
2658       // 0 - (X sdiv C)  -> (X sdiv -C)
2659       if (Op1I->getOpcode() == Instruction::SDiv)
2660         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2661           if (CSI->isZero())
2662             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2663               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2664                                           ConstantExpr::getNeg(DivRHS));
2665
2666       // X - X*C --> X * (1-C)
2667       ConstantInt *C2 = 0;
2668       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2669         Constant *CP1 = 
2670           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2671                                              C2);
2672         return BinaryOperator::CreateMul(Op0, CP1);
2673       }
2674     }
2675   }
2676
2677   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2678     if (Op0I->getOpcode() == Instruction::Add) {
2679       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2680         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2681       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2682         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2683     } else if (Op0I->getOpcode() == Instruction::Sub) {
2684       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2685         return BinaryOperator::CreateNeg(Op0I->getOperand(1),
2686                                          I.getName());
2687     }
2688   }
2689
2690   ConstantInt *C1;
2691   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2692     if (X == Op1)  // X*C - X --> X * (C-1)
2693       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2694
2695     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2696     if (X == dyn_castFoldableMul(Op1, C2))
2697       return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2698   }
2699   return 0;
2700 }
2701
2702 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2703   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2704
2705   // If this is a 'B = x-(-A)', change to B = x+A...
2706   if (Value *V = dyn_castFNegVal(Op1))
2707     return BinaryOperator::CreateFAdd(Op0, V);
2708
2709   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2710     if (Op1I->getOpcode() == Instruction::FAdd) {
2711       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2712         return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
2713                                           I.getName());
2714       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2715         return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
2716                                           I.getName());
2717     }
2718   }
2719
2720   return 0;
2721 }
2722
2723 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2724 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2725 /// TrueIfSigned if the result of the comparison is true when the input value is
2726 /// signed.
2727 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2728                            bool &TrueIfSigned) {
2729   switch (pred) {
2730   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2731     TrueIfSigned = true;
2732     return RHS->isZero();
2733   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2734     TrueIfSigned = true;
2735     return RHS->isAllOnesValue();
2736   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2737     TrueIfSigned = false;
2738     return RHS->isAllOnesValue();
2739   case ICmpInst::ICMP_UGT:
2740     // True if LHS u> RHS and RHS == high-bit-mask - 1
2741     TrueIfSigned = true;
2742     return RHS->getValue() ==
2743       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2744   case ICmpInst::ICMP_UGE: 
2745     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2746     TrueIfSigned = true;
2747     return RHS->getValue().isSignBit();
2748   default:
2749     return false;
2750   }
2751 }
2752
2753 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2754   bool Changed = SimplifyCommutative(I);
2755   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2756
2757   if (isa<UndefValue>(Op1))              // undef * X -> 0
2758     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2759
2760   // Simplify mul instructions with a constant RHS.
2761   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2762     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
2763
2764       // ((X << C1)*C2) == (X * (C2 << C1))
2765       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2766         if (SI->getOpcode() == Instruction::Shl)
2767           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2768             return BinaryOperator::CreateMul(SI->getOperand(0),
2769                                         ConstantExpr::getShl(CI, ShOp));
2770
2771       if (CI->isZero())
2772         return ReplaceInstUsesWith(I, Op1C);  // X * 0  == 0
2773       if (CI->equalsInt(1))                  // X * 1  == X
2774         return ReplaceInstUsesWith(I, Op0);
2775       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2776         return BinaryOperator::CreateNeg(Op0, I.getName());
2777
2778       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2779       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2780         return BinaryOperator::CreateShl(Op0,
2781                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2782       }
2783     } else if (isa<VectorType>(Op1C->getType())) {
2784       if (Op1C->isNullValue())
2785         return ReplaceInstUsesWith(I, Op1C);
2786
2787       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
2788         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2789           return BinaryOperator::CreateNeg(Op0, I.getName());
2790
2791         // As above, vector X*splat(1.0) -> X in all defined cases.
2792         if (Constant *Splat = Op1V->getSplatValue()) {
2793           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2794             if (CI->equalsInt(1))
2795               return ReplaceInstUsesWith(I, Op0);
2796         }
2797       }
2798     }
2799     
2800     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2801       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2802           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
2803         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2804         Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
2805         Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
2806         return BinaryOperator::CreateAdd(Add, C1C2);
2807         
2808       }
2809
2810     // Try to fold constant mul into select arguments.
2811     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2812       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2813         return R;
2814
2815     if (isa<PHINode>(Op0))
2816       if (Instruction *NV = FoldOpIntoPhi(I))
2817         return NV;
2818   }
2819
2820   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2821     if (Value *Op1v = dyn_castNegVal(Op1))
2822       return BinaryOperator::CreateMul(Op0v, Op1v);
2823
2824   // (X / Y) *  Y = X - (X % Y)
2825   // (X / Y) * -Y = (X % Y) - X
2826   {
2827     Value *Op1C = Op1;
2828     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2829     if (!BO ||
2830         (BO->getOpcode() != Instruction::UDiv && 
2831          BO->getOpcode() != Instruction::SDiv)) {
2832       Op1C = Op0;
2833       BO = dyn_cast<BinaryOperator>(Op1);
2834     }
2835     Value *Neg = dyn_castNegVal(Op1C);
2836     if (BO && BO->hasOneUse() &&
2837         (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
2838         (BO->getOpcode() == Instruction::UDiv ||
2839          BO->getOpcode() == Instruction::SDiv)) {
2840       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2841
2842       // If the division is exact, X % Y is zero.
2843       if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2844         if (SDiv->isExact()) {
2845           if (Op1BO == Op1C)
2846             return ReplaceInstUsesWith(I, Op0BO);
2847           return BinaryOperator::CreateNeg(Op0BO);
2848         }
2849
2850       Value *Rem;
2851       if (BO->getOpcode() == Instruction::UDiv)
2852         Rem = Builder->CreateURem(Op0BO, Op1BO);
2853       else
2854         Rem = Builder->CreateSRem(Op0BO, Op1BO);
2855       Rem->takeName(BO);
2856
2857       if (Op1BO == Op1C)
2858         return BinaryOperator::CreateSub(Op0BO, Rem);
2859       return BinaryOperator::CreateSub(Rem, Op0BO);
2860     }
2861   }
2862
2863   /// i1 mul -> i1 and.
2864   if (I.getType() == Type::getInt1Ty(*Context))
2865     return BinaryOperator::CreateAnd(Op0, Op1);
2866
2867   // X*(1 << Y) --> X << Y
2868   // (1 << Y)*X --> X << Y
2869   {
2870     Value *Y;
2871     if (match(Op0, m_Shl(m_One(), m_Value(Y))))
2872       return BinaryOperator::CreateShl(Op1, Y);
2873     if (match(Op1, m_Shl(m_One(), m_Value(Y))))
2874       return BinaryOperator::CreateShl(Op0, Y);
2875   }
2876   
2877   // If one of the operands of the multiply is a cast from a boolean value, then
2878   // we know the bool is either zero or one, so this is a 'masking' multiply.
2879   //   X * Y (where Y is 0 or 1) -> X & (0-Y)
2880   if (!isa<VectorType>(I.getType())) {
2881     // -2 is "-1 << 1" so it is all bits set except the low one.
2882     APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
2883     
2884     Value *BoolCast = 0, *OtherOp = 0;
2885     if (MaskedValueIsZero(Op0, Negative2))
2886       BoolCast = Op0, OtherOp = Op1;
2887     else if (MaskedValueIsZero(Op1, Negative2))
2888       BoolCast = Op1, OtherOp = Op0;
2889
2890     if (BoolCast) {
2891       Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
2892                                     BoolCast, "tmp");
2893       return BinaryOperator::CreateAnd(V, OtherOp);
2894     }
2895   }
2896
2897   return Changed ? &I : 0;
2898 }
2899
2900 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2901   bool Changed = SimplifyCommutative(I);
2902   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2903
2904   // Simplify mul instructions with a constant RHS...
2905   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2906     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
2907       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2908       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2909       if (Op1F->isExactlyValue(1.0))
2910         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2911     } else if (isa<VectorType>(Op1C->getType())) {
2912       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
2913         // As above, vector X*splat(1.0) -> X in all defined cases.
2914         if (Constant *Splat = Op1V->getSplatValue()) {
2915           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2916             if (F->isExactlyValue(1.0))
2917               return ReplaceInstUsesWith(I, Op0);
2918         }
2919       }
2920     }
2921
2922     // Try to fold constant mul into select arguments.
2923     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2924       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2925         return R;
2926
2927     if (isa<PHINode>(Op0))
2928       if (Instruction *NV = FoldOpIntoPhi(I))
2929         return NV;
2930   }
2931
2932   if (Value *Op0v = dyn_castFNegVal(Op0))     // -X * -Y = X*Y
2933     if (Value *Op1v = dyn_castFNegVal(Op1))
2934       return BinaryOperator::CreateFMul(Op0v, Op1v);
2935
2936   return Changed ? &I : 0;
2937 }
2938
2939 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2940 /// instruction.
2941 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2942   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2943   
2944   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2945   int NonNullOperand = -1;
2946   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2947     if (ST->isNullValue())
2948       NonNullOperand = 2;
2949   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2950   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2951     if (ST->isNullValue())
2952       NonNullOperand = 1;
2953   
2954   if (NonNullOperand == -1)
2955     return false;
2956   
2957   Value *SelectCond = SI->getOperand(0);
2958   
2959   // Change the div/rem to use 'Y' instead of the select.
2960   I.setOperand(1, SI->getOperand(NonNullOperand));
2961   
2962   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2963   // problem.  However, the select, or the condition of the select may have
2964   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2965   // propagate the known value for the select into other uses of it, and
2966   // propagate a known value of the condition into its other users.
2967   
2968   // If the select and condition only have a single use, don't bother with this,
2969   // early exit.
2970   if (SI->use_empty() && SelectCond->hasOneUse())
2971     return true;
2972   
2973   // Scan the current block backward, looking for other uses of SI.
2974   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2975   
2976   while (BBI != BBFront) {
2977     --BBI;
2978     // If we found a call to a function, we can't assume it will return, so
2979     // information from below it cannot be propagated above it.
2980     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2981       break;
2982     
2983     // Replace uses of the select or its condition with the known values.
2984     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2985          I != E; ++I) {
2986       if (*I == SI) {
2987         *I = SI->getOperand(NonNullOperand);
2988         Worklist.Add(BBI);
2989       } else if (*I == SelectCond) {
2990         *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2991                                    ConstantInt::getFalse(*Context);
2992         Worklist.Add(BBI);
2993       }
2994     }
2995     
2996     // If we past the instruction, quit looking for it.
2997     if (&*BBI == SI)
2998       SI = 0;
2999     if (&*BBI == SelectCond)
3000       SelectCond = 0;
3001     
3002     // If we ran out of things to eliminate, break out of the loop.
3003     if (SelectCond == 0 && SI == 0)
3004       break;
3005     
3006   }
3007   return true;
3008 }
3009
3010
3011 /// This function implements the transforms on div instructions that work
3012 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3013 /// used by the visitors to those instructions.
3014 /// @brief Transforms common to all three div instructions
3015 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
3016   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3017
3018   // undef / X -> 0        for integer.
3019   // undef / X -> undef    for FP (the undef could be a snan).
3020   if (isa<UndefValue>(Op0)) {
3021     if (Op0->getType()->isFPOrFPVector())
3022       return ReplaceInstUsesWith(I, Op0);
3023     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3024   }
3025
3026   // X / undef -> undef
3027   if (isa<UndefValue>(Op1))
3028     return ReplaceInstUsesWith(I, Op1);
3029
3030   return 0;
3031 }
3032
3033 /// This function implements the transforms common to both integer division
3034 /// instructions (udiv and sdiv). It is called by the visitors to those integer
3035 /// division instructions.
3036 /// @brief Common integer divide transforms
3037 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
3038   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3039
3040   // (sdiv X, X) --> 1     (udiv X, X) --> 1
3041   if (Op0 == Op1) {
3042     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
3043       Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
3044       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
3045       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
3046     }
3047
3048     Constant *CI = ConstantInt::get(I.getType(), 1);
3049     return ReplaceInstUsesWith(I, CI);
3050   }
3051   
3052   if (Instruction *Common = commonDivTransforms(I))
3053     return Common;
3054   
3055   // Handle cases involving: [su]div X, (select Cond, Y, Z)
3056   // This does not apply for fdiv.
3057   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3058     return &I;
3059
3060   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3061     // div X, 1 == X
3062     if (RHS->equalsInt(1))
3063       return ReplaceInstUsesWith(I, Op0);
3064
3065     // (X / C1) / C2  -> X / (C1*C2)
3066     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3067       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3068         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3069           if (MultiplyOverflows(RHS, LHSRHS,
3070                                 I.getOpcode()==Instruction::SDiv))
3071             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3072           else 
3073             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
3074                                       ConstantExpr::getMul(RHS, LHSRHS));
3075         }
3076
3077     if (!RHS->isZero()) { // avoid X udiv 0
3078       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3079         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3080           return R;
3081       if (isa<PHINode>(Op0))
3082         if (Instruction *NV = FoldOpIntoPhi(I))
3083           return NV;
3084     }
3085   }
3086
3087   // 0 / X == 0, we don't need to preserve faults!
3088   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3089     if (LHS->equalsInt(0))
3090       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3091
3092   // It can't be division by zero, hence it must be division by one.
3093   if (I.getType() == Type::getInt1Ty(*Context))
3094     return ReplaceInstUsesWith(I, Op0);
3095
3096   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3097     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3098       // div X, 1 == X
3099       if (X->isOne())
3100         return ReplaceInstUsesWith(I, Op0);
3101   }
3102
3103   return 0;
3104 }
3105
3106 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3107   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3108
3109   // Handle the integer div common cases
3110   if (Instruction *Common = commonIDivTransforms(I))
3111     return Common;
3112
3113   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3114     // X udiv C^2 -> X >> C
3115     // Check to see if this is an unsigned division with an exact power of 2,
3116     // if so, convert to a right shift.
3117     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3118       return BinaryOperator::CreateLShr(Op0, 
3119             ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3120
3121     // X udiv C, where C >= signbit
3122     if (C->getValue().isNegative()) {
3123       Value *IC = Builder->CreateICmpULT( Op0, C);
3124       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3125                                 ConstantInt::get(I.getType(), 1));
3126     }
3127   }
3128
3129   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3130   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3131     if (RHSI->getOpcode() == Instruction::Shl &&
3132         isa<ConstantInt>(RHSI->getOperand(0))) {
3133       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3134       if (C1.isPowerOf2()) {
3135         Value *N = RHSI->getOperand(1);
3136         const Type *NTy = N->getType();
3137         if (uint32_t C2 = C1.logBase2())
3138           N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
3139         return BinaryOperator::CreateLShr(Op0, N);
3140       }
3141     }
3142   }
3143   
3144   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3145   // where C1&C2 are powers of two.
3146   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3147     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3148       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3149         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3150         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3151           // Compute the shift amounts
3152           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3153           // Construct the "on true" case of the select
3154           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3155           Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
3156   
3157           // Construct the "on false" case of the select
3158           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3159           Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
3160
3161           // construct the select instruction and return it.
3162           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3163         }
3164       }
3165   return 0;
3166 }
3167
3168 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3169   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3170
3171   // Handle the integer div common cases
3172   if (Instruction *Common = commonIDivTransforms(I))
3173     return Common;
3174
3175   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3176     // sdiv X, -1 == -X
3177     if (RHS->isAllOnesValue())
3178       return BinaryOperator::CreateNeg(Op0);
3179
3180     // sdiv X, C  -->  ashr X, log2(C)
3181     if (cast<SDivOperator>(&I)->isExact() &&
3182         RHS->getValue().isNonNegative() &&
3183         RHS->getValue().isPowerOf2()) {
3184       Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3185                                             RHS->getValue().exactLogBase2());
3186       return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3187     }
3188
3189     // -X/C  -->  X/-C  provided the negation doesn't overflow.
3190     if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3191       if (isa<Constant>(Sub->getOperand(0)) &&
3192           cast<Constant>(Sub->getOperand(0))->isNullValue() &&
3193           Sub->hasNoSignedWrap())
3194         return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3195                                           ConstantExpr::getNeg(RHS));
3196   }
3197
3198   // If the sign bits of both operands are zero (i.e. we can prove they are
3199   // unsigned inputs), turn this into a udiv.
3200   if (I.getType()->isInteger()) {
3201     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3202     if (MaskedValueIsZero(Op0, Mask)) {
3203       if (MaskedValueIsZero(Op1, Mask)) {
3204         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3205         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3206       }
3207       ConstantInt *ShiftedInt;
3208       if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
3209           ShiftedInt->getValue().isPowerOf2()) {
3210         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3211         // Safe because the only negative value (1 << Y) can take on is
3212         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3213         // the sign bit set.
3214         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3215       }
3216     }
3217   }
3218   
3219   return 0;
3220 }
3221
3222 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3223   return commonDivTransforms(I);
3224 }
3225
3226 /// This function implements the transforms on rem instructions that work
3227 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3228 /// is used by the visitors to those instructions.
3229 /// @brief Transforms common to all three rem instructions
3230 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3231   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3232
3233   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3234     if (I.getType()->isFPOrFPVector())
3235       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3236     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3237   }
3238   if (isa<UndefValue>(Op1))
3239     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3240
3241   // Handle cases involving: rem X, (select Cond, Y, Z)
3242   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3243     return &I;
3244
3245   return 0;
3246 }
3247
3248 /// This function implements the transforms common to both integer remainder
3249 /// instructions (urem and srem). It is called by the visitors to those integer
3250 /// remainder instructions.
3251 /// @brief Common integer remainder transforms
3252 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3253   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3254
3255   if (Instruction *common = commonRemTransforms(I))
3256     return common;
3257
3258   // 0 % X == 0 for integer, we don't need to preserve faults!
3259   if (Constant *LHS = dyn_cast<Constant>(Op0))
3260     if (LHS->isNullValue())
3261       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3262
3263   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3264     // X % 0 == undef, we don't need to preserve faults!
3265     if (RHS->equalsInt(0))
3266       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3267     
3268     if (RHS->equalsInt(1))  // X % 1 == 0
3269       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3270
3271     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3272       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3273         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3274           return R;
3275       } else if (isa<PHINode>(Op0I)) {
3276         if (Instruction *NV = FoldOpIntoPhi(I))
3277           return NV;
3278       }
3279
3280       // See if we can fold away this rem instruction.
3281       if (SimplifyDemandedInstructionBits(I))
3282         return &I;
3283     }
3284   }
3285
3286   return 0;
3287 }
3288
3289 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3290   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3291
3292   if (Instruction *common = commonIRemTransforms(I))
3293     return common;
3294   
3295   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3296     // X urem C^2 -> X and C
3297     // Check to see if this is an unsigned remainder with an exact power of 2,
3298     // if so, convert to a bitwise and.
3299     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3300       if (C->getValue().isPowerOf2())
3301         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3302   }
3303
3304   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3305     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3306     if (RHSI->getOpcode() == Instruction::Shl &&
3307         isa<ConstantInt>(RHSI->getOperand(0))) {
3308       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3309         Constant *N1 = Constant::getAllOnesValue(I.getType());
3310         Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
3311         return BinaryOperator::CreateAnd(Op0, Add);
3312       }
3313     }
3314   }
3315
3316   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3317   // where C1&C2 are powers of two.
3318   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3319     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3320       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3321         // STO == 0 and SFO == 0 handled above.
3322         if ((STO->getValue().isPowerOf2()) && 
3323             (SFO->getValue().isPowerOf2())) {
3324           Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3325                                               SI->getName()+".t");
3326           Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3327                                                SI->getName()+".f");
3328           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3329         }
3330       }
3331   }
3332   
3333   return 0;
3334 }
3335
3336 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3337   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3338
3339   // Handle the integer rem common cases
3340   if (Instruction *Common = commonIRemTransforms(I))
3341     return Common;
3342   
3343   if (Value *RHSNeg = dyn_castNegVal(Op1))
3344     if (!isa<Constant>(RHSNeg) ||
3345         (isa<ConstantInt>(RHSNeg) &&
3346          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3347       // X % -Y -> X % Y
3348       Worklist.AddValue(I.getOperand(1));
3349       I.setOperand(1, RHSNeg);
3350       return &I;
3351     }
3352
3353   // If the sign bits of both operands are zero (i.e. we can prove they are
3354   // unsigned inputs), turn this into a urem.
3355   if (I.getType()->isInteger()) {
3356     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3357     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3358       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3359       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3360     }
3361   }
3362
3363   // If it's a constant vector, flip any negative values positive.
3364   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3365     unsigned VWidth = RHSV->getNumOperands();
3366
3367     bool hasNegative = false;
3368     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3369       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3370         if (RHS->getValue().isNegative())
3371           hasNegative = true;
3372
3373     if (hasNegative) {
3374       std::vector<Constant *> Elts(VWidth);
3375       for (unsigned i = 0; i != VWidth; ++i) {
3376         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3377           if (RHS->getValue().isNegative())
3378             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3379           else
3380             Elts[i] = RHS;
3381         }
3382       }
3383
3384       Constant *NewRHSV = ConstantVector::get(Elts);
3385       if (NewRHSV != RHSV) {
3386         Worklist.AddValue(I.getOperand(1));
3387         I.setOperand(1, NewRHSV);
3388         return &I;
3389       }
3390     }
3391   }
3392
3393   return 0;
3394 }
3395
3396 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3397   return commonRemTransforms(I);
3398 }
3399
3400 // isOneBitSet - Return true if there is exactly one bit set in the specified
3401 // constant.
3402 static bool isOneBitSet(const ConstantInt *CI) {
3403   return CI->getValue().isPowerOf2();
3404 }
3405
3406 // isHighOnes - Return true if the constant is of the form 1+0+.
3407 // This is the same as lowones(~X).
3408 static bool isHighOnes(const ConstantInt *CI) {
3409   return (~CI->getValue() + 1).isPowerOf2();
3410 }
3411
3412 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3413 /// are carefully arranged to allow folding of expressions such as:
3414 ///
3415 ///      (A < B) | (A > B) --> (A != B)
3416 ///
3417 /// Note that this is only valid if the first and second predicates have the
3418 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3419 ///
3420 /// Three bits are used to represent the condition, as follows:
3421 ///   0  A > B
3422 ///   1  A == B
3423 ///   2  A < B
3424 ///
3425 /// <=>  Value  Definition
3426 /// 000     0   Always false
3427 /// 001     1   A >  B
3428 /// 010     2   A == B
3429 /// 011     3   A >= B
3430 /// 100     4   A <  B
3431 /// 101     5   A != B
3432 /// 110     6   A <= B
3433 /// 111     7   Always true
3434 ///  
3435 static unsigned getICmpCode(const ICmpInst *ICI) {
3436   switch (ICI->getPredicate()) {
3437     // False -> 0
3438   case ICmpInst::ICMP_UGT: return 1;  // 001
3439   case ICmpInst::ICMP_SGT: return 1;  // 001
3440   case ICmpInst::ICMP_EQ:  return 2;  // 010
3441   case ICmpInst::ICMP_UGE: return 3;  // 011
3442   case ICmpInst::ICMP_SGE: return 3;  // 011
3443   case ICmpInst::ICMP_ULT: return 4;  // 100
3444   case ICmpInst::ICMP_SLT: return 4;  // 100
3445   case ICmpInst::ICMP_NE:  return 5;  // 101
3446   case ICmpInst::ICMP_ULE: return 6;  // 110
3447   case ICmpInst::ICMP_SLE: return 6;  // 110
3448     // True -> 7
3449   default:
3450     llvm_unreachable("Invalid ICmp predicate!");
3451     return 0;
3452   }
3453 }
3454
3455 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3456 /// predicate into a three bit mask. It also returns whether it is an ordered
3457 /// predicate by reference.
3458 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3459   isOrdered = false;
3460   switch (CC) {
3461   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3462   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3463   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3464   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3465   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3466   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3467   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3468   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3469   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3470   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3471   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3472   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3473   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3474   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3475     // True -> 7
3476   default:
3477     // Not expecting FCMP_FALSE and FCMP_TRUE;
3478     llvm_unreachable("Unexpected FCmp predicate!");
3479     return 0;
3480   }
3481 }
3482
3483 /// getICmpValue - This is the complement of getICmpCode, which turns an
3484 /// opcode and two operands into either a constant true or false, or a brand 
3485 /// new ICmp instruction. The sign is passed in to determine which kind
3486 /// of predicate to use in the new icmp instruction.
3487 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3488                            LLVMContext *Context) {
3489   switch (code) {
3490   default: llvm_unreachable("Illegal ICmp code!");
3491   case  0: return ConstantInt::getFalse(*Context);
3492   case  1: 
3493     if (sign)
3494       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3495     else
3496       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3497   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3498   case  3: 
3499     if (sign)
3500       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3501     else
3502       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3503   case  4: 
3504     if (sign)
3505       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3506     else
3507       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3508   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3509   case  6: 
3510     if (sign)
3511       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3512     else
3513       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3514   case  7: return ConstantInt::getTrue(*Context);
3515   }
3516 }
3517
3518 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3519 /// opcode and two operands into either a FCmp instruction. isordered is passed
3520 /// in to determine which kind of predicate to use in the new fcmp instruction.
3521 static Value *getFCmpValue(bool isordered, unsigned code,
3522                            Value *LHS, Value *RHS, LLVMContext *Context) {
3523   switch (code) {
3524   default: llvm_unreachable("Illegal FCmp code!");
3525   case  0:
3526     if (isordered)
3527       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3528     else
3529       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3530   case  1: 
3531     if (isordered)
3532       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3533     else
3534       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3535   case  2: 
3536     if (isordered)
3537       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3538     else
3539       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3540   case  3: 
3541     if (isordered)
3542       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3543     else
3544       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3545   case  4: 
3546     if (isordered)
3547       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3548     else
3549       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3550   case  5: 
3551     if (isordered)
3552       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3553     else
3554       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3555   case  6: 
3556     if (isordered)
3557       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3558     else
3559       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3560   case  7: return ConstantInt::getTrue(*Context);
3561   }
3562 }
3563
3564 /// PredicatesFoldable - Return true if both predicates match sign or if at
3565 /// least one of them is an equality comparison (which is signless).
3566 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3567   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3568          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3569          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3570 }
3571
3572 namespace { 
3573 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3574 struct FoldICmpLogical {
3575   InstCombiner &IC;
3576   Value *LHS, *RHS;
3577   ICmpInst::Predicate pred;
3578   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3579     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3580       pred(ICI->getPredicate()) {}
3581   bool shouldApply(Value *V) const {
3582     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3583       if (PredicatesFoldable(pred, ICI->getPredicate()))
3584         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3585                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3586     return false;
3587   }
3588   Instruction *apply(Instruction &Log) const {
3589     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3590     if (ICI->getOperand(0) != LHS) {
3591       assert(ICI->getOperand(1) == LHS);
3592       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3593     }
3594
3595     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3596     unsigned LHSCode = getICmpCode(ICI);
3597     unsigned RHSCode = getICmpCode(RHSICI);
3598     unsigned Code;
3599     switch (Log.getOpcode()) {
3600     case Instruction::And: Code = LHSCode & RHSCode; break;
3601     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3602     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3603     default: llvm_unreachable("Illegal logical opcode!"); return 0;
3604     }
3605
3606     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3607                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3608       
3609     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3610     if (Instruction *I = dyn_cast<Instruction>(RV))
3611       return I;
3612     // Otherwise, it's a constant boolean value...
3613     return IC.ReplaceInstUsesWith(Log, RV);
3614   }
3615 };
3616 } // end anonymous namespace
3617
3618 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3619 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3620 // guaranteed to be a binary operator.
3621 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3622                                     ConstantInt *OpRHS,
3623                                     ConstantInt *AndRHS,
3624                                     BinaryOperator &TheAnd) {
3625   Value *X = Op->getOperand(0);
3626   Constant *Together = 0;
3627   if (!Op->isShift())
3628     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3629
3630   switch (Op->getOpcode()) {
3631   case Instruction::Xor:
3632     if (Op->hasOneUse()) {
3633       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3634       Value *And = Builder->CreateAnd(X, AndRHS);
3635       And->takeName(Op);
3636       return BinaryOperator::CreateXor(And, Together);
3637     }
3638     break;
3639   case Instruction::Or:
3640     if (Together == AndRHS) // (X | C) & C --> C
3641       return ReplaceInstUsesWith(TheAnd, AndRHS);
3642
3643     if (Op->hasOneUse() && Together != OpRHS) {
3644       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3645       Value *Or = Builder->CreateOr(X, Together);
3646       Or->takeName(Op);
3647       return BinaryOperator::CreateAnd(Or, AndRHS);
3648     }
3649     break;
3650   case Instruction::Add:
3651     if (Op->hasOneUse()) {
3652       // Adding a one to a single bit bit-field should be turned into an XOR
3653       // of the bit.  First thing to check is to see if this AND is with a
3654       // single bit constant.
3655       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3656
3657       // If there is only one bit set...
3658       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3659         // Ok, at this point, we know that we are masking the result of the
3660         // ADD down to exactly one bit.  If the constant we are adding has
3661         // no bits set below this bit, then we can eliminate the ADD.
3662         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3663
3664         // Check to see if any bits below the one bit set in AndRHSV are set.
3665         if ((AddRHS & (AndRHSV-1)) == 0) {
3666           // If not, the only thing that can effect the output of the AND is
3667           // the bit specified by AndRHSV.  If that bit is set, the effect of
3668           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3669           // no effect.
3670           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3671             TheAnd.setOperand(0, X);
3672             return &TheAnd;
3673           } else {
3674             // Pull the XOR out of the AND.
3675             Value *NewAnd = Builder->CreateAnd(X, AndRHS);
3676             NewAnd->takeName(Op);
3677             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3678           }
3679         }
3680       }
3681     }
3682     break;
3683
3684   case Instruction::Shl: {
3685     // We know that the AND will not produce any of the bits shifted in, so if
3686     // the anded constant includes them, clear them now!
3687     //
3688     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3689     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3690     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3691     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3692
3693     if (CI->getValue() == ShlMask) { 
3694     // Masking out bits that the shift already masks
3695       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3696     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3697       TheAnd.setOperand(1, CI);
3698       return &TheAnd;
3699     }
3700     break;
3701   }
3702   case Instruction::LShr:
3703   {
3704     // We know that the AND will not produce any of the bits shifted in, so if
3705     // the anded constant includes them, clear them now!  This only applies to
3706     // unsigned shifts, because a signed shr may bring in set bits!
3707     //
3708     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3709     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3710     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3711     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3712
3713     if (CI->getValue() == ShrMask) {   
3714     // Masking out bits that the shift already masks.
3715       return ReplaceInstUsesWith(TheAnd, Op);
3716     } else if (CI != AndRHS) {
3717       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3718       return &TheAnd;
3719     }
3720     break;
3721   }
3722   case Instruction::AShr:
3723     // Signed shr.
3724     // See if this is shifting in some sign extension, then masking it out
3725     // with an and.
3726     if (Op->hasOneUse()) {
3727       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3728       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3729       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3730       Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3731       if (C == AndRHS) {          // Masking out bits shifted in.
3732         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3733         // Make the argument unsigned.
3734         Value *ShVal = Op->getOperand(0);
3735         ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
3736         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3737       }
3738     }
3739     break;
3740   }
3741   return 0;
3742 }
3743
3744
3745 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3746 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3747 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3748 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3749 /// insert new instructions.
3750 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3751                                            bool isSigned, bool Inside, 
3752                                            Instruction &IB) {
3753   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3754             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3755          "Lo is not <= Hi in range emission code!");
3756     
3757   if (Inside) {
3758     if (Lo == Hi)  // Trivially false.
3759       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3760
3761     // V >= Min && V < Hi --> V < Hi
3762     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3763       ICmpInst::Predicate pred = (isSigned ? 
3764         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3765       return new ICmpInst(pred, V, Hi);
3766     }
3767
3768     // Emit V-Lo <u Hi-Lo
3769     Constant *NegLo = ConstantExpr::getNeg(Lo);
3770     Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3771     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3772     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3773   }
3774
3775   if (Lo == Hi)  // Trivially true.
3776     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3777
3778   // V < Min || V >= Hi -> V > Hi-1
3779   Hi = SubOne(cast<ConstantInt>(Hi));
3780   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3781     ICmpInst::Predicate pred = (isSigned ? 
3782         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3783     return new ICmpInst(pred, V, Hi);
3784   }
3785
3786   // Emit V-Lo >u Hi-1-Lo
3787   // Note that Hi has already had one subtracted from it, above.
3788   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3789   Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3790   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3791   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3792 }
3793
3794 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3795 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3796 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3797 // not, since all 1s are not contiguous.
3798 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3799   const APInt& V = Val->getValue();
3800   uint32_t BitWidth = Val->getType()->getBitWidth();
3801   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3802
3803   // look for the first zero bit after the run of ones
3804   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3805   // look for the first non-zero bit
3806   ME = V.getActiveBits(); 
3807   return true;
3808 }
3809
3810 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3811 /// where isSub determines whether the operator is a sub.  If we can fold one of
3812 /// the following xforms:
3813 /// 
3814 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3815 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3816 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3817 ///
3818 /// return (A +/- B).
3819 ///
3820 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3821                                         ConstantInt *Mask, bool isSub,
3822                                         Instruction &I) {
3823   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3824   if (!LHSI || LHSI->getNumOperands() != 2 ||
3825       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3826
3827   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3828
3829   switch (LHSI->getOpcode()) {
3830   default: return 0;
3831   case Instruction::And:
3832     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3833       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3834       if ((Mask->getValue().countLeadingZeros() + 
3835            Mask->getValue().countPopulation()) == 
3836           Mask->getValue().getBitWidth())
3837         break;
3838
3839       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3840       // part, we don't need any explicit masks to take them out of A.  If that
3841       // is all N is, ignore it.
3842       uint32_t MB = 0, ME = 0;
3843       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3844         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3845         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3846         if (MaskedValueIsZero(RHS, Mask))
3847           break;
3848       }
3849     }
3850     return 0;
3851   case Instruction::Or:
3852   case Instruction::Xor:
3853     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3854     if ((Mask->getValue().countLeadingZeros() + 
3855          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3856         && ConstantExpr::getAnd(N, Mask)->isNullValue())
3857       break;
3858     return 0;
3859   }
3860   
3861   if (isSub)
3862     return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3863   return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
3864 }
3865
3866 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3867 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3868                                           ICmpInst *LHS, ICmpInst *RHS) {
3869   Value *Val, *Val2;
3870   ConstantInt *LHSCst, *RHSCst;
3871   ICmpInst::Predicate LHSCC, RHSCC;
3872   
3873   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3874   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3875                          m_ConstantInt(LHSCst))) ||
3876       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3877                          m_ConstantInt(RHSCst))))
3878     return 0;
3879   
3880   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3881   // where C is a power of 2
3882   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3883       LHSCst->getValue().isPowerOf2()) {
3884     Value *NewOr = Builder->CreateOr(Val, Val2);
3885     return new ICmpInst(LHSCC, NewOr, LHSCst);
3886   }
3887   
3888   // From here on, we only handle:
3889   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3890   if (Val != Val2) return 0;
3891   
3892   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3893   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3894       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3895       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3896       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3897     return 0;
3898   
3899   // We can't fold (ugt x, C) & (sgt x, C2).
3900   if (!PredicatesFoldable(LHSCC, RHSCC))
3901     return 0;
3902     
3903   // Ensure that the larger constant is on the RHS.
3904   bool ShouldSwap;
3905   if (ICmpInst::isSignedPredicate(LHSCC) ||
3906       (ICmpInst::isEquality(LHSCC) && 
3907        ICmpInst::isSignedPredicate(RHSCC)))
3908     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3909   else
3910     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3911     
3912   if (ShouldSwap) {
3913     std::swap(LHS, RHS);
3914     std::swap(LHSCst, RHSCst);
3915     std::swap(LHSCC, RHSCC);
3916   }
3917
3918   // At this point, we know we have have two icmp instructions
3919   // comparing a value against two constants and and'ing the result
3920   // together.  Because of the above check, we know that we only have
3921   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3922   // (from the FoldICmpLogical check above), that the two constants 
3923   // are not equal and that the larger constant is on the RHS
3924   assert(LHSCst != RHSCst && "Compares not folded above?");
3925
3926   switch (LHSCC) {
3927   default: llvm_unreachable("Unknown integer condition code!");
3928   case ICmpInst::ICMP_EQ:
3929     switch (RHSCC) {
3930     default: llvm_unreachable("Unknown integer condition code!");
3931     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3932     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3933     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3934       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3935     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3936     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3937     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3938       return ReplaceInstUsesWith(I, LHS);
3939     }
3940   case ICmpInst::ICMP_NE:
3941     switch (RHSCC) {
3942     default: llvm_unreachable("Unknown integer condition code!");
3943     case ICmpInst::ICMP_ULT:
3944       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3945         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3946       break;                        // (X != 13 & X u< 15) -> no change
3947     case ICmpInst::ICMP_SLT:
3948       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3949         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3950       break;                        // (X != 13 & X s< 15) -> no change
3951     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3952     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3953     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3954       return ReplaceInstUsesWith(I, RHS);
3955     case ICmpInst::ICMP_NE:
3956       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3957         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3958         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
3959         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3960                             ConstantInt::get(Add->getType(), 1));
3961       }
3962       break;                        // (X != 13 & X != 15) -> no change
3963     }
3964     break;
3965   case ICmpInst::ICMP_ULT:
3966     switch (RHSCC) {
3967     default: llvm_unreachable("Unknown integer condition code!");
3968     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3969     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3970       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3971     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3972       break;
3973     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3974     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3975       return ReplaceInstUsesWith(I, LHS);
3976     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3977       break;
3978     }
3979     break;
3980   case ICmpInst::ICMP_SLT:
3981     switch (RHSCC) {
3982     default: llvm_unreachable("Unknown integer condition code!");
3983     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3984     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3985       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3986     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3987       break;
3988     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3989     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3990       return ReplaceInstUsesWith(I, LHS);
3991     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3992       break;
3993     }
3994     break;
3995   case ICmpInst::ICMP_UGT:
3996     switch (RHSCC) {
3997     default: llvm_unreachable("Unknown integer condition code!");
3998     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3999     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
4000       return ReplaceInstUsesWith(I, RHS);
4001     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
4002       break;
4003     case ICmpInst::ICMP_NE:
4004       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4005         return new ICmpInst(LHSCC, Val, RHSCst);
4006       break;                        // (X u> 13 & X != 15) -> no change
4007     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
4008       return InsertRangeTest(Val, AddOne(LHSCst),
4009                              RHSCst, false, true, I);
4010     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
4011       break;
4012     }
4013     break;
4014   case ICmpInst::ICMP_SGT:
4015     switch (RHSCC) {
4016     default: llvm_unreachable("Unknown integer condition code!");
4017     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
4018     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
4019       return ReplaceInstUsesWith(I, RHS);
4020     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
4021       break;
4022     case ICmpInst::ICMP_NE:
4023       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4024         return new ICmpInst(LHSCC, Val, RHSCst);
4025       break;                        // (X s> 13 & X != 15) -> no change
4026     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
4027       return InsertRangeTest(Val, AddOne(LHSCst),
4028                              RHSCst, true, true, I);
4029     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
4030       break;
4031     }
4032     break;
4033   }
4034  
4035   return 0;
4036 }
4037
4038 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4039                                           FCmpInst *RHS) {
4040   
4041   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4042       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4043     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4044     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4045       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4046         // If either of the constants are nans, then the whole thing returns
4047         // false.
4048         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4049           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4050         return new FCmpInst(FCmpInst::FCMP_ORD,
4051                             LHS->getOperand(0), RHS->getOperand(0));
4052       }
4053     
4054     // Handle vector zeros.  This occurs because the canonical form of
4055     // "fcmp ord x,x" is "fcmp ord x, 0".
4056     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4057         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4058       return new FCmpInst(FCmpInst::FCMP_ORD,
4059                           LHS->getOperand(0), RHS->getOperand(0));
4060     return 0;
4061   }
4062   
4063   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4064   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4065   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4066   
4067   
4068   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4069     // Swap RHS operands to match LHS.
4070     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4071     std::swap(Op1LHS, Op1RHS);
4072   }
4073   
4074   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4075     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4076     if (Op0CC == Op1CC)
4077       return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4078     
4079     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
4080       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4081     if (Op0CC == FCmpInst::FCMP_TRUE)
4082       return ReplaceInstUsesWith(I, RHS);
4083     if (Op1CC == FCmpInst::FCMP_TRUE)
4084       return ReplaceInstUsesWith(I, LHS);
4085     
4086     bool Op0Ordered;
4087     bool Op1Ordered;
4088     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4089     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4090     if (Op1Pred == 0) {
4091       std::swap(LHS, RHS);
4092       std::swap(Op0Pred, Op1Pred);
4093       std::swap(Op0Ordered, Op1Ordered);
4094     }
4095     if (Op0Pred == 0) {
4096       // uno && ueq -> uno && (uno || eq) -> ueq
4097       // ord && olt -> ord && (ord && lt) -> olt
4098       if (Op0Ordered == Op1Ordered)
4099         return ReplaceInstUsesWith(I, RHS);
4100       
4101       // uno && oeq -> uno && (ord && eq) -> false
4102       // uno && ord -> false
4103       if (!Op0Ordered)
4104         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4105       // ord && ueq -> ord && (uno || eq) -> oeq
4106       return cast<Instruction>(getFCmpValue(true, Op1Pred,
4107                                             Op0LHS, Op0RHS, Context));
4108     }
4109   }
4110
4111   return 0;
4112 }
4113
4114
4115 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4116   bool Changed = SimplifyCommutative(I);
4117   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4118
4119   if (isa<UndefValue>(Op1))                         // X & undef -> 0
4120     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4121
4122   // and X, X = X
4123   if (Op0 == Op1)
4124     return ReplaceInstUsesWith(I, Op1);
4125
4126   // See if we can simplify any instructions used by the instruction whose sole 
4127   // purpose is to compute bits we don't care about.
4128   if (SimplifyDemandedInstructionBits(I))
4129     return &I;
4130   if (isa<VectorType>(I.getType())) {
4131     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4132       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
4133         return ReplaceInstUsesWith(I, I.getOperand(0));
4134     } else if (isa<ConstantAggregateZero>(Op1)) {
4135       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
4136     }
4137   }
4138
4139   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4140     const APInt &AndRHSMask = AndRHS->getValue();
4141     APInt NotAndRHS(~AndRHSMask);
4142
4143     // Optimize a variety of ((val OP C1) & C2) combinations...
4144     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4145       Value *Op0LHS = Op0I->getOperand(0);
4146       Value *Op0RHS = Op0I->getOperand(1);
4147       switch (Op0I->getOpcode()) {
4148       default: break;
4149       case Instruction::Xor:
4150       case Instruction::Or:
4151         // If the mask is only needed on one incoming arm, push it up.
4152         if (!Op0I->hasOneUse()) break;
4153           
4154         if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4155           // Not masking anything out for the LHS, move to RHS.
4156           Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4157                                              Op0RHS->getName()+".masked");
4158           return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4159         }
4160         if (!isa<Constant>(Op0RHS) &&
4161             MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4162           // Not masking anything out for the RHS, move to LHS.
4163           Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4164                                              Op0LHS->getName()+".masked");
4165           return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
4166         }
4167
4168         break;
4169       case Instruction::Add:
4170         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4171         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4172         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4173         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4174           return BinaryOperator::CreateAnd(V, AndRHS);
4175         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4176           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4177         break;
4178
4179       case Instruction::Sub:
4180         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4181         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4182         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4183         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4184           return BinaryOperator::CreateAnd(V, AndRHS);
4185
4186         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4187         // has 1's for all bits that the subtraction with A might affect.
4188         if (Op0I->hasOneUse()) {
4189           uint32_t BitWidth = AndRHSMask.getBitWidth();
4190           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4191           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4192
4193           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4194           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4195               MaskedValueIsZero(Op0LHS, Mask)) {
4196             Value *NewNeg = Builder->CreateNeg(Op0RHS);
4197             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4198           }
4199         }
4200         break;
4201
4202       case Instruction::Shl:
4203       case Instruction::LShr:
4204         // (1 << x) & 1 --> zext(x == 0)
4205         // (1 >> x) & 1 --> zext(x == 0)
4206         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4207           Value *NewICmp =
4208             Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
4209           return new ZExtInst(NewICmp, I.getType());
4210         }
4211         break;
4212       }
4213
4214       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4215         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4216           return Res;
4217     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4218       // If this is an integer truncation or change from signed-to-unsigned, and
4219       // if the source is an and/or with immediate, transform it.  This
4220       // frequently occurs for bitfield accesses.
4221       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4222         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4223             CastOp->getNumOperands() == 2)
4224           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4225             if (CastOp->getOpcode() == Instruction::And) {
4226               // Change: and (cast (and X, C1) to T), C2
4227               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4228               // This will fold the two constants together, which may allow 
4229               // other simplifications.
4230               Value *NewCast = Builder->CreateTruncOrBitCast(
4231                 CastOp->getOperand(0), I.getType(), 
4232                 CastOp->getName()+".shrunk");
4233               // trunc_or_bitcast(C1)&C2
4234               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4235               C3 = ConstantExpr::getAnd(C3, AndRHS);
4236               return BinaryOperator::CreateAnd(NewCast, C3);
4237             } else if (CastOp->getOpcode() == Instruction::Or) {
4238               // Change: and (cast (or X, C1) to T), C2
4239               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4240               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4241               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
4242                 // trunc(C1)&C2
4243                 return ReplaceInstUsesWith(I, AndRHS);
4244             }
4245           }
4246       }
4247     }
4248
4249     // Try to fold constant and into select arguments.
4250     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4251       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4252         return R;
4253     if (isa<PHINode>(Op0))
4254       if (Instruction *NV = FoldOpIntoPhi(I))
4255         return NV;
4256   }
4257
4258   Value *Op0NotVal = dyn_castNotVal(Op0);
4259   Value *Op1NotVal = dyn_castNotVal(Op1);
4260
4261   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4262     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4263
4264   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4265   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4266     Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4267                                   I.getName()+".demorgan");
4268     return BinaryOperator::CreateNot(Or);
4269   }
4270   
4271   {
4272     Value *A = 0, *B = 0, *C = 0, *D = 0;
4273     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4274       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4275         return ReplaceInstUsesWith(I, Op1);
4276     
4277       // (A|B) & ~(A&B) -> A^B
4278       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4279         if ((A == C && B == D) || (A == D && B == C))
4280           return BinaryOperator::CreateXor(A, B);
4281       }
4282     }
4283     
4284     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4285       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4286         return ReplaceInstUsesWith(I, Op0);
4287
4288       // ~(A&B) & (A|B) -> A^B
4289       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4290         if ((A == C && B == D) || (A == D && B == C))
4291           return BinaryOperator::CreateXor(A, B);
4292       }
4293     }
4294     
4295     if (Op0->hasOneUse() &&
4296         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4297       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4298         I.swapOperands();     // Simplify below
4299         std::swap(Op0, Op1);
4300       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4301         cast<BinaryOperator>(Op0)->swapOperands();
4302         I.swapOperands();     // Simplify below
4303         std::swap(Op0, Op1);
4304       }
4305     }
4306
4307     if (Op1->hasOneUse() &&
4308         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4309       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4310         cast<BinaryOperator>(Op1)->swapOperands();
4311         std::swap(A, B);
4312       }
4313       if (A == Op0)                                // A&(A^B) -> A & ~B
4314         return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
4315     }
4316
4317     // (A&((~A)|B)) -> A&B
4318     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4319         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4320       return BinaryOperator::CreateAnd(A, Op1);
4321     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4322         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4323       return BinaryOperator::CreateAnd(A, Op0);
4324   }
4325   
4326   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4327     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4328     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4329       return R;
4330
4331     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4332       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4333         return Res;
4334   }
4335
4336   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4337   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4338     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4339       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4340         const Type *SrcTy = Op0C->getOperand(0)->getType();
4341         if (SrcTy == Op1C->getOperand(0)->getType() &&
4342             SrcTy->isIntOrIntVector() &&
4343             // Only do this if the casts both really cause code to be generated.
4344             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4345                               I.getType(), TD) &&
4346             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4347                               I.getType(), TD)) {
4348           Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4349                                             Op1C->getOperand(0), I.getName());
4350           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4351         }
4352       }
4353     
4354   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4355   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4356     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4357       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4358           SI0->getOperand(1) == SI1->getOperand(1) &&
4359           (SI0->hasOneUse() || SI1->hasOneUse())) {
4360         Value *NewOp =
4361           Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4362                              SI0->getName());
4363         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4364                                       SI1->getOperand(1));
4365       }
4366   }
4367
4368   // If and'ing two fcmp, try combine them into one.
4369   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4370     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4371       if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4372         return Res;
4373   }
4374
4375   return Changed ? &I : 0;
4376 }
4377
4378 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4379 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4380 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4381 /// the expression came from the corresponding "byte swapped" byte in some other
4382 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4383 /// we know that the expression deposits the low byte of %X into the high byte
4384 /// of the bswap result and that all other bytes are zero.  This expression is
4385 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4386 /// match.
4387 ///
4388 /// This function returns true if the match was unsuccessful and false if so.
4389 /// On entry to the function the "OverallLeftShift" is a signed integer value
4390 /// indicating the number of bytes that the subexpression is later shifted.  For
4391 /// example, if the expression is later right shifted by 16 bits, the
4392 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4393 /// byte of ByteValues is actually being set.
4394 ///
4395 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4396 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4397 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4398 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4399 /// always in the local (OverallLeftShift) coordinate space.
4400 ///
4401 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4402                               SmallVector<Value*, 8> &ByteValues) {
4403   if (Instruction *I = dyn_cast<Instruction>(V)) {
4404     // If this is an or instruction, it may be an inner node of the bswap.
4405     if (I->getOpcode() == Instruction::Or) {
4406       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4407                                ByteValues) ||
4408              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4409                                ByteValues);
4410     }
4411   
4412     // If this is a logical shift by a constant multiple of 8, recurse with
4413     // OverallLeftShift and ByteMask adjusted.
4414     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4415       unsigned ShAmt = 
4416         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4417       // Ensure the shift amount is defined and of a byte value.
4418       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4419         return true;
4420
4421       unsigned ByteShift = ShAmt >> 3;
4422       if (I->getOpcode() == Instruction::Shl) {
4423         // X << 2 -> collect(X, +2)
4424         OverallLeftShift += ByteShift;
4425         ByteMask >>= ByteShift;
4426       } else {
4427         // X >>u 2 -> collect(X, -2)
4428         OverallLeftShift -= ByteShift;
4429         ByteMask <<= ByteShift;
4430         ByteMask &= (~0U >> (32-ByteValues.size()));
4431       }
4432
4433       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4434       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4435
4436       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4437                                ByteValues);
4438     }
4439
4440     // If this is a logical 'and' with a mask that clears bytes, clear the
4441     // corresponding bytes in ByteMask.
4442     if (I->getOpcode() == Instruction::And &&
4443         isa<ConstantInt>(I->getOperand(1))) {
4444       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4445       unsigned NumBytes = ByteValues.size();
4446       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4447       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4448       
4449       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4450         // If this byte is masked out by a later operation, we don't care what
4451         // the and mask is.
4452         if ((ByteMask & (1 << i)) == 0)
4453           continue;
4454         
4455         // If the AndMask is all zeros for this byte, clear the bit.
4456         APInt MaskB = AndMask & Byte;
4457         if (MaskB == 0) {
4458           ByteMask &= ~(1U << i);
4459           continue;
4460         }
4461         
4462         // If the AndMask is not all ones for this byte, it's not a bytezap.
4463         if (MaskB != Byte)
4464           return true;
4465
4466         // Otherwise, this byte is kept.
4467       }
4468
4469       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4470                                ByteValues);
4471     }
4472   }
4473   
4474   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4475   // the input value to the bswap.  Some observations: 1) if more than one byte
4476   // is demanded from this input, then it could not be successfully assembled
4477   // into a byteswap.  At least one of the two bytes would not be aligned with
4478   // their ultimate destination.
4479   if (!isPowerOf2_32(ByteMask)) return true;
4480   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4481   
4482   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4483   // is demanded, it needs to go into byte 0 of the result.  This means that the
4484   // byte needs to be shifted until it lands in the right byte bucket.  The
4485   // shift amount depends on the position: if the byte is coming from the high
4486   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4487   // low part, it must be shifted left.
4488   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4489   if (InputByteNo < ByteValues.size()/2) {
4490     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4491       return true;
4492   } else {
4493     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4494       return true;
4495   }
4496   
4497   // If the destination byte value is already defined, the values are or'd
4498   // together, which isn't a bswap (unless it's an or of the same bits).
4499   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4500     return true;
4501   ByteValues[DestByteNo] = V;
4502   return false;
4503 }
4504
4505 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4506 /// If so, insert the new bswap intrinsic and return it.
4507 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4508   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4509   if (!ITy || ITy->getBitWidth() % 16 || 
4510       // ByteMask only allows up to 32-byte values.
4511       ITy->getBitWidth() > 32*8) 
4512     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4513   
4514   /// ByteValues - For each byte of the result, we keep track of which value
4515   /// defines each byte.
4516   SmallVector<Value*, 8> ByteValues;
4517   ByteValues.resize(ITy->getBitWidth()/8);
4518     
4519   // Try to find all the pieces corresponding to the bswap.
4520   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4521   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4522     return 0;
4523   
4524   // Check to see if all of the bytes come from the same value.
4525   Value *V = ByteValues[0];
4526   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4527   
4528   // Check to make sure that all of the bytes come from the same value.
4529   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4530     if (ByteValues[i] != V)
4531       return 0;
4532   const Type *Tys[] = { ITy };
4533   Module *M = I.getParent()->getParent()->getParent();
4534   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4535   return CallInst::Create(F, V);
4536 }
4537
4538 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4539 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4540 /// we can simplify this expression to "cond ? C : D or B".
4541 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4542                                          Value *C, Value *D,
4543                                          LLVMContext *Context) {
4544   // If A is not a select of -1/0, this cannot match.
4545   Value *Cond = 0;
4546   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4547     return 0;
4548
4549   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4550   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4551     return SelectInst::Create(Cond, C, B);
4552   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4553     return SelectInst::Create(Cond, C, B);
4554   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4555   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4556     return SelectInst::Create(Cond, C, D);
4557   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4558     return SelectInst::Create(Cond, C, D);
4559   return 0;
4560 }
4561
4562 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4563 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4564                                          ICmpInst *LHS, ICmpInst *RHS) {
4565   Value *Val, *Val2;
4566   ConstantInt *LHSCst, *RHSCst;
4567   ICmpInst::Predicate LHSCC, RHSCC;
4568   
4569   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4570   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4571              m_ConstantInt(LHSCst))) ||
4572       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4573              m_ConstantInt(RHSCst))))
4574     return 0;
4575   
4576   // From here on, we only handle:
4577   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4578   if (Val != Val2) return 0;
4579   
4580   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4581   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4582       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4583       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4584       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4585     return 0;
4586   
4587   // We can't fold (ugt x, C) | (sgt x, C2).
4588   if (!PredicatesFoldable(LHSCC, RHSCC))
4589     return 0;
4590   
4591   // Ensure that the larger constant is on the RHS.
4592   bool ShouldSwap;
4593   if (ICmpInst::isSignedPredicate(LHSCC) ||
4594       (ICmpInst::isEquality(LHSCC) && 
4595        ICmpInst::isSignedPredicate(RHSCC)))
4596     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4597   else
4598     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4599   
4600   if (ShouldSwap) {
4601     std::swap(LHS, RHS);
4602     std::swap(LHSCst, RHSCst);
4603     std::swap(LHSCC, RHSCC);
4604   }
4605   
4606   // At this point, we know we have have two icmp instructions
4607   // comparing a value against two constants and or'ing the result
4608   // together.  Because of the above check, we know that we only have
4609   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4610   // FoldICmpLogical check above), that the two constants are not
4611   // equal.
4612   assert(LHSCst != RHSCst && "Compares not folded above?");
4613
4614   switch (LHSCC) {
4615   default: llvm_unreachable("Unknown integer condition code!");
4616   case ICmpInst::ICMP_EQ:
4617     switch (RHSCC) {
4618     default: llvm_unreachable("Unknown integer condition code!");
4619     case ICmpInst::ICMP_EQ:
4620       if (LHSCst == SubOne(RHSCst)) {
4621         // (X == 13 | X == 14) -> X-13 <u 2
4622         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4623         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
4624         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4625         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4626       }
4627       break;                         // (X == 13 | X == 15) -> no change
4628     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4629     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4630       break;
4631     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4632     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4633     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4634       return ReplaceInstUsesWith(I, RHS);
4635     }
4636     break;
4637   case ICmpInst::ICMP_NE:
4638     switch (RHSCC) {
4639     default: llvm_unreachable("Unknown integer condition code!");
4640     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4641     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4642     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4643       return ReplaceInstUsesWith(I, LHS);
4644     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4645     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4646     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4647       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4648     }
4649     break;
4650   case ICmpInst::ICMP_ULT:
4651     switch (RHSCC) {
4652     default: llvm_unreachable("Unknown integer condition code!");
4653     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4654       break;
4655     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4656       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4657       // this can cause overflow.
4658       if (RHSCst->isMaxValue(false))
4659         return ReplaceInstUsesWith(I, LHS);
4660       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4661                              false, false, I);
4662     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4663       break;
4664     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4665     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4666       return ReplaceInstUsesWith(I, RHS);
4667     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4668       break;
4669     }
4670     break;
4671   case ICmpInst::ICMP_SLT:
4672     switch (RHSCC) {
4673     default: llvm_unreachable("Unknown integer condition code!");
4674     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4675       break;
4676     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4677       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4678       // this can cause overflow.
4679       if (RHSCst->isMaxValue(true))
4680         return ReplaceInstUsesWith(I, LHS);
4681       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4682                              true, false, I);
4683     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4684       break;
4685     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4686     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4687       return ReplaceInstUsesWith(I, RHS);
4688     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4689       break;
4690     }
4691     break;
4692   case ICmpInst::ICMP_UGT:
4693     switch (RHSCC) {
4694     default: llvm_unreachable("Unknown integer condition code!");
4695     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4696     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4697       return ReplaceInstUsesWith(I, LHS);
4698     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4699       break;
4700     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4701     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4702       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4703     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4704       break;
4705     }
4706     break;
4707   case ICmpInst::ICMP_SGT:
4708     switch (RHSCC) {
4709     default: llvm_unreachable("Unknown integer condition code!");
4710     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4711     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4712       return ReplaceInstUsesWith(I, LHS);
4713     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4714       break;
4715     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4716     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4717       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4718     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4719       break;
4720     }
4721     break;
4722   }
4723   return 0;
4724 }
4725
4726 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4727                                          FCmpInst *RHS) {
4728   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4729       RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4730       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4731     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4732       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4733         // If either of the constants are nans, then the whole thing returns
4734         // true.
4735         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4736           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4737         
4738         // Otherwise, no need to compare the two constants, compare the
4739         // rest.
4740         return new FCmpInst(FCmpInst::FCMP_UNO,
4741                             LHS->getOperand(0), RHS->getOperand(0));
4742       }
4743     
4744     // Handle vector zeros.  This occurs because the canonical form of
4745     // "fcmp uno x,x" is "fcmp uno x, 0".
4746     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4747         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4748       return new FCmpInst(FCmpInst::FCMP_UNO,
4749                           LHS->getOperand(0), RHS->getOperand(0));
4750     
4751     return 0;
4752   }
4753   
4754   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4755   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4756   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4757   
4758   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4759     // Swap RHS operands to match LHS.
4760     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4761     std::swap(Op1LHS, Op1RHS);
4762   }
4763   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4764     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4765     if (Op0CC == Op1CC)
4766       return new FCmpInst((FCmpInst::Predicate)Op0CC,
4767                           Op0LHS, Op0RHS);
4768     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
4769       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4770     if (Op0CC == FCmpInst::FCMP_FALSE)
4771       return ReplaceInstUsesWith(I, RHS);
4772     if (Op1CC == FCmpInst::FCMP_FALSE)
4773       return ReplaceInstUsesWith(I, LHS);
4774     bool Op0Ordered;
4775     bool Op1Ordered;
4776     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4777     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4778     if (Op0Ordered == Op1Ordered) {
4779       // If both are ordered or unordered, return a new fcmp with
4780       // or'ed predicates.
4781       Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4782                                Op0LHS, Op0RHS, Context);
4783       if (Instruction *I = dyn_cast<Instruction>(RV))
4784         return I;
4785       // Otherwise, it's a constant boolean value...
4786       return ReplaceInstUsesWith(I, RV);
4787     }
4788   }
4789   return 0;
4790 }
4791
4792 /// FoldOrWithConstants - This helper function folds:
4793 ///
4794 ///     ((A | B) & C1) | (B & C2)
4795 ///
4796 /// into:
4797 /// 
4798 ///     (A & C1) | B
4799 ///
4800 /// when the XOR of the two constants is "all ones" (-1).
4801 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4802                                                Value *A, Value *B, Value *C) {
4803   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4804   if (!CI1) return 0;
4805
4806   Value *V1 = 0;
4807   ConstantInt *CI2 = 0;
4808   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4809
4810   APInt Xor = CI1->getValue() ^ CI2->getValue();
4811   if (!Xor.isAllOnesValue()) return 0;
4812
4813   if (V1 == A || V1 == B) {
4814     Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
4815     return BinaryOperator::CreateOr(NewOp, V1);
4816   }
4817
4818   return 0;
4819 }
4820
4821 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4822   bool Changed = SimplifyCommutative(I);
4823   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4824
4825   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4826     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4827
4828   // or X, X = X
4829   if (Op0 == Op1)
4830     return ReplaceInstUsesWith(I, Op0);
4831
4832   // See if we can simplify any instructions used by the instruction whose sole 
4833   // purpose is to compute bits we don't care about.
4834   if (SimplifyDemandedInstructionBits(I))
4835     return &I;
4836   if (isa<VectorType>(I.getType())) {
4837     if (isa<ConstantAggregateZero>(Op1)) {
4838       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4839     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4840       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4841         return ReplaceInstUsesWith(I, I.getOperand(1));
4842     }
4843   }
4844
4845   // or X, -1 == -1
4846   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4847     ConstantInt *C1 = 0; Value *X = 0;
4848     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4849     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
4850         isOnlyUse(Op0)) {
4851       Value *Or = Builder->CreateOr(X, RHS);
4852       Or->takeName(Op0);
4853       return BinaryOperator::CreateAnd(Or, 
4854                ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
4855     }
4856
4857     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4858     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
4859         isOnlyUse(Op0)) {
4860       Value *Or = Builder->CreateOr(X, RHS);
4861       Or->takeName(Op0);
4862       return BinaryOperator::CreateXor(Or,
4863                  ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
4864     }
4865
4866     // Try to fold constant and into select arguments.
4867     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4868       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4869         return R;
4870     if (isa<PHINode>(Op0))
4871       if (Instruction *NV = FoldOpIntoPhi(I))
4872         return NV;
4873   }
4874
4875   Value *A = 0, *B = 0;
4876   ConstantInt *C1 = 0, *C2 = 0;
4877
4878   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4879     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4880       return ReplaceInstUsesWith(I, Op1);
4881   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4882     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4883       return ReplaceInstUsesWith(I, Op0);
4884
4885   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4886   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4887   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4888       match(Op1, m_Or(m_Value(), m_Value())) ||
4889       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4890        match(Op1, m_Shift(m_Value(), m_Value())))) {
4891     if (Instruction *BSwap = MatchBSwap(I))
4892       return BSwap;
4893   }
4894   
4895   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4896   if (Op0->hasOneUse() &&
4897       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4898       MaskedValueIsZero(Op1, C1->getValue())) {
4899     Value *NOr = Builder->CreateOr(A, Op1);
4900     NOr->takeName(Op0);
4901     return BinaryOperator::CreateXor(NOr, C1);
4902   }
4903
4904   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4905   if (Op1->hasOneUse() &&
4906       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4907       MaskedValueIsZero(Op0, C1->getValue())) {
4908     Value *NOr = Builder->CreateOr(A, Op0);
4909     NOr->takeName(Op0);
4910     return BinaryOperator::CreateXor(NOr, C1);
4911   }
4912
4913   // (A & C)|(B & D)
4914   Value *C = 0, *D = 0;
4915   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4916       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4917     Value *V1 = 0, *V2 = 0, *V3 = 0;
4918     C1 = dyn_cast<ConstantInt>(C);
4919     C2 = dyn_cast<ConstantInt>(D);
4920     if (C1 && C2) {  // (A & C1)|(B & C2)
4921       // If we have: ((V + N) & C1) | (V & C2)
4922       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4923       // replace with V+N.
4924       if (C1->getValue() == ~C2->getValue()) {
4925         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4926             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4927           // Add commutes, try both ways.
4928           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4929             return ReplaceInstUsesWith(I, A);
4930           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4931             return ReplaceInstUsesWith(I, A);
4932         }
4933         // Or commutes, try both ways.
4934         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4935             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4936           // Add commutes, try both ways.
4937           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4938             return ReplaceInstUsesWith(I, B);
4939           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4940             return ReplaceInstUsesWith(I, B);
4941         }
4942       }
4943       V1 = 0; V2 = 0; V3 = 0;
4944     }
4945     
4946     // Check to see if we have any common things being and'ed.  If so, find the
4947     // terms for V1 & (V2|V3).
4948     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4949       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4950         V1 = A, V2 = C, V3 = D;
4951       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4952         V1 = A, V2 = B, V3 = C;
4953       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4954         V1 = C, V2 = A, V3 = D;
4955       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4956         V1 = C, V2 = A, V3 = B;
4957       
4958       if (V1) {
4959         Value *Or = Builder->CreateOr(V2, V3, "tmp");
4960         return BinaryOperator::CreateAnd(V1, Or);
4961       }
4962     }
4963
4964     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4965     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4966       return Match;
4967     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4968       return Match;
4969     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4970       return Match;
4971     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4972       return Match;
4973
4974     // ((A&~B)|(~A&B)) -> A^B
4975     if ((match(C, m_Not(m_Specific(D))) &&
4976          match(B, m_Not(m_Specific(A)))))
4977       return BinaryOperator::CreateXor(A, D);
4978     // ((~B&A)|(~A&B)) -> A^B
4979     if ((match(A, m_Not(m_Specific(D))) &&
4980          match(B, m_Not(m_Specific(C)))))
4981       return BinaryOperator::CreateXor(C, D);
4982     // ((A&~B)|(B&~A)) -> A^B
4983     if ((match(C, m_Not(m_Specific(B))) &&
4984          match(D, m_Not(m_Specific(A)))))
4985       return BinaryOperator::CreateXor(A, B);
4986     // ((~B&A)|(B&~A)) -> A^B
4987     if ((match(A, m_Not(m_Specific(B))) &&
4988          match(D, m_Not(m_Specific(C)))))
4989       return BinaryOperator::CreateXor(C, B);
4990   }
4991   
4992   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4993   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4994     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4995       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4996           SI0->getOperand(1) == SI1->getOperand(1) &&
4997           (SI0->hasOneUse() || SI1->hasOneUse())) {
4998         Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4999                                          SI0->getName());
5000         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
5001                                       SI1->getOperand(1));
5002       }
5003   }
5004
5005   // ((A|B)&1)|(B&-2) -> (A&1) | B
5006   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5007       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
5008     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
5009     if (Ret) return Ret;
5010   }
5011   // (B&-2)|((A|B)&1) -> (A&1) | B
5012   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5013       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
5014     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
5015     if (Ret) return Ret;
5016   }
5017
5018   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
5019     if (A == Op1)   // ~A | A == -1
5020       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5021   } else {
5022     A = 0;
5023   }
5024   // Note, A is still live here!
5025   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
5026     if (Op0 == B)
5027       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5028
5029     // (~A | ~B) == (~(A & B)) - De Morgan's Law
5030     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
5031       Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
5032       return BinaryOperator::CreateNot(And);
5033     }
5034   }
5035
5036   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5037   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
5038     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5039       return R;
5040
5041     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5042       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5043         return Res;
5044   }
5045     
5046   // fold (or (cast A), (cast B)) -> (cast (or A, B))
5047   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5048     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5049       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
5050         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5051             !isa<ICmpInst>(Op1C->getOperand(0))) {
5052           const Type *SrcTy = Op0C->getOperand(0)->getType();
5053           if (SrcTy == Op1C->getOperand(0)->getType() &&
5054               SrcTy->isIntOrIntVector() &&
5055               // Only do this if the casts both really cause code to be
5056               // generated.
5057               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5058                                 I.getType(), TD) &&
5059               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5060                                 I.getType(), TD)) {
5061             Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5062                                              Op1C->getOperand(0), I.getName());
5063             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5064           }
5065         }
5066       }
5067   }
5068   
5069     
5070   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
5071   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
5072     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5073       if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5074         return Res;
5075   }
5076
5077   return Changed ? &I : 0;
5078 }
5079
5080 namespace {
5081
5082 // XorSelf - Implements: X ^ X --> 0
5083 struct XorSelf {
5084   Value *RHS;
5085   XorSelf(Value *rhs) : RHS(rhs) {}
5086   bool shouldApply(Value *LHS) const { return LHS == RHS; }
5087   Instruction *apply(BinaryOperator &Xor) const {
5088     return &Xor;
5089   }
5090 };
5091
5092 }
5093
5094 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5095   bool Changed = SimplifyCommutative(I);
5096   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5097
5098   if (isa<UndefValue>(Op1)) {
5099     if (isa<UndefValue>(Op0))
5100       // Handle undef ^ undef -> 0 special case. This is a common
5101       // idiom (misuse).
5102       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5103     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5104   }
5105
5106   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5107   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
5108     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5109     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5110   }
5111   
5112   // See if we can simplify any instructions used by the instruction whose sole 
5113   // purpose is to compute bits we don't care about.
5114   if (SimplifyDemandedInstructionBits(I))
5115     return &I;
5116   if (isa<VectorType>(I.getType()))
5117     if (isa<ConstantAggregateZero>(Op1))
5118       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5119
5120   // Is this a ~ operation?
5121   if (Value *NotOp = dyn_castNotVal(&I)) {
5122     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5123     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5124     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5125       if (Op0I->getOpcode() == Instruction::And || 
5126           Op0I->getOpcode() == Instruction::Or) {
5127         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5128         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5129           Value *NotY =
5130             Builder->CreateNot(Op0I->getOperand(1),
5131                                Op0I->getOperand(1)->getName()+".not");
5132           if (Op0I->getOpcode() == Instruction::And)
5133             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5134           return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5135         }
5136       }
5137     }
5138   }
5139   
5140   
5141   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5142     if (RHS->isOne() && Op0->hasOneUse()) {
5143       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5144       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5145         return new ICmpInst(ICI->getInversePredicate(),
5146                             ICI->getOperand(0), ICI->getOperand(1));
5147
5148       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5149         return new FCmpInst(FCI->getInversePredicate(),
5150                             FCI->getOperand(0), FCI->getOperand(1));
5151     }
5152
5153     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5154     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5155       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5156         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5157           Instruction::CastOps Opcode = Op0C->getOpcode();
5158           if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5159               (RHS == ConstantExpr::getCast(Opcode, 
5160                                             ConstantInt::getTrue(*Context),
5161                                             Op0C->getDestTy()))) {
5162             CI->setPredicate(CI->getInversePredicate());
5163             return CastInst::Create(Opcode, CI, Op0C->getType());
5164           }
5165         }
5166       }
5167     }
5168
5169     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5170       // ~(c-X) == X-c-1 == X+(-c-1)
5171       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5172         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5173           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5174           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5175                                       ConstantInt::get(I.getType(), 1));
5176           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5177         }
5178           
5179       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5180         if (Op0I->getOpcode() == Instruction::Add) {
5181           // ~(X-c) --> (-c-1)-X
5182           if (RHS->isAllOnesValue()) {
5183             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5184             return BinaryOperator::CreateSub(
5185                            ConstantExpr::getSub(NegOp0CI,
5186                                       ConstantInt::get(I.getType(), 1)),
5187                                       Op0I->getOperand(0));
5188           } else if (RHS->getValue().isSignBit()) {
5189             // (X + C) ^ signbit -> (X + C + signbit)
5190             Constant *C = ConstantInt::get(*Context,
5191                                            RHS->getValue() + Op0CI->getValue());
5192             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5193
5194           }
5195         } else if (Op0I->getOpcode() == Instruction::Or) {
5196           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5197           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5198             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5199             // Anything in both C1 and C2 is known to be zero, remove it from
5200             // NewRHS.
5201             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5202             NewRHS = ConstantExpr::getAnd(NewRHS, 
5203                                        ConstantExpr::getNot(CommonBits));
5204             Worklist.Add(Op0I);
5205             I.setOperand(0, Op0I->getOperand(0));
5206             I.setOperand(1, NewRHS);
5207             return &I;
5208           }
5209         }
5210       }
5211     }
5212
5213     // Try to fold constant and into select arguments.
5214     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5215       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5216         return R;
5217     if (isa<PHINode>(Op0))
5218       if (Instruction *NV = FoldOpIntoPhi(I))
5219         return NV;
5220   }
5221
5222   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
5223     if (X == Op1)
5224       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5225
5226   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5227     if (X == Op0)
5228       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5229
5230   
5231   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5232   if (Op1I) {
5233     Value *A, *B;
5234     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5235       if (A == Op0) {              // B^(B|A) == (A|B)^B
5236         Op1I->swapOperands();
5237         I.swapOperands();
5238         std::swap(Op0, Op1);
5239       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5240         I.swapOperands();     // Simplified below.
5241         std::swap(Op0, Op1);
5242       }
5243     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5244       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5245     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5246       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5247     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && 
5248                Op1I->hasOneUse()){
5249       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5250         Op1I->swapOperands();
5251         std::swap(A, B);
5252       }
5253       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5254         I.swapOperands();     // Simplified below.
5255         std::swap(Op0, Op1);
5256       }
5257     }
5258   }
5259   
5260   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5261   if (Op0I) {
5262     Value *A, *B;
5263     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5264         Op0I->hasOneUse()) {
5265       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5266         std::swap(A, B);
5267       if (B == Op1)                                  // (A|B)^B == A & ~B
5268         return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
5269     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5270       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5271     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5272       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5273     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && 
5274                Op0I->hasOneUse()){
5275       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5276         std::swap(A, B);
5277       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5278           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5279         return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
5280       }
5281     }
5282   }
5283   
5284   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5285   if (Op0I && Op1I && Op0I->isShift() && 
5286       Op0I->getOpcode() == Op1I->getOpcode() && 
5287       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5288       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5289     Value *NewOp =
5290       Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5291                          Op0I->getName());
5292     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5293                                   Op1I->getOperand(1));
5294   }
5295     
5296   if (Op0I && Op1I) {
5297     Value *A, *B, *C, *D;
5298     // (A & B)^(A | B) -> A ^ B
5299     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5300         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5301       if ((A == C && B == D) || (A == D && B == C)) 
5302         return BinaryOperator::CreateXor(A, B);
5303     }
5304     // (A | B)^(A & B) -> A ^ B
5305     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5306         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5307       if ((A == C && B == D) || (A == D && B == C)) 
5308         return BinaryOperator::CreateXor(A, B);
5309     }
5310     
5311     // (A & B)^(C & D)
5312     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5313         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5314         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5315       // (X & Y)^(X & Y) -> (Y^Z) & X
5316       Value *X = 0, *Y = 0, *Z = 0;
5317       if (A == C)
5318         X = A, Y = B, Z = D;
5319       else if (A == D)
5320         X = A, Y = B, Z = C;
5321       else if (B == C)
5322         X = B, Y = A, Z = D;
5323       else if (B == D)
5324         X = B, Y = A, Z = C;
5325       
5326       if (X) {
5327         Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
5328         return BinaryOperator::CreateAnd(NewOp, X);
5329       }
5330     }
5331   }
5332     
5333   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5334   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5335     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5336       return R;
5337
5338   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5339   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5340     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5341       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5342         const Type *SrcTy = Op0C->getOperand(0)->getType();
5343         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5344             // Only do this if the casts both really cause code to be generated.
5345             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5346                               I.getType(), TD) &&
5347             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5348                               I.getType(), TD)) {
5349           Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5350                                             Op1C->getOperand(0), I.getName());
5351           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5352         }
5353       }
5354   }
5355
5356   return Changed ? &I : 0;
5357 }
5358
5359 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5360                                    LLVMContext *Context) {
5361   return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5362 }
5363
5364 static bool HasAddOverflow(ConstantInt *Result,
5365                            ConstantInt *In1, ConstantInt *In2,
5366                            bool IsSigned) {
5367   if (IsSigned)
5368     if (In2->getValue().isNegative())
5369       return Result->getValue().sgt(In1->getValue());
5370     else
5371       return Result->getValue().slt(In1->getValue());
5372   else
5373     return Result->getValue().ult(In1->getValue());
5374 }
5375
5376 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5377 /// overflowed for this type.
5378 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5379                             Constant *In2, LLVMContext *Context,
5380                             bool IsSigned = false) {
5381   Result = ConstantExpr::getAdd(In1, In2);
5382
5383   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5384     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5385       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5386       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5387                          ExtractElement(In1, Idx, Context),
5388                          ExtractElement(In2, Idx, Context),
5389                          IsSigned))
5390         return true;
5391     }
5392     return false;
5393   }
5394
5395   return HasAddOverflow(cast<ConstantInt>(Result),
5396                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5397                         IsSigned);
5398 }
5399
5400 static bool HasSubOverflow(ConstantInt *Result,
5401                            ConstantInt *In1, ConstantInt *In2,
5402                            bool IsSigned) {
5403   if (IsSigned)
5404     if (In2->getValue().isNegative())
5405       return Result->getValue().slt(In1->getValue());
5406     else
5407       return Result->getValue().sgt(In1->getValue());
5408   else
5409     return Result->getValue().ugt(In1->getValue());
5410 }
5411
5412 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5413 /// overflowed for this type.
5414 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5415                             Constant *In2, LLVMContext *Context,
5416                             bool IsSigned = false) {
5417   Result = ConstantExpr::getSub(In1, In2);
5418
5419   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5420     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5421       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5422       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5423                          ExtractElement(In1, Idx, Context),
5424                          ExtractElement(In2, Idx, Context),
5425                          IsSigned))
5426         return true;
5427     }
5428     return false;
5429   }
5430
5431   return HasSubOverflow(cast<ConstantInt>(Result),
5432                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5433                         IsSigned);
5434 }
5435
5436 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5437 /// code necessary to compute the offset from the base pointer (without adding
5438 /// in the base pointer).  Return the result as a signed integer of intptr size.
5439 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5440   TargetData &TD = *IC.getTargetData();
5441   gep_type_iterator GTI = gep_type_begin(GEP);
5442   const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
5443   Value *Result = Constant::getNullValue(IntPtrTy);
5444
5445   // Build a mask for high order bits.
5446   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5447   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5448
5449   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5450        ++i, ++GTI) {
5451     Value *Op = *i;
5452     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5453     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5454       if (OpC->isZero()) continue;
5455       
5456       // Handle a struct index, which adds its field offset to the pointer.
5457       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5458         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5459         
5460         Result = IC.Builder->CreateAdd(Result,
5461                                        ConstantInt::get(IntPtrTy, Size),
5462                                        GEP->getName()+".offs");
5463         continue;
5464       }
5465       
5466       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5467       Constant *OC =
5468               ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5469       Scale = ConstantExpr::getMul(OC, Scale);
5470       // Emit an add instruction.
5471       Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
5472       continue;
5473     }
5474     // Convert to correct type.
5475     if (Op->getType() != IntPtrTy)
5476       Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
5477     if (Size != 1) {
5478       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5479       // We'll let instcombine(mul) convert this to a shl if possible.
5480       Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
5481     }
5482
5483     // Emit an add instruction.
5484     Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
5485   }
5486   return Result;
5487 }
5488
5489
5490 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5491 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
5492 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
5493 /// be complex, and scales are involved.  The above expression would also be
5494 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5495 /// This later form is less amenable to optimization though, and we are allowed
5496 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5497 ///
5498 /// If we can't emit an optimized form for this expression, this returns null.
5499 /// 
5500 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5501                                           InstCombiner &IC) {
5502   TargetData &TD = *IC.getTargetData();
5503   gep_type_iterator GTI = gep_type_begin(GEP);
5504
5505   // Check to see if this gep only has a single variable index.  If so, and if
5506   // any constant indices are a multiple of its scale, then we can compute this
5507   // in terms of the scale of the variable index.  For example, if the GEP
5508   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5509   // because the expression will cross zero at the same point.
5510   unsigned i, e = GEP->getNumOperands();
5511   int64_t Offset = 0;
5512   for (i = 1; i != e; ++i, ++GTI) {
5513     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5514       // Compute the aggregate offset of constant indices.
5515       if (CI->isZero()) continue;
5516
5517       // Handle a struct index, which adds its field offset to the pointer.
5518       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5519         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5520       } else {
5521         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5522         Offset += Size*CI->getSExtValue();
5523       }
5524     } else {
5525       // Found our variable index.
5526       break;
5527     }
5528   }
5529   
5530   // If there are no variable indices, we must have a constant offset, just
5531   // evaluate it the general way.
5532   if (i == e) return 0;
5533   
5534   Value *VariableIdx = GEP->getOperand(i);
5535   // Determine the scale factor of the variable element.  For example, this is
5536   // 4 if the variable index is into an array of i32.
5537   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5538   
5539   // Verify that there are no other variable indices.  If so, emit the hard way.
5540   for (++i, ++GTI; i != e; ++i, ++GTI) {
5541     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5542     if (!CI) return 0;
5543    
5544     // Compute the aggregate offset of constant indices.
5545     if (CI->isZero()) continue;
5546     
5547     // Handle a struct index, which adds its field offset to the pointer.
5548     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5549       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5550     } else {
5551       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5552       Offset += Size*CI->getSExtValue();
5553     }
5554   }
5555   
5556   // Okay, we know we have a single variable index, which must be a
5557   // pointer/array/vector index.  If there is no offset, life is simple, return
5558   // the index.
5559   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5560   if (Offset == 0) {
5561     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5562     // we don't need to bother extending: the extension won't affect where the
5563     // computation crosses zero.
5564     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5565       VariableIdx = new TruncInst(VariableIdx, 
5566                                   TD.getIntPtrType(VariableIdx->getContext()),
5567                                   VariableIdx->getName(), &I);
5568     return VariableIdx;
5569   }
5570   
5571   // Otherwise, there is an index.  The computation we will do will be modulo
5572   // the pointer size, so get it.
5573   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5574   
5575   Offset &= PtrSizeMask;
5576   VariableScale &= PtrSizeMask;
5577
5578   // To do this transformation, any constant index must be a multiple of the
5579   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5580   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5581   // multiple of the variable scale.
5582   int64_t NewOffs = Offset / (int64_t)VariableScale;
5583   if (Offset != NewOffs*(int64_t)VariableScale)
5584     return 0;
5585
5586   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5587   const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
5588   if (VariableIdx->getType() != IntPtrTy)
5589     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5590                                               true /*SExt*/, 
5591                                               VariableIdx->getName(), &I);
5592   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5593   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5594 }
5595
5596
5597 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5598 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5599 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
5600                                        ICmpInst::Predicate Cond,
5601                                        Instruction &I) {
5602   // Look through bitcasts.
5603   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5604     RHS = BCI->getOperand(0);
5605
5606   Value *PtrBase = GEPLHS->getOperand(0);
5607   if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
5608     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5609     // This transformation (ignoring the base and scales) is valid because we
5610     // know pointers can't overflow since the gep is inbounds.  See if we can
5611     // output an optimized form.
5612     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5613     
5614     // If not, synthesize the offset the hard way.
5615     if (Offset == 0)
5616       Offset = EmitGEPOffset(GEPLHS, I, *this);
5617     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5618                         Constant::getNullValue(Offset->getType()));
5619   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
5620     // If the base pointers are different, but the indices are the same, just
5621     // compare the base pointer.
5622     if (PtrBase != GEPRHS->getOperand(0)) {
5623       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5624       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5625                         GEPRHS->getOperand(0)->getType();
5626       if (IndicesTheSame)
5627         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5628           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5629             IndicesTheSame = false;
5630             break;
5631           }
5632
5633       // If all indices are the same, just compare the base pointers.
5634       if (IndicesTheSame)
5635         return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5636                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5637
5638       // Otherwise, the base pointers are different and the indices are
5639       // different, bail out.
5640       return 0;
5641     }
5642
5643     // If one of the GEPs has all zero indices, recurse.
5644     bool AllZeros = true;
5645     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5646       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5647           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5648         AllZeros = false;
5649         break;
5650       }
5651     if (AllZeros)
5652       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5653                           ICmpInst::getSwappedPredicate(Cond), I);
5654
5655     // If the other GEP has all zero indices, recurse.
5656     AllZeros = true;
5657     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5658       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5659           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5660         AllZeros = false;
5661         break;
5662       }
5663     if (AllZeros)
5664       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5665
5666     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5667       // If the GEPs only differ by one index, compare it.
5668       unsigned NumDifferences = 0;  // Keep track of # differences.
5669       unsigned DiffOperand = 0;     // The operand that differs.
5670       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5671         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5672           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5673                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5674             // Irreconcilable differences.
5675             NumDifferences = 2;
5676             break;
5677           } else {
5678             if (NumDifferences++) break;
5679             DiffOperand = i;
5680           }
5681         }
5682
5683       if (NumDifferences == 0)   // SAME GEP?
5684         return ReplaceInstUsesWith(I, // No comparison is needed here.
5685                                    ConstantInt::get(Type::getInt1Ty(*Context),
5686                                              ICmpInst::isTrueWhenEqual(Cond)));
5687
5688       else if (NumDifferences == 1) {
5689         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5690         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5691         // Make sure we do a signed comparison here.
5692         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5693       }
5694     }
5695
5696     // Only lower this if the icmp is the only user of the GEP or if we expect
5697     // the result to fold to a constant!
5698     if (TD &&
5699         (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5700         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5701       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5702       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5703       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5704       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5705     }
5706   }
5707   return 0;
5708 }
5709
5710 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5711 ///
5712 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5713                                                 Instruction *LHSI,
5714                                                 Constant *RHSC) {
5715   if (!isa<ConstantFP>(RHSC)) return 0;
5716   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5717   
5718   // Get the width of the mantissa.  We don't want to hack on conversions that
5719   // might lose information from the integer, e.g. "i64 -> float"
5720   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5721   if (MantissaWidth == -1) return 0;  // Unknown.
5722   
5723   // Check to see that the input is converted from an integer type that is small
5724   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5725   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5726   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5727   
5728   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5729   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5730   if (LHSUnsigned)
5731     ++InputSize;
5732   
5733   // If the conversion would lose info, don't hack on this.
5734   if ((int)InputSize > MantissaWidth)
5735     return 0;
5736   
5737   // Otherwise, we can potentially simplify the comparison.  We know that it
5738   // will always come through as an integer value and we know the constant is
5739   // not a NAN (it would have been previously simplified).
5740   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5741   
5742   ICmpInst::Predicate Pred;
5743   switch (I.getPredicate()) {
5744   default: llvm_unreachable("Unexpected predicate!");
5745   case FCmpInst::FCMP_UEQ:
5746   case FCmpInst::FCMP_OEQ:
5747     Pred = ICmpInst::ICMP_EQ;
5748     break;
5749   case FCmpInst::FCMP_UGT:
5750   case FCmpInst::FCMP_OGT:
5751     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5752     break;
5753   case FCmpInst::FCMP_UGE:
5754   case FCmpInst::FCMP_OGE:
5755     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5756     break;
5757   case FCmpInst::FCMP_ULT:
5758   case FCmpInst::FCMP_OLT:
5759     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5760     break;
5761   case FCmpInst::FCMP_ULE:
5762   case FCmpInst::FCMP_OLE:
5763     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5764     break;
5765   case FCmpInst::FCMP_UNE:
5766   case FCmpInst::FCMP_ONE:
5767     Pred = ICmpInst::ICMP_NE;
5768     break;
5769   case FCmpInst::FCMP_ORD:
5770     return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5771   case FCmpInst::FCMP_UNO:
5772     return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5773   }
5774   
5775   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5776   
5777   // Now we know that the APFloat is a normal number, zero or inf.
5778   
5779   // See if the FP constant is too large for the integer.  For example,
5780   // comparing an i8 to 300.0.
5781   unsigned IntWidth = IntTy->getScalarSizeInBits();
5782   
5783   if (!LHSUnsigned) {
5784     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5785     // and large values.
5786     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5787     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5788                           APFloat::rmNearestTiesToEven);
5789     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5790       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5791           Pred == ICmpInst::ICMP_SLE)
5792         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5793       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5794     }
5795   } else {
5796     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5797     // +INF and large values.
5798     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5799     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5800                           APFloat::rmNearestTiesToEven);
5801     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5802       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5803           Pred == ICmpInst::ICMP_ULE)
5804         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5805       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5806     }
5807   }
5808   
5809   if (!LHSUnsigned) {
5810     // See if the RHS value is < SignedMin.
5811     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5812     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5813                           APFloat::rmNearestTiesToEven);
5814     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5815       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5816           Pred == ICmpInst::ICMP_SGE)
5817         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5818       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5819     }
5820   }
5821
5822   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5823   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5824   // casting the FP value to the integer value and back, checking for equality.
5825   // Don't do this for zero, because -0.0 is not fractional.
5826   Constant *RHSInt = LHSUnsigned
5827     ? ConstantExpr::getFPToUI(RHSC, IntTy)
5828     : ConstantExpr::getFPToSI(RHSC, IntTy);
5829   if (!RHS.isZero()) {
5830     bool Equal = LHSUnsigned
5831       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5832       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5833     if (!Equal) {
5834       // If we had a comparison against a fractional value, we have to adjust
5835       // the compare predicate and sometimes the value.  RHSC is rounded towards
5836       // zero at this point.
5837       switch (Pred) {
5838       default: llvm_unreachable("Unexpected integer comparison!");
5839       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5840         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5841       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5842         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5843       case ICmpInst::ICMP_ULE:
5844         // (float)int <= 4.4   --> int <= 4
5845         // (float)int <= -4.4  --> false
5846         if (RHS.isNegative())
5847           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5848         break;
5849       case ICmpInst::ICMP_SLE:
5850         // (float)int <= 4.4   --> int <= 4
5851         // (float)int <= -4.4  --> int < -4
5852         if (RHS.isNegative())
5853           Pred = ICmpInst::ICMP_SLT;
5854         break;
5855       case ICmpInst::ICMP_ULT:
5856         // (float)int < -4.4   --> false
5857         // (float)int < 4.4    --> int <= 4
5858         if (RHS.isNegative())
5859           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5860         Pred = ICmpInst::ICMP_ULE;
5861         break;
5862       case ICmpInst::ICMP_SLT:
5863         // (float)int < -4.4   --> int < -4
5864         // (float)int < 4.4    --> int <= 4
5865         if (!RHS.isNegative())
5866           Pred = ICmpInst::ICMP_SLE;
5867         break;
5868       case ICmpInst::ICMP_UGT:
5869         // (float)int > 4.4    --> int > 4
5870         // (float)int > -4.4   --> true
5871         if (RHS.isNegative())
5872           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5873         break;
5874       case ICmpInst::ICMP_SGT:
5875         // (float)int > 4.4    --> int > 4
5876         // (float)int > -4.4   --> int >= -4
5877         if (RHS.isNegative())
5878           Pred = ICmpInst::ICMP_SGE;
5879         break;
5880       case ICmpInst::ICMP_UGE:
5881         // (float)int >= -4.4   --> true
5882         // (float)int >= 4.4    --> int > 4
5883         if (!RHS.isNegative())
5884           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5885         Pred = ICmpInst::ICMP_UGT;
5886         break;
5887       case ICmpInst::ICMP_SGE:
5888         // (float)int >= -4.4   --> int >= -4
5889         // (float)int >= 4.4    --> int > 4
5890         if (!RHS.isNegative())
5891           Pred = ICmpInst::ICMP_SGT;
5892         break;
5893       }
5894     }
5895   }
5896
5897   // Lower this FP comparison into an appropriate integer version of the
5898   // comparison.
5899   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5900 }
5901
5902 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5903   bool Changed = SimplifyCompare(I);
5904   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5905
5906   // Fold trivial predicates.
5907   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5908     return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
5909   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5910     return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
5911   
5912   // Simplify 'fcmp pred X, X'
5913   if (Op0 == Op1) {
5914     switch (I.getPredicate()) {
5915     default: llvm_unreachable("Unknown predicate!");
5916     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5917     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5918     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5919       return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
5920     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5921     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5922     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5923       return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
5924       
5925     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5926     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5927     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5928     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5929       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5930       I.setPredicate(FCmpInst::FCMP_UNO);
5931       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5932       return &I;
5933       
5934     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5935     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5936     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5937     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5938       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5939       I.setPredicate(FCmpInst::FCMP_ORD);
5940       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5941       return &I;
5942     }
5943   }
5944     
5945   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5946     return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
5947
5948   // Handle fcmp with constant RHS
5949   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5950     // If the constant is a nan, see if we can fold the comparison based on it.
5951     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5952       if (CFP->getValueAPF().isNaN()) {
5953         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5954           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5955         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5956                "Comparison must be either ordered or unordered!");
5957         // True if unordered.
5958         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5959       }
5960     }
5961     
5962     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5963       switch (LHSI->getOpcode()) {
5964       case Instruction::PHI:
5965         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5966         // block.  If in the same block, we're encouraging jump threading.  If
5967         // not, we are just pessimizing the code by making an i1 phi.
5968         if (LHSI->getParent() == I.getParent())
5969           if (Instruction *NV = FoldOpIntoPhi(I, true))
5970             return NV;
5971         break;
5972       case Instruction::SIToFP:
5973       case Instruction::UIToFP:
5974         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5975           return NV;
5976         break;
5977       case Instruction::Select:
5978         // If either operand of the select is a constant, we can fold the
5979         // comparison into the select arms, which will cause one to be
5980         // constant folded and the select turned into a bitwise or.
5981         Value *Op1 = 0, *Op2 = 0;
5982         if (LHSI->hasOneUse()) {
5983           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5984             // Fold the known value into the constant operand.
5985             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5986             // Insert a new FCmp of the other select operand.
5987             Op2 = Builder->CreateFCmp(I.getPredicate(),
5988                                       LHSI->getOperand(2), RHSC, I.getName());
5989           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5990             // Fold the known value into the constant operand.
5991             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5992             // Insert a new FCmp of the other select operand.
5993             Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5994                                       RHSC, I.getName());
5995           }
5996         }
5997
5998         if (Op1)
5999           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6000         break;
6001       }
6002   }
6003
6004   return Changed ? &I : 0;
6005 }
6006
6007 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
6008   bool Changed = SimplifyCompare(I);
6009   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6010   const Type *Ty = Op0->getType();
6011
6012   // icmp X, X
6013   if (Op0 == Op1)
6014     return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(),
6015                                                    I.isTrueWhenEqual()));
6016
6017   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
6018     return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
6019   
6020   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
6021   // addresses never equal each other!  We already know that Op0 != Op1.
6022   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) || 
6023        isa<ConstantPointerNull>(Op0)) &&
6024       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) || 
6025        isa<ConstantPointerNull>(Op1)))
6026     return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context), 
6027                                                    !I.isTrueWhenEqual()));
6028
6029   // icmp's with boolean values can always be turned into bitwise operations
6030   if (Ty == Type::getInt1Ty(*Context)) {
6031     switch (I.getPredicate()) {
6032     default: llvm_unreachable("Invalid icmp instruction!");
6033     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
6034       Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
6035       return BinaryOperator::CreateNot(Xor);
6036     }
6037     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
6038       return BinaryOperator::CreateXor(Op0, Op1);
6039
6040     case ICmpInst::ICMP_UGT:
6041       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
6042       // FALL THROUGH
6043     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
6044       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
6045       return BinaryOperator::CreateAnd(Not, Op1);
6046     }
6047     case ICmpInst::ICMP_SGT:
6048       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
6049       // FALL THROUGH
6050     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
6051       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
6052       return BinaryOperator::CreateAnd(Not, Op0);
6053     }
6054     case ICmpInst::ICMP_UGE:
6055       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6056       // FALL THROUGH
6057     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6058       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
6059       return BinaryOperator::CreateOr(Not, Op1);
6060     }
6061     case ICmpInst::ICMP_SGE:
6062       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6063       // FALL THROUGH
6064     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6065       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
6066       return BinaryOperator::CreateOr(Not, Op0);
6067     }
6068     }
6069   }
6070
6071   unsigned BitWidth = 0;
6072   if (TD)
6073     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6074   else if (Ty->isIntOrIntVector())
6075     BitWidth = Ty->getScalarSizeInBits();
6076
6077   bool isSignBit = false;
6078
6079   // See if we are doing a comparison with a constant.
6080   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6081     Value *A = 0, *B = 0;
6082     
6083     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6084     if (I.isEquality() && CI->isNullValue() &&
6085         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
6086       // (icmp cond A B) if cond is equality
6087       return new ICmpInst(I.getPredicate(), A, B);
6088     }
6089     
6090     // If we have an icmp le or icmp ge instruction, turn it into the
6091     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6092     // them being folded in the code below.
6093     switch (I.getPredicate()) {
6094     default: break;
6095     case ICmpInst::ICMP_ULE:
6096       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
6097         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6098       return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
6099                           AddOne(CI));
6100     case ICmpInst::ICMP_SLE:
6101       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
6102         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6103       return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6104                           AddOne(CI));
6105     case ICmpInst::ICMP_UGE:
6106       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
6107         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6108       return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
6109                           SubOne(CI));
6110     case ICmpInst::ICMP_SGE:
6111       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
6112         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6113       return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6114                           SubOne(CI));
6115     }
6116     
6117     // If this comparison is a normal comparison, it demands all
6118     // bits, if it is a sign bit comparison, it only demands the sign bit.
6119     bool UnusedBit;
6120     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6121   }
6122
6123   // See if we can fold the comparison based on range information we can get
6124   // by checking whether bits are known to be zero or one in the input.
6125   if (BitWidth != 0) {
6126     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6127     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6128
6129     if (SimplifyDemandedBits(I.getOperandUse(0),
6130                              isSignBit ? APInt::getSignBit(BitWidth)
6131                                        : APInt::getAllOnesValue(BitWidth),
6132                              Op0KnownZero, Op0KnownOne, 0))
6133       return &I;
6134     if (SimplifyDemandedBits(I.getOperandUse(1),
6135                              APInt::getAllOnesValue(BitWidth),
6136                              Op1KnownZero, Op1KnownOne, 0))
6137       return &I;
6138
6139     // Given the known and unknown bits, compute a range that the LHS could be
6140     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6141     // EQ and NE we use unsigned values.
6142     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6143     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6144     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6145       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6146                                              Op0Min, Op0Max);
6147       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6148                                              Op1Min, Op1Max);
6149     } else {
6150       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6151                                                Op0Min, Op0Max);
6152       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6153                                                Op1Min, Op1Max);
6154     }
6155
6156     // If Min and Max are known to be the same, then SimplifyDemandedBits
6157     // figured out that the LHS is a constant.  Just constant fold this now so
6158     // that code below can assume that Min != Max.
6159     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6160       return new ICmpInst(I.getPredicate(),
6161                           ConstantInt::get(*Context, Op0Min), Op1);
6162     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6163       return new ICmpInst(I.getPredicate(), Op0,
6164                           ConstantInt::get(*Context, Op1Min));
6165
6166     // Based on the range information we know about the LHS, see if we can
6167     // simplify this comparison.  For example, (x&4) < 8  is always true.
6168     switch (I.getPredicate()) {
6169     default: llvm_unreachable("Unknown icmp opcode!");
6170     case ICmpInst::ICMP_EQ:
6171       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6172         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6173       break;
6174     case ICmpInst::ICMP_NE:
6175       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6176         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6177       break;
6178     case ICmpInst::ICMP_ULT:
6179       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6180         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6181       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6182         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6183       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6184         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6185       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6186         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6187           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6188                               SubOne(CI));
6189
6190         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6191         if (CI->isMinValue(true))
6192           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6193                            Constant::getAllOnesValue(Op0->getType()));
6194       }
6195       break;
6196     case ICmpInst::ICMP_UGT:
6197       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6198         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6199       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6200         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6201
6202       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6203         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6204       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6205         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6206           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6207                               AddOne(CI));
6208
6209         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6210         if (CI->isMaxValue(true))
6211           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6212                               Constant::getNullValue(Op0->getType()));
6213       }
6214       break;
6215     case ICmpInst::ICMP_SLT:
6216       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6217         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6218       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6219         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6220       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6221         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6222       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6223         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6224           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6225                               SubOne(CI));
6226       }
6227       break;
6228     case ICmpInst::ICMP_SGT:
6229       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6230         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6231       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6232         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6233
6234       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6235         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6236       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6237         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6238           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6239                               AddOne(CI));
6240       }
6241       break;
6242     case ICmpInst::ICMP_SGE:
6243       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6244       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6245         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6246       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6247         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6248       break;
6249     case ICmpInst::ICMP_SLE:
6250       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6251       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6252         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6253       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6254         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6255       break;
6256     case ICmpInst::ICMP_UGE:
6257       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6258       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6259         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6260       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6261         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6262       break;
6263     case ICmpInst::ICMP_ULE:
6264       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6265       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6266         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6267       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6268         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6269       break;
6270     }
6271
6272     // Turn a signed comparison into an unsigned one if both operands
6273     // are known to have the same sign.
6274     if (I.isSignedPredicate() &&
6275         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6276          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6277       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6278   }
6279
6280   // Test if the ICmpInst instruction is used exclusively by a select as
6281   // part of a minimum or maximum operation. If so, refrain from doing
6282   // any other folding. This helps out other analyses which understand
6283   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6284   // and CodeGen. And in this case, at least one of the comparison
6285   // operands has at least one user besides the compare (the select),
6286   // which would often largely negate the benefit of folding anyway.
6287   if (I.hasOneUse())
6288     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6289       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6290           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6291         return 0;
6292
6293   // See if we are doing a comparison between a constant and an instruction that
6294   // can be folded into the comparison.
6295   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6296     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6297     // instruction, see if that instruction also has constants so that the 
6298     // instruction can be folded into the icmp 
6299     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6300       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6301         return Res;
6302   }
6303
6304   // Handle icmp with constant (but not simple integer constant) RHS
6305   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6306     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6307       switch (LHSI->getOpcode()) {
6308       case Instruction::GetElementPtr:
6309         if (RHSC->isNullValue()) {
6310           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6311           bool isAllZeros = true;
6312           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6313             if (!isa<Constant>(LHSI->getOperand(i)) ||
6314                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6315               isAllZeros = false;
6316               break;
6317             }
6318           if (isAllZeros)
6319             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6320                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
6321         }
6322         break;
6323
6324       case Instruction::PHI:
6325         // Only fold icmp into the PHI if the phi and icmp are in the same
6326         // block.  If in the same block, we're encouraging jump threading.  If
6327         // not, we are just pessimizing the code by making an i1 phi.
6328         if (LHSI->getParent() == I.getParent())
6329           if (Instruction *NV = FoldOpIntoPhi(I, true))
6330             return NV;
6331         break;
6332       case Instruction::Select: {
6333         // If either operand of the select is a constant, we can fold the
6334         // comparison into the select arms, which will cause one to be
6335         // constant folded and the select turned into a bitwise or.
6336         Value *Op1 = 0, *Op2 = 0;
6337         if (LHSI->hasOneUse()) {
6338           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6339             // Fold the known value into the constant operand.
6340             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6341             // Insert a new ICmp of the other select operand.
6342             Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6343                                       RHSC, I.getName());
6344           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6345             // Fold the known value into the constant operand.
6346             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6347             // Insert a new ICmp of the other select operand.
6348             Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6349                                       RHSC, I.getName());
6350           }
6351         }
6352
6353         if (Op1)
6354           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6355         break;
6356       }
6357       case Instruction::Call:
6358         // If we have (malloc != null), and if the malloc has a single use, we
6359         // can assume it is successful and remove the malloc.
6360         if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6361             isa<ConstantPointerNull>(RHSC)) {
6362           Worklist.Add(LHSI);
6363           return ReplaceInstUsesWith(I,
6364                                      ConstantInt::get(Type::getInt1Ty(*Context),
6365                                                       !I.isTrueWhenEqual()));
6366         }
6367         break;
6368       }
6369   }
6370
6371   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6372   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6373     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6374       return NI;
6375   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6376     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6377                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6378       return NI;
6379
6380   // Test to see if the operands of the icmp are casted versions of other
6381   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6382   // now.
6383   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6384     if (isa<PointerType>(Op0->getType()) && 
6385         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6386       // We keep moving the cast from the left operand over to the right
6387       // operand, where it can often be eliminated completely.
6388       Op0 = CI->getOperand(0);
6389
6390       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6391       // so eliminate it as well.
6392       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6393         Op1 = CI2->getOperand(0);
6394
6395       // If Op1 is a constant, we can fold the cast into the constant.
6396       if (Op0->getType() != Op1->getType()) {
6397         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6398           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6399         } else {
6400           // Otherwise, cast the RHS right before the icmp
6401           Op1 = Builder->CreateBitCast(Op1, Op0->getType());
6402         }
6403       }
6404       return new ICmpInst(I.getPredicate(), Op0, Op1);
6405     }
6406   }
6407   
6408   if (isa<CastInst>(Op0)) {
6409     // Handle the special case of: icmp (cast bool to X), <cst>
6410     // This comes up when you have code like
6411     //   int X = A < B;
6412     //   if (X) ...
6413     // For generality, we handle any zero-extension of any operand comparison
6414     // with a constant or another cast from the same type.
6415     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6416       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6417         return R;
6418   }
6419   
6420   // See if it's the same type of instruction on the left and right.
6421   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6422     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6423       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6424           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6425         switch (Op0I->getOpcode()) {
6426         default: break;
6427         case Instruction::Add:
6428         case Instruction::Sub:
6429         case Instruction::Xor:
6430           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6431             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6432                                 Op1I->getOperand(0));
6433           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6434           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6435             if (CI->getValue().isSignBit()) {
6436               ICmpInst::Predicate Pred = I.isSignedPredicate()
6437                                              ? I.getUnsignedPredicate()
6438                                              : I.getSignedPredicate();
6439               return new ICmpInst(Pred, Op0I->getOperand(0),
6440                                   Op1I->getOperand(0));
6441             }
6442             
6443             if (CI->getValue().isMaxSignedValue()) {
6444               ICmpInst::Predicate Pred = I.isSignedPredicate()
6445                                              ? I.getUnsignedPredicate()
6446                                              : I.getSignedPredicate();
6447               Pred = I.getSwappedPredicate(Pred);
6448               return new ICmpInst(Pred, Op0I->getOperand(0),
6449                                   Op1I->getOperand(0));
6450             }
6451           }
6452           break;
6453         case Instruction::Mul:
6454           if (!I.isEquality())
6455             break;
6456
6457           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6458             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6459             // Mask = -1 >> count-trailing-zeros(Cst).
6460             if (!CI->isZero() && !CI->isOne()) {
6461               const APInt &AP = CI->getValue();
6462               ConstantInt *Mask = ConstantInt::get(*Context, 
6463                                       APInt::getLowBitsSet(AP.getBitWidth(),
6464                                                            AP.getBitWidth() -
6465                                                       AP.countTrailingZeros()));
6466               Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6467               Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
6468               return new ICmpInst(I.getPredicate(), And1, And2);
6469             }
6470           }
6471           break;
6472         }
6473       }
6474     }
6475   }
6476   
6477   // ~x < ~y --> y < x
6478   { Value *A, *B;
6479     if (match(Op0, m_Not(m_Value(A))) &&
6480         match(Op1, m_Not(m_Value(B))))
6481       return new ICmpInst(I.getPredicate(), B, A);
6482   }
6483   
6484   if (I.isEquality()) {
6485     Value *A, *B, *C, *D;
6486     
6487     // -x == -y --> x == y
6488     if (match(Op0, m_Neg(m_Value(A))) &&
6489         match(Op1, m_Neg(m_Value(B))))
6490       return new ICmpInst(I.getPredicate(), A, B);
6491     
6492     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6493       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6494         Value *OtherVal = A == Op1 ? B : A;
6495         return new ICmpInst(I.getPredicate(), OtherVal,
6496                             Constant::getNullValue(A->getType()));
6497       }
6498
6499       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6500         // A^c1 == C^c2 --> A == C^(c1^c2)
6501         ConstantInt *C1, *C2;
6502         if (match(B, m_ConstantInt(C1)) &&
6503             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6504           Constant *NC = 
6505                    ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6506           Value *Xor = Builder->CreateXor(C, NC, "tmp");
6507           return new ICmpInst(I.getPredicate(), A, Xor);
6508         }
6509         
6510         // A^B == A^D -> B == D
6511         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6512         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6513         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6514         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6515       }
6516     }
6517     
6518     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6519         (A == Op0 || B == Op0)) {
6520       // A == (A^B)  ->  B == 0
6521       Value *OtherVal = A == Op0 ? B : A;
6522       return new ICmpInst(I.getPredicate(), OtherVal,
6523                           Constant::getNullValue(A->getType()));
6524     }
6525
6526     // (A-B) == A  ->  B == 0
6527     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6528       return new ICmpInst(I.getPredicate(), B, 
6529                           Constant::getNullValue(B->getType()));
6530
6531     // A == (A-B)  ->  B == 0
6532     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6533       return new ICmpInst(I.getPredicate(), B,
6534                           Constant::getNullValue(B->getType()));
6535     
6536     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6537     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6538         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6539         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6540       Value *X = 0, *Y = 0, *Z = 0;
6541       
6542       if (A == C) {
6543         X = B; Y = D; Z = A;
6544       } else if (A == D) {
6545         X = B; Y = C; Z = A;
6546       } else if (B == C) {
6547         X = A; Y = D; Z = B;
6548       } else if (B == D) {
6549         X = A; Y = C; Z = B;
6550       }
6551       
6552       if (X) {   // Build (X^Y) & Z
6553         Op1 = Builder->CreateXor(X, Y, "tmp");
6554         Op1 = Builder->CreateAnd(Op1, Z, "tmp");
6555         I.setOperand(0, Op1);
6556         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6557         return &I;
6558       }
6559     }
6560   }
6561   return Changed ? &I : 0;
6562 }
6563
6564
6565 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6566 /// and CmpRHS are both known to be integer constants.
6567 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6568                                           ConstantInt *DivRHS) {
6569   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6570   const APInt &CmpRHSV = CmpRHS->getValue();
6571   
6572   // FIXME: If the operand types don't match the type of the divide 
6573   // then don't attempt this transform. The code below doesn't have the
6574   // logic to deal with a signed divide and an unsigned compare (and
6575   // vice versa). This is because (x /s C1) <s C2  produces different 
6576   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6577   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6578   // work. :(  The if statement below tests that condition and bails 
6579   // if it finds it. 
6580   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6581   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6582     return 0;
6583   if (DivRHS->isZero())
6584     return 0; // The ProdOV computation fails on divide by zero.
6585   if (DivIsSigned && DivRHS->isAllOnesValue())
6586     return 0; // The overflow computation also screws up here
6587   if (DivRHS->isOne())
6588     return 0; // Not worth bothering, and eliminates some funny cases
6589               // with INT_MIN.
6590
6591   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6592   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6593   // C2 (CI). By solving for X we can turn this into a range check 
6594   // instead of computing a divide. 
6595   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6596
6597   // Determine if the product overflows by seeing if the product is
6598   // not equal to the divide. Make sure we do the same kind of divide
6599   // as in the LHS instruction that we're folding. 
6600   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6601                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6602
6603   // Get the ICmp opcode
6604   ICmpInst::Predicate Pred = ICI.getPredicate();
6605
6606   // Figure out the interval that is being checked.  For example, a comparison
6607   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6608   // Compute this interval based on the constants involved and the signedness of
6609   // the compare/divide.  This computes a half-open interval, keeping track of
6610   // whether either value in the interval overflows.  After analysis each
6611   // overflow variable is set to 0 if it's corresponding bound variable is valid
6612   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6613   int LoOverflow = 0, HiOverflow = 0;
6614   Constant *LoBound = 0, *HiBound = 0;
6615   
6616   if (!DivIsSigned) {  // udiv
6617     // e.g. X/5 op 3  --> [15, 20)
6618     LoBound = Prod;
6619     HiOverflow = LoOverflow = ProdOV;
6620     if (!HiOverflow)
6621       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6622   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6623     if (CmpRHSV == 0) {       // (X / pos) op 0
6624       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6625       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6626       HiBound = DivRHS;
6627     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6628       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6629       HiOverflow = LoOverflow = ProdOV;
6630       if (!HiOverflow)
6631         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6632     } else {                       // (X / pos) op neg
6633       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6634       HiBound = AddOne(Prod);
6635       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6636       if (!LoOverflow) {
6637         ConstantInt* DivNeg =
6638                          cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6639         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6640                                      true) ? -1 : 0;
6641        }
6642     }
6643   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6644     if (CmpRHSV == 0) {       // (X / neg) op 0
6645       // e.g. X/-5 op 0  --> [-4, 5)
6646       LoBound = AddOne(DivRHS);
6647       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6648       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6649         HiOverflow = 1;            // [INTMIN+1, overflow)
6650         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6651       }
6652     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6653       // e.g. X/-5 op 3  --> [-19, -14)
6654       HiBound = AddOne(Prod);
6655       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6656       if (!LoOverflow)
6657         LoOverflow = AddWithOverflow(LoBound, HiBound,
6658                                      DivRHS, Context, true) ? -1 : 0;
6659     } else {                       // (X / neg) op neg
6660       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6661       LoOverflow = HiOverflow = ProdOV;
6662       if (!HiOverflow)
6663         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6664     }
6665     
6666     // Dividing by a negative swaps the condition.  LT <-> GT
6667     Pred = ICmpInst::getSwappedPredicate(Pred);
6668   }
6669
6670   Value *X = DivI->getOperand(0);
6671   switch (Pred) {
6672   default: llvm_unreachable("Unhandled icmp opcode!");
6673   case ICmpInst::ICMP_EQ:
6674     if (LoOverflow && HiOverflow)
6675       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6676     else if (HiOverflow)
6677       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6678                           ICmpInst::ICMP_UGE, X, LoBound);
6679     else if (LoOverflow)
6680       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6681                           ICmpInst::ICMP_ULT, X, HiBound);
6682     else
6683       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6684   case ICmpInst::ICMP_NE:
6685     if (LoOverflow && HiOverflow)
6686       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6687     else if (HiOverflow)
6688       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6689                           ICmpInst::ICMP_ULT, X, LoBound);
6690     else if (LoOverflow)
6691       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6692                           ICmpInst::ICMP_UGE, X, HiBound);
6693     else
6694       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6695   case ICmpInst::ICMP_ULT:
6696   case ICmpInst::ICMP_SLT:
6697     if (LoOverflow == +1)   // Low bound is greater than input range.
6698       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6699     if (LoOverflow == -1)   // Low bound is less than input range.
6700       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6701     return new ICmpInst(Pred, X, LoBound);
6702   case ICmpInst::ICMP_UGT:
6703   case ICmpInst::ICMP_SGT:
6704     if (HiOverflow == +1)       // High bound greater than input range.
6705       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6706     else if (HiOverflow == -1)  // High bound less than input range.
6707       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6708     if (Pred == ICmpInst::ICMP_UGT)
6709       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6710     else
6711       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6712   }
6713 }
6714
6715
6716 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6717 ///
6718 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6719                                                           Instruction *LHSI,
6720                                                           ConstantInt *RHS) {
6721   const APInt &RHSV = RHS->getValue();
6722   
6723   switch (LHSI->getOpcode()) {
6724   case Instruction::Trunc:
6725     if (ICI.isEquality() && LHSI->hasOneUse()) {
6726       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6727       // of the high bits truncated out of x are known.
6728       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6729              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6730       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6731       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6732       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6733       
6734       // If all the high bits are known, we can do this xform.
6735       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6736         // Pull in the high bits from known-ones set.
6737         APInt NewRHS(RHS->getValue());
6738         NewRHS.zext(SrcBits);
6739         NewRHS |= KnownOne;
6740         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6741                             ConstantInt::get(*Context, NewRHS));
6742       }
6743     }
6744     break;
6745       
6746   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6747     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6748       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6749       // fold the xor.
6750       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6751           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6752         Value *CompareVal = LHSI->getOperand(0);
6753         
6754         // If the sign bit of the XorCST is not set, there is no change to
6755         // the operation, just stop using the Xor.
6756         if (!XorCST->getValue().isNegative()) {
6757           ICI.setOperand(0, CompareVal);
6758           Worklist.Add(LHSI);
6759           return &ICI;
6760         }
6761         
6762         // Was the old condition true if the operand is positive?
6763         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6764         
6765         // If so, the new one isn't.
6766         isTrueIfPositive ^= true;
6767         
6768         if (isTrueIfPositive)
6769           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
6770                               SubOne(RHS));
6771         else
6772           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
6773                               AddOne(RHS));
6774       }
6775
6776       if (LHSI->hasOneUse()) {
6777         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6778         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6779           const APInt &SignBit = XorCST->getValue();
6780           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6781                                          ? ICI.getUnsignedPredicate()
6782                                          : ICI.getSignedPredicate();
6783           return new ICmpInst(Pred, LHSI->getOperand(0),
6784                               ConstantInt::get(*Context, RHSV ^ SignBit));
6785         }
6786
6787         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6788         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6789           const APInt &NotSignBit = XorCST->getValue();
6790           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6791                                          ? ICI.getUnsignedPredicate()
6792                                          : ICI.getSignedPredicate();
6793           Pred = ICI.getSwappedPredicate(Pred);
6794           return new ICmpInst(Pred, LHSI->getOperand(0),
6795                               ConstantInt::get(*Context, RHSV ^ NotSignBit));
6796         }
6797       }
6798     }
6799     break;
6800   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6801     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6802         LHSI->getOperand(0)->hasOneUse()) {
6803       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6804       
6805       // If the LHS is an AND of a truncating cast, we can widen the
6806       // and/compare to be the input width without changing the value
6807       // produced, eliminating a cast.
6808       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6809         // We can do this transformation if either the AND constant does not
6810         // have its sign bit set or if it is an equality comparison. 
6811         // Extending a relational comparison when we're checking the sign
6812         // bit would not work.
6813         if (Cast->hasOneUse() &&
6814             (ICI.isEquality() ||
6815              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6816           uint32_t BitWidth = 
6817             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6818           APInt NewCST = AndCST->getValue();
6819           NewCST.zext(BitWidth);
6820           APInt NewCI = RHSV;
6821           NewCI.zext(BitWidth);
6822           Value *NewAnd = 
6823             Builder->CreateAnd(Cast->getOperand(0),
6824                            ConstantInt::get(*Context, NewCST), LHSI->getName());
6825           return new ICmpInst(ICI.getPredicate(), NewAnd,
6826                               ConstantInt::get(*Context, NewCI));
6827         }
6828       }
6829       
6830       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6831       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6832       // happens a LOT in code produced by the C front-end, for bitfield
6833       // access.
6834       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6835       if (Shift && !Shift->isShift())
6836         Shift = 0;
6837       
6838       ConstantInt *ShAmt;
6839       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6840       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6841       const Type *AndTy = AndCST->getType();          // Type of the and.
6842       
6843       // We can fold this as long as we can't shift unknown bits
6844       // into the mask.  This can only happen with signed shift
6845       // rights, as they sign-extend.
6846       if (ShAmt) {
6847         bool CanFold = Shift->isLogicalShift();
6848         if (!CanFold) {
6849           // To test for the bad case of the signed shr, see if any
6850           // of the bits shifted in could be tested after the mask.
6851           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6852           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6853           
6854           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6855           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6856                AndCST->getValue()) == 0)
6857             CanFold = true;
6858         }
6859         
6860         if (CanFold) {
6861           Constant *NewCst;
6862           if (Shift->getOpcode() == Instruction::Shl)
6863             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6864           else
6865             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6866           
6867           // Check to see if we are shifting out any of the bits being
6868           // compared.
6869           if (ConstantExpr::get(Shift->getOpcode(),
6870                                        NewCst, ShAmt) != RHS) {
6871             // If we shifted bits out, the fold is not going to work out.
6872             // As a special case, check to see if this means that the
6873             // result is always true or false now.
6874             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6875               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6876             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6877               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6878           } else {
6879             ICI.setOperand(1, NewCst);
6880             Constant *NewAndCST;
6881             if (Shift->getOpcode() == Instruction::Shl)
6882               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6883             else
6884               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6885             LHSI->setOperand(1, NewAndCST);
6886             LHSI->setOperand(0, Shift->getOperand(0));
6887             Worklist.Add(Shift); // Shift is dead.
6888             return &ICI;
6889           }
6890         }
6891       }
6892       
6893       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6894       // preferable because it allows the C<<Y expression to be hoisted out
6895       // of a loop if Y is invariant and X is not.
6896       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6897           ICI.isEquality() && !Shift->isArithmeticShift() &&
6898           !isa<Constant>(Shift->getOperand(0))) {
6899         // Compute C << Y.
6900         Value *NS;
6901         if (Shift->getOpcode() == Instruction::LShr) {
6902           NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
6903         } else {
6904           // Insert a logical shift.
6905           NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
6906         }
6907         
6908         // Compute X & (C << Y).
6909         Value *NewAnd = 
6910           Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6911         
6912         ICI.setOperand(0, NewAnd);
6913         return &ICI;
6914       }
6915     }
6916     break;
6917     
6918   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6919     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6920     if (!ShAmt) break;
6921     
6922     uint32_t TypeBits = RHSV.getBitWidth();
6923     
6924     // Check that the shift amount is in range.  If not, don't perform
6925     // undefined shifts.  When the shift is visited it will be
6926     // simplified.
6927     if (ShAmt->uge(TypeBits))
6928       break;
6929     
6930     if (ICI.isEquality()) {
6931       // If we are comparing against bits always shifted out, the
6932       // comparison cannot succeed.
6933       Constant *Comp =
6934         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
6935                                                                  ShAmt);
6936       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6937         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6938         Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6939         return ReplaceInstUsesWith(ICI, Cst);
6940       }
6941       
6942       if (LHSI->hasOneUse()) {
6943         // Otherwise strength reduce the shift into an and.
6944         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6945         Constant *Mask =
6946           ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits, 
6947                                                        TypeBits-ShAmtVal));
6948         
6949         Value *And =
6950           Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
6951         return new ICmpInst(ICI.getPredicate(), And,
6952                             ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
6953       }
6954     }
6955     
6956     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6957     bool TrueIfSigned = false;
6958     if (LHSI->hasOneUse() &&
6959         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6960       // (X << 31) <s 0  --> (X&1) != 0
6961       Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
6962                                            (TypeBits-ShAmt->getZExtValue()-1));
6963       Value *And =
6964         Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
6965       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6966                           And, Constant::getNullValue(And->getType()));
6967     }
6968     break;
6969   }
6970     
6971   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6972   case Instruction::AShr: {
6973     // Only handle equality comparisons of shift-by-constant.
6974     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6975     if (!ShAmt || !ICI.isEquality()) break;
6976
6977     // Check that the shift amount is in range.  If not, don't perform
6978     // undefined shifts.  When the shift is visited it will be
6979     // simplified.
6980     uint32_t TypeBits = RHSV.getBitWidth();
6981     if (ShAmt->uge(TypeBits))
6982       break;
6983     
6984     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6985       
6986     // If we are comparing against bits always shifted out, the
6987     // comparison cannot succeed.
6988     APInt Comp = RHSV << ShAmtVal;
6989     if (LHSI->getOpcode() == Instruction::LShr)
6990       Comp = Comp.lshr(ShAmtVal);
6991     else
6992       Comp = Comp.ashr(ShAmtVal);
6993     
6994     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6995       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6996       Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6997       return ReplaceInstUsesWith(ICI, Cst);
6998     }
6999     
7000     // Otherwise, check to see if the bits shifted out are known to be zero.
7001     // If so, we can compare against the unshifted value:
7002     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
7003     if (LHSI->hasOneUse() &&
7004         MaskedValueIsZero(LHSI->getOperand(0), 
7005                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
7006       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
7007                           ConstantExpr::getShl(RHS, ShAmt));
7008     }
7009       
7010     if (LHSI->hasOneUse()) {
7011       // Otherwise strength reduce the shift into an and.
7012       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
7013       Constant *Mask = ConstantInt::get(*Context, Val);
7014       
7015       Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7016                                       Mask, LHSI->getName()+".mask");
7017       return new ICmpInst(ICI.getPredicate(), And,
7018                           ConstantExpr::getShl(RHS, ShAmt));
7019     }
7020     break;
7021   }
7022     
7023   case Instruction::SDiv:
7024   case Instruction::UDiv:
7025     // Fold: icmp pred ([us]div X, C1), C2 -> range test
7026     // Fold this div into the comparison, producing a range check. 
7027     // Determine, based on the divide type, what the range is being 
7028     // checked.  If there is an overflow on the low or high side, remember 
7029     // it, otherwise compute the range [low, hi) bounding the new value.
7030     // See: InsertRangeTest above for the kinds of replacements possible.
7031     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7032       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7033                                           DivRHS))
7034         return R;
7035     break;
7036
7037   case Instruction::Add:
7038     // Fold: icmp pred (add, X, C1), C2
7039
7040     if (!ICI.isEquality()) {
7041       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7042       if (!LHSC) break;
7043       const APInt &LHSV = LHSC->getValue();
7044
7045       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7046                             .subtract(LHSV);
7047
7048       if (ICI.isSignedPredicate()) {
7049         if (CR.getLower().isSignBit()) {
7050           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7051                               ConstantInt::get(*Context, CR.getUpper()));
7052         } else if (CR.getUpper().isSignBit()) {
7053           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7054                               ConstantInt::get(*Context, CR.getLower()));
7055         }
7056       } else {
7057         if (CR.getLower().isMinValue()) {
7058           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7059                               ConstantInt::get(*Context, CR.getUpper()));
7060         } else if (CR.getUpper().isMinValue()) {
7061           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7062                               ConstantInt::get(*Context, CR.getLower()));
7063         }
7064       }
7065     }
7066     break;
7067   }
7068   
7069   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7070   if (ICI.isEquality()) {
7071     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7072     
7073     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7074     // the second operand is a constant, simplify a bit.
7075     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7076       switch (BO->getOpcode()) {
7077       case Instruction::SRem:
7078         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7079         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7080           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7081           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7082             Value *NewRem =
7083               Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7084                                   BO->getName());
7085             return new ICmpInst(ICI.getPredicate(), NewRem,
7086                                 Constant::getNullValue(BO->getType()));
7087           }
7088         }
7089         break;
7090       case Instruction::Add:
7091         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7092         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7093           if (BO->hasOneUse())
7094             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7095                                 ConstantExpr::getSub(RHS, BOp1C));
7096         } else if (RHSV == 0) {
7097           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7098           // efficiently invertible, or if the add has just this one use.
7099           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7100           
7101           if (Value *NegVal = dyn_castNegVal(BOp1))
7102             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
7103           else if (Value *NegVal = dyn_castNegVal(BOp0))
7104             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
7105           else if (BO->hasOneUse()) {
7106             Value *Neg = Builder->CreateNeg(BOp1);
7107             Neg->takeName(BO);
7108             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
7109           }
7110         }
7111         break;
7112       case Instruction::Xor:
7113         // For the xor case, we can xor two constants together, eliminating
7114         // the explicit xor.
7115         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7116           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
7117                               ConstantExpr::getXor(RHS, BOC));
7118         
7119         // FALLTHROUGH
7120       case Instruction::Sub:
7121         // Replace (([sub|xor] A, B) != 0) with (A != B)
7122         if (RHSV == 0)
7123           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7124                               BO->getOperand(1));
7125         break;
7126         
7127       case Instruction::Or:
7128         // If bits are being or'd in that are not present in the constant we
7129         // are comparing against, then the comparison could never succeed!
7130         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7131           Constant *NotCI = ConstantExpr::getNot(RHS);
7132           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7133             return ReplaceInstUsesWith(ICI,
7134                                        ConstantInt::get(Type::getInt1Ty(*Context), 
7135                                        isICMP_NE));
7136         }
7137         break;
7138         
7139       case Instruction::And:
7140         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7141           // If bits are being compared against that are and'd out, then the
7142           // comparison can never succeed!
7143           if ((RHSV & ~BOC->getValue()) != 0)
7144             return ReplaceInstUsesWith(ICI,
7145                                        ConstantInt::get(Type::getInt1Ty(*Context),
7146                                        isICMP_NE));
7147           
7148           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7149           if (RHS == BOC && RHSV.isPowerOf2())
7150             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7151                                 ICmpInst::ICMP_NE, LHSI,
7152                                 Constant::getNullValue(RHS->getType()));
7153           
7154           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7155           if (BOC->getValue().isSignBit()) {
7156             Value *X = BO->getOperand(0);
7157             Constant *Zero = Constant::getNullValue(X->getType());
7158             ICmpInst::Predicate pred = isICMP_NE ? 
7159               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7160             return new ICmpInst(pred, X, Zero);
7161           }
7162           
7163           // ((X & ~7) == 0) --> X < 8
7164           if (RHSV == 0 && isHighOnes(BOC)) {
7165             Value *X = BO->getOperand(0);
7166             Constant *NegX = ConstantExpr::getNeg(BOC);
7167             ICmpInst::Predicate pred = isICMP_NE ? 
7168               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7169             return new ICmpInst(pred, X, NegX);
7170           }
7171         }
7172       default: break;
7173       }
7174     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7175       // Handle icmp {eq|ne} <intrinsic>, intcst.
7176       if (II->getIntrinsicID() == Intrinsic::bswap) {
7177         Worklist.Add(II);
7178         ICI.setOperand(0, II->getOperand(1));
7179         ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7180         return &ICI;
7181       }
7182     }
7183   }
7184   return 0;
7185 }
7186
7187 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7188 /// We only handle extending casts so far.
7189 ///
7190 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7191   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7192   Value *LHSCIOp        = LHSCI->getOperand(0);
7193   const Type *SrcTy     = LHSCIOp->getType();
7194   const Type *DestTy    = LHSCI->getType();
7195   Value *RHSCIOp;
7196
7197   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7198   // integer type is the same size as the pointer type.
7199   if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7200       TD->getPointerSizeInBits() ==
7201          cast<IntegerType>(DestTy)->getBitWidth()) {
7202     Value *RHSOp = 0;
7203     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7204       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7205     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7206       RHSOp = RHSC->getOperand(0);
7207       // If the pointer types don't match, insert a bitcast.
7208       if (LHSCIOp->getType() != RHSOp->getType())
7209         RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
7210     }
7211
7212     if (RHSOp)
7213       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7214   }
7215   
7216   // The code below only handles extension cast instructions, so far.
7217   // Enforce this.
7218   if (LHSCI->getOpcode() != Instruction::ZExt &&
7219       LHSCI->getOpcode() != Instruction::SExt)
7220     return 0;
7221
7222   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7223   bool isSignedCmp = ICI.isSignedPredicate();
7224
7225   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7226     // Not an extension from the same type?
7227     RHSCIOp = CI->getOperand(0);
7228     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7229       return 0;
7230     
7231     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7232     // and the other is a zext), then we can't handle this.
7233     if (CI->getOpcode() != LHSCI->getOpcode())
7234       return 0;
7235
7236     // Deal with equality cases early.
7237     if (ICI.isEquality())
7238       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7239
7240     // A signed comparison of sign extended values simplifies into a
7241     // signed comparison.
7242     if (isSignedCmp && isSignedExt)
7243       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7244
7245     // The other three cases all fold into an unsigned comparison.
7246     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7247   }
7248
7249   // If we aren't dealing with a constant on the RHS, exit early
7250   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7251   if (!CI)
7252     return 0;
7253
7254   // Compute the constant that would happen if we truncated to SrcTy then
7255   // reextended to DestTy.
7256   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7257   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7258                                                 Res1, DestTy);
7259
7260   // If the re-extended constant didn't change...
7261   if (Res2 == CI) {
7262     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7263     // For example, we might have:
7264     //    %A = sext i16 %X to i32
7265     //    %B = icmp ugt i32 %A, 1330
7266     // It is incorrect to transform this into 
7267     //    %B = icmp ugt i16 %X, 1330
7268     // because %A may have negative value. 
7269     //
7270     // However, we allow this when the compare is EQ/NE, because they are
7271     // signless.
7272     if (isSignedExt == isSignedCmp || ICI.isEquality())
7273       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7274     return 0;
7275   }
7276
7277   // The re-extended constant changed so the constant cannot be represented 
7278   // in the shorter type. Consequently, we cannot emit a simple comparison.
7279
7280   // First, handle some easy cases. We know the result cannot be equal at this
7281   // point so handle the ICI.isEquality() cases
7282   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7283     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7284   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7285     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7286
7287   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7288   // should have been folded away previously and not enter in here.
7289   Value *Result;
7290   if (isSignedCmp) {
7291     // We're performing a signed comparison.
7292     if (cast<ConstantInt>(CI)->getValue().isNegative())
7293       Result = ConstantInt::getFalse(*Context);          // X < (small) --> false
7294     else
7295       Result = ConstantInt::getTrue(*Context);           // X < (large) --> true
7296   } else {
7297     // We're performing an unsigned comparison.
7298     if (isSignedExt) {
7299       // We're performing an unsigned comp with a sign extended value.
7300       // This is true if the input is >= 0. [aka >s -1]
7301       Constant *NegOne = Constant::getAllOnesValue(SrcTy);
7302       Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
7303     } else {
7304       // Unsigned extend & unsigned compare -> always true.
7305       Result = ConstantInt::getTrue(*Context);
7306     }
7307   }
7308
7309   // Finally, return the value computed.
7310   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7311       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7312     return ReplaceInstUsesWith(ICI, Result);
7313
7314   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7315           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7316          "ICmp should be folded!");
7317   if (Constant *CI = dyn_cast<Constant>(Result))
7318     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7319   return BinaryOperator::CreateNot(Result);
7320 }
7321
7322 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7323   return commonShiftTransforms(I);
7324 }
7325
7326 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7327   return commonShiftTransforms(I);
7328 }
7329
7330 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7331   if (Instruction *R = commonShiftTransforms(I))
7332     return R;
7333   
7334   Value *Op0 = I.getOperand(0);
7335   
7336   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7337   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7338     if (CSI->isAllOnesValue())
7339       return ReplaceInstUsesWith(I, CSI);
7340
7341   // See if we can turn a signed shr into an unsigned shr.
7342   if (MaskedValueIsZero(Op0,
7343                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7344     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7345
7346   // Arithmetic shifting an all-sign-bit value is a no-op.
7347   unsigned NumSignBits = ComputeNumSignBits(Op0);
7348   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7349     return ReplaceInstUsesWith(I, Op0);
7350
7351   return 0;
7352 }
7353
7354 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7355   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7356   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7357
7358   // shl X, 0 == X and shr X, 0 == X
7359   // shl 0, X == 0 and shr 0, X == 0
7360   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7361       Op0 == Constant::getNullValue(Op0->getType()))
7362     return ReplaceInstUsesWith(I, Op0);
7363   
7364   if (isa<UndefValue>(Op0)) {            
7365     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7366       return ReplaceInstUsesWith(I, Op0);
7367     else                                    // undef << X -> 0, undef >>u X -> 0
7368       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7369   }
7370   if (isa<UndefValue>(Op1)) {
7371     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7372       return ReplaceInstUsesWith(I, Op0);          
7373     else                                     // X << undef, X >>u undef -> 0
7374       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7375   }
7376
7377   // See if we can fold away this shift.
7378   if (SimplifyDemandedInstructionBits(I))
7379     return &I;
7380
7381   // Try to fold constant and into select arguments.
7382   if (isa<Constant>(Op0))
7383     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7384       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7385         return R;
7386
7387   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7388     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7389       return Res;
7390   return 0;
7391 }
7392
7393 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7394                                                BinaryOperator &I) {
7395   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7396
7397   // See if we can simplify any instructions used by the instruction whose sole 
7398   // purpose is to compute bits we don't care about.
7399   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7400   
7401   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7402   // a signed shift.
7403   //
7404   if (Op1->uge(TypeBits)) {
7405     if (I.getOpcode() != Instruction::AShr)
7406       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7407     else {
7408       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7409       return &I;
7410     }
7411   }
7412   
7413   // ((X*C1) << C2) == (X * (C1 << C2))
7414   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7415     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7416       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7417         return BinaryOperator::CreateMul(BO->getOperand(0),
7418                                         ConstantExpr::getShl(BOOp, Op1));
7419   
7420   // Try to fold constant and into select arguments.
7421   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7422     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7423       return R;
7424   if (isa<PHINode>(Op0))
7425     if (Instruction *NV = FoldOpIntoPhi(I))
7426       return NV;
7427   
7428   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7429   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7430     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7431     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7432     // place.  Don't try to do this transformation in this case.  Also, we
7433     // require that the input operand is a shift-by-constant so that we have
7434     // confidence that the shifts will get folded together.  We could do this
7435     // xform in more cases, but it is unlikely to be profitable.
7436     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7437         isa<ConstantInt>(TrOp->getOperand(1))) {
7438       // Okay, we'll do this xform.  Make the shift of shift.
7439       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7440       // (shift2 (shift1 & 0x00FF), c2)
7441       Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
7442
7443       // For logical shifts, the truncation has the effect of making the high
7444       // part of the register be zeros.  Emulate this by inserting an AND to
7445       // clear the top bits as needed.  This 'and' will usually be zapped by
7446       // other xforms later if dead.
7447       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7448       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7449       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7450       
7451       // The mask we constructed says what the trunc would do if occurring
7452       // between the shifts.  We want to know the effect *after* the second
7453       // shift.  We know that it is a logical shift by a constant, so adjust the
7454       // mask as appropriate.
7455       if (I.getOpcode() == Instruction::Shl)
7456         MaskV <<= Op1->getZExtValue();
7457       else {
7458         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7459         MaskV = MaskV.lshr(Op1->getZExtValue());
7460       }
7461
7462       // shift1 & 0x00FF
7463       Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7464                                       TI->getName());
7465
7466       // Return the value truncated to the interesting size.
7467       return new TruncInst(And, I.getType());
7468     }
7469   }
7470   
7471   if (Op0->hasOneUse()) {
7472     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7473       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7474       Value *V1, *V2;
7475       ConstantInt *CC;
7476       switch (Op0BO->getOpcode()) {
7477         default: break;
7478         case Instruction::Add:
7479         case Instruction::And:
7480         case Instruction::Or:
7481         case Instruction::Xor: {
7482           // These operators commute.
7483           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7484           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7485               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7486                     m_Specific(Op1)))) {
7487             Value *YS =         // (Y << C)
7488               Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7489             // (X + (Y << C))
7490             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7491                                             Op0BO->getOperand(1)->getName());
7492             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7493             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7494                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7495           }
7496           
7497           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7498           Value *Op0BOOp1 = Op0BO->getOperand(1);
7499           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7500               match(Op0BOOp1, 
7501                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7502                           m_ConstantInt(CC))) &&
7503               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7504             Value *YS =   // (Y << C)
7505               Builder->CreateShl(Op0BO->getOperand(0), Op1,
7506                                            Op0BO->getName());
7507             // X & (CC << C)
7508             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7509                                            V1->getName()+".mask");
7510             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7511           }
7512         }
7513           
7514         // FALL THROUGH.
7515         case Instruction::Sub: {
7516           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7517           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7518               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7519                     m_Specific(Op1)))) {
7520             Value *YS =  // (Y << C)
7521               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7522             // (X + (Y << C))
7523             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7524                                             Op0BO->getOperand(0)->getName());
7525             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7526             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7527                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7528           }
7529           
7530           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7531           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7532               match(Op0BO->getOperand(0),
7533                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7534                           m_ConstantInt(CC))) && V2 == Op1 &&
7535               cast<BinaryOperator>(Op0BO->getOperand(0))
7536                   ->getOperand(0)->hasOneUse()) {
7537             Value *YS = // (Y << C)
7538               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7539             // X & (CC << C)
7540             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7541                                            V1->getName()+".mask");
7542             
7543             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7544           }
7545           
7546           break;
7547         }
7548       }
7549       
7550       
7551       // If the operand is an bitwise operator with a constant RHS, and the
7552       // shift is the only use, we can pull it out of the shift.
7553       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7554         bool isValid = true;     // Valid only for And, Or, Xor
7555         bool highBitSet = false; // Transform if high bit of constant set?
7556         
7557         switch (Op0BO->getOpcode()) {
7558           default: isValid = false; break;   // Do not perform transform!
7559           case Instruction::Add:
7560             isValid = isLeftShift;
7561             break;
7562           case Instruction::Or:
7563           case Instruction::Xor:
7564             highBitSet = false;
7565             break;
7566           case Instruction::And:
7567             highBitSet = true;
7568             break;
7569         }
7570         
7571         // If this is a signed shift right, and the high bit is modified
7572         // by the logical operation, do not perform the transformation.
7573         // The highBitSet boolean indicates the value of the high bit of
7574         // the constant which would cause it to be modified for this
7575         // operation.
7576         //
7577         if (isValid && I.getOpcode() == Instruction::AShr)
7578           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7579         
7580         if (isValid) {
7581           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7582           
7583           Value *NewShift =
7584             Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
7585           NewShift->takeName(Op0BO);
7586           
7587           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7588                                         NewRHS);
7589         }
7590       }
7591     }
7592   }
7593   
7594   // Find out if this is a shift of a shift by a constant.
7595   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7596   if (ShiftOp && !ShiftOp->isShift())
7597     ShiftOp = 0;
7598   
7599   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7600     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7601     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7602     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7603     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7604     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7605     Value *X = ShiftOp->getOperand(0);
7606     
7607     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7608     
7609     const IntegerType *Ty = cast<IntegerType>(I.getType());
7610     
7611     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7612     if (I.getOpcode() == ShiftOp->getOpcode()) {
7613       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7614       // saturates.
7615       if (AmtSum >= TypeBits) {
7616         if (I.getOpcode() != Instruction::AShr)
7617           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7618         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7619       }
7620       
7621       return BinaryOperator::Create(I.getOpcode(), X,
7622                                     ConstantInt::get(Ty, AmtSum));
7623     }
7624     
7625     if (ShiftOp->getOpcode() == Instruction::LShr &&
7626         I.getOpcode() == Instruction::AShr) {
7627       if (AmtSum >= TypeBits)
7628         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7629       
7630       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7631       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7632     }
7633     
7634     if (ShiftOp->getOpcode() == Instruction::AShr &&
7635         I.getOpcode() == Instruction::LShr) {
7636       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7637       if (AmtSum >= TypeBits)
7638         AmtSum = TypeBits-1;
7639       
7640       Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7641
7642       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7643       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
7644     }
7645     
7646     // Okay, if we get here, one shift must be left, and the other shift must be
7647     // right.  See if the amounts are equal.
7648     if (ShiftAmt1 == ShiftAmt2) {
7649       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7650       if (I.getOpcode() == Instruction::Shl) {
7651         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7652         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7653       }
7654       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7655       if (I.getOpcode() == Instruction::LShr) {
7656         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7657         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7658       }
7659       // We can simplify ((X << C) >>s C) into a trunc + sext.
7660       // NOTE: we could do this for any C, but that would make 'unusual' integer
7661       // types.  For now, just stick to ones well-supported by the code
7662       // generators.
7663       const Type *SExtType = 0;
7664       switch (Ty->getBitWidth() - ShiftAmt1) {
7665       case 1  :
7666       case 8  :
7667       case 16 :
7668       case 32 :
7669       case 64 :
7670       case 128:
7671         SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
7672         break;
7673       default: break;
7674       }
7675       if (SExtType)
7676         return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
7677       // Otherwise, we can't handle it yet.
7678     } else if (ShiftAmt1 < ShiftAmt2) {
7679       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7680       
7681       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7682       if (I.getOpcode() == Instruction::Shl) {
7683         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7684                ShiftOp->getOpcode() == Instruction::AShr);
7685         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7686         
7687         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7688         return BinaryOperator::CreateAnd(Shift,
7689                                          ConstantInt::get(*Context, Mask));
7690       }
7691       
7692       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7693       if (I.getOpcode() == Instruction::LShr) {
7694         assert(ShiftOp->getOpcode() == Instruction::Shl);
7695         Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7696         
7697         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7698         return BinaryOperator::CreateAnd(Shift,
7699                                          ConstantInt::get(*Context, Mask));
7700       }
7701       
7702       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7703     } else {
7704       assert(ShiftAmt2 < ShiftAmt1);
7705       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7706
7707       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7708       if (I.getOpcode() == Instruction::Shl) {
7709         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7710                ShiftOp->getOpcode() == Instruction::AShr);
7711         Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7712                                             ConstantInt::get(Ty, ShiftDiff));
7713         
7714         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7715         return BinaryOperator::CreateAnd(Shift,
7716                                          ConstantInt::get(*Context, Mask));
7717       }
7718       
7719       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7720       if (I.getOpcode() == Instruction::LShr) {
7721         assert(ShiftOp->getOpcode() == Instruction::Shl);
7722         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7723         
7724         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7725         return BinaryOperator::CreateAnd(Shift,
7726                                          ConstantInt::get(*Context, Mask));
7727       }
7728       
7729       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7730     }
7731   }
7732   return 0;
7733 }
7734
7735
7736 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7737 /// expression.  If so, decompose it, returning some value X, such that Val is
7738 /// X*Scale+Offset.
7739 ///
7740 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7741                                         int &Offset, LLVMContext *Context) {
7742   assert(Val->getType() == Type::getInt32Ty(*Context) && 
7743          "Unexpected allocation size type!");
7744   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7745     Offset = CI->getZExtValue();
7746     Scale  = 0;
7747     return ConstantInt::get(Type::getInt32Ty(*Context), 0);
7748   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7749     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7750       if (I->getOpcode() == Instruction::Shl) {
7751         // This is a value scaled by '1 << the shift amt'.
7752         Scale = 1U << RHS->getZExtValue();
7753         Offset = 0;
7754         return I->getOperand(0);
7755       } else if (I->getOpcode() == Instruction::Mul) {
7756         // This value is scaled by 'RHS'.
7757         Scale = RHS->getZExtValue();
7758         Offset = 0;
7759         return I->getOperand(0);
7760       } else if (I->getOpcode() == Instruction::Add) {
7761         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7762         // where C1 is divisible by C2.
7763         unsigned SubScale;
7764         Value *SubVal = 
7765           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7766                                     Offset, Context);
7767         Offset += RHS->getZExtValue();
7768         Scale = SubScale;
7769         return SubVal;
7770       }
7771     }
7772   }
7773
7774   // Otherwise, we can't look past this.
7775   Scale = 1;
7776   Offset = 0;
7777   return Val;
7778 }
7779
7780
7781 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7782 /// try to eliminate the cast by moving the type information into the alloc.
7783 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7784                                                    AllocationInst &AI) {
7785   const PointerType *PTy = cast<PointerType>(CI.getType());
7786   
7787   BuilderTy AllocaBuilder(*Builder);
7788   AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7789   
7790   // Remove any uses of AI that are dead.
7791   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7792   
7793   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7794     Instruction *User = cast<Instruction>(*UI++);
7795     if (isInstructionTriviallyDead(User)) {
7796       while (UI != E && *UI == User)
7797         ++UI; // If this instruction uses AI more than once, don't break UI.
7798       
7799       ++NumDeadInst;
7800       DEBUG(errs() << "IC: DCE: " << *User << '\n');
7801       EraseInstFromFunction(*User);
7802     }
7803   }
7804
7805   // This requires TargetData to get the alloca alignment and size information.
7806   if (!TD) return 0;
7807
7808   // Get the type really allocated and the type casted to.
7809   const Type *AllocElTy = AI.getAllocatedType();
7810   const Type *CastElTy = PTy->getElementType();
7811   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7812
7813   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7814   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7815   if (CastElTyAlign < AllocElTyAlign) return 0;
7816
7817   // If the allocation has multiple uses, only promote it if we are strictly
7818   // increasing the alignment of the resultant allocation.  If we keep it the
7819   // same, we open the door to infinite loops of various kinds.  (A reference
7820   // from a dbg.declare doesn't count as a use for this purpose.)
7821   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7822       CastElTyAlign == AllocElTyAlign) return 0;
7823
7824   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7825   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7826   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7827
7828   // See if we can satisfy the modulus by pulling a scale out of the array
7829   // size argument.
7830   unsigned ArraySizeScale;
7831   int ArrayOffset;
7832   Value *NumElements = // See if the array size is a decomposable linear expr.
7833     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7834                               ArrayOffset, Context);
7835  
7836   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7837   // do the xform.
7838   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7839       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7840
7841   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7842   Value *Amt = 0;
7843   if (Scale == 1) {
7844     Amt = NumElements;
7845   } else {
7846     Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
7847     // Insert before the alloca, not before the cast.
7848     Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
7849   }
7850   
7851   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7852     Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
7853     Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
7854   }
7855   
7856   AllocationInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7857   New->setAlignment(AI.getAlignment());
7858   New->takeName(&AI);
7859   
7860   // If the allocation has one real use plus a dbg.declare, just remove the
7861   // declare.
7862   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7863     EraseInstFromFunction(*DI);
7864   }
7865   // If the allocation has multiple real uses, insert a cast and change all
7866   // things that used it to use the new cast.  This will also hack on CI, but it
7867   // will die soon.
7868   else if (!AI.hasOneUse()) {
7869     // New is the allocation instruction, pointer typed. AI is the original
7870     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7871     Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
7872     AI.replaceAllUsesWith(NewCast);
7873   }
7874   return ReplaceInstUsesWith(CI, New);
7875 }
7876
7877 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7878 /// and return it as type Ty without inserting any new casts and without
7879 /// changing the computed value.  This is used by code that tries to decide
7880 /// whether promoting or shrinking integer operations to wider or smaller types
7881 /// will allow us to eliminate a truncate or extend.
7882 ///
7883 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7884 /// extension operation if Ty is larger.
7885 ///
7886 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7887 /// should return true if trunc(V) can be computed by computing V in the smaller
7888 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7889 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7890 /// efficiently truncated.
7891 ///
7892 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7893 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7894 /// the final result.
7895 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7896                                               unsigned CastOpc,
7897                                               int &NumCastsRemoved){
7898   // We can always evaluate constants in another type.
7899   if (isa<Constant>(V))
7900     return true;
7901   
7902   Instruction *I = dyn_cast<Instruction>(V);
7903   if (!I) return false;
7904   
7905   const Type *OrigTy = V->getType();
7906   
7907   // If this is an extension or truncate, we can often eliminate it.
7908   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7909     // If this is a cast from the destination type, we can trivially eliminate
7910     // it, and this will remove a cast overall.
7911     if (I->getOperand(0)->getType() == Ty) {
7912       // If the first operand is itself a cast, and is eliminable, do not count
7913       // this as an eliminable cast.  We would prefer to eliminate those two
7914       // casts first.
7915       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7916         ++NumCastsRemoved;
7917       return true;
7918     }
7919   }
7920
7921   // We can't extend or shrink something that has multiple uses: doing so would
7922   // require duplicating the instruction in general, which isn't profitable.
7923   if (!I->hasOneUse()) return false;
7924
7925   unsigned Opc = I->getOpcode();
7926   switch (Opc) {
7927   case Instruction::Add:
7928   case Instruction::Sub:
7929   case Instruction::Mul:
7930   case Instruction::And:
7931   case Instruction::Or:
7932   case Instruction::Xor:
7933     // These operators can all arbitrarily be extended or truncated.
7934     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7935                                       NumCastsRemoved) &&
7936            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7937                                       NumCastsRemoved);
7938
7939   case Instruction::UDiv:
7940   case Instruction::URem: {
7941     // UDiv and URem can be truncated if all the truncated bits are zero.
7942     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7943     uint32_t BitWidth = Ty->getScalarSizeInBits();
7944     if (BitWidth < OrigBitWidth) {
7945       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7946       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7947           MaskedValueIsZero(I->getOperand(1), Mask)) {
7948         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7949                                           NumCastsRemoved) &&
7950                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7951                                           NumCastsRemoved);
7952       }
7953     }
7954     break;
7955   }
7956   case Instruction::Shl:
7957     // If we are truncating the result of this SHL, and if it's a shift of a
7958     // constant amount, we can always perform a SHL in a smaller type.
7959     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7960       uint32_t BitWidth = Ty->getScalarSizeInBits();
7961       if (BitWidth < OrigTy->getScalarSizeInBits() &&
7962           CI->getLimitedValue(BitWidth) < BitWidth)
7963         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7964                                           NumCastsRemoved);
7965     }
7966     break;
7967   case Instruction::LShr:
7968     // If this is a truncate of a logical shr, we can truncate it to a smaller
7969     // lshr iff we know that the bits we would otherwise be shifting in are
7970     // already zeros.
7971     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7972       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7973       uint32_t BitWidth = Ty->getScalarSizeInBits();
7974       if (BitWidth < OrigBitWidth &&
7975           MaskedValueIsZero(I->getOperand(0),
7976             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7977           CI->getLimitedValue(BitWidth) < BitWidth) {
7978         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7979                                           NumCastsRemoved);
7980       }
7981     }
7982     break;
7983   case Instruction::ZExt:
7984   case Instruction::SExt:
7985   case Instruction::Trunc:
7986     // If this is the same kind of case as our original (e.g. zext+zext), we
7987     // can safely replace it.  Note that replacing it does not reduce the number
7988     // of casts in the input.
7989     if (Opc == CastOpc)
7990       return true;
7991
7992     // sext (zext ty1), ty2 -> zext ty2
7993     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7994       return true;
7995     break;
7996   case Instruction::Select: {
7997     SelectInst *SI = cast<SelectInst>(I);
7998     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7999                                       NumCastsRemoved) &&
8000            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8001                                       NumCastsRemoved);
8002   }
8003   case Instruction::PHI: {
8004     // We can change a phi if we can change all operands.
8005     PHINode *PN = cast<PHINode>(I);
8006     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8007       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8008                                       NumCastsRemoved))
8009         return false;
8010     return true;
8011   }
8012   default:
8013     // TODO: Can handle more cases here.
8014     break;
8015   }
8016   
8017   return false;
8018 }
8019
8020 /// EvaluateInDifferentType - Given an expression that 
8021 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8022 /// evaluate the expression.
8023 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
8024                                              bool isSigned) {
8025   if (Constant *C = dyn_cast<Constant>(V))
8026     return ConstantExpr::getIntegerCast(C, Ty,
8027                                                isSigned /*Sext or ZExt*/);
8028
8029   // Otherwise, it must be an instruction.
8030   Instruction *I = cast<Instruction>(V);
8031   Instruction *Res = 0;
8032   unsigned Opc = I->getOpcode();
8033   switch (Opc) {
8034   case Instruction::Add:
8035   case Instruction::Sub:
8036   case Instruction::Mul:
8037   case Instruction::And:
8038   case Instruction::Or:
8039   case Instruction::Xor:
8040   case Instruction::AShr:
8041   case Instruction::LShr:
8042   case Instruction::Shl:
8043   case Instruction::UDiv:
8044   case Instruction::URem: {
8045     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8046     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8047     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8048     break;
8049   }    
8050   case Instruction::Trunc:
8051   case Instruction::ZExt:
8052   case Instruction::SExt:
8053     // If the source type of the cast is the type we're trying for then we can
8054     // just return the source.  There's no need to insert it because it is not
8055     // new.
8056     if (I->getOperand(0)->getType() == Ty)
8057       return I->getOperand(0);
8058     
8059     // Otherwise, must be the same type of cast, so just reinsert a new one.
8060     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8061                            Ty);
8062     break;
8063   case Instruction::Select: {
8064     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8065     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8066     Res = SelectInst::Create(I->getOperand(0), True, False);
8067     break;
8068   }
8069   case Instruction::PHI: {
8070     PHINode *OPN = cast<PHINode>(I);
8071     PHINode *NPN = PHINode::Create(Ty);
8072     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8073       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8074       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8075     }
8076     Res = NPN;
8077     break;
8078   }
8079   default: 
8080     // TODO: Can handle more cases here.
8081     llvm_unreachable("Unreachable!");
8082     break;
8083   }
8084   
8085   Res->takeName(I);
8086   return InsertNewInstBefore(Res, *I);
8087 }
8088
8089 /// @brief Implement the transforms common to all CastInst visitors.
8090 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8091   Value *Src = CI.getOperand(0);
8092
8093   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8094   // eliminate it now.
8095   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8096     if (Instruction::CastOps opc = 
8097         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8098       // The first cast (CSrc) is eliminable so we need to fix up or replace
8099       // the second cast (CI). CSrc will then have a good chance of being dead.
8100       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8101     }
8102   }
8103
8104   // If we are casting a select then fold the cast into the select
8105   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8106     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8107       return NV;
8108
8109   // If we are casting a PHI then fold the cast into the PHI
8110   if (isa<PHINode>(Src))
8111     if (Instruction *NV = FoldOpIntoPhi(CI))
8112       return NV;
8113   
8114   return 0;
8115 }
8116
8117 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8118 /// or not there is a sequence of GEP indices into the type that will land us at
8119 /// the specified offset.  If so, fill them into NewIndices and return the
8120 /// resultant element type, otherwise return null.
8121 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8122                                        SmallVectorImpl<Value*> &NewIndices,
8123                                        const TargetData *TD,
8124                                        LLVMContext *Context) {
8125   if (!TD) return 0;
8126   if (!Ty->isSized()) return 0;
8127   
8128   // Start with the index over the outer type.  Note that the type size
8129   // might be zero (even if the offset isn't zero) if the indexed type
8130   // is something like [0 x {int, int}]
8131   const Type *IntPtrTy = TD->getIntPtrType(*Context);
8132   int64_t FirstIdx = 0;
8133   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8134     FirstIdx = Offset/TySize;
8135     Offset -= FirstIdx*TySize;
8136     
8137     // Handle hosts where % returns negative instead of values [0..TySize).
8138     if (Offset < 0) {
8139       --FirstIdx;
8140       Offset += TySize;
8141       assert(Offset >= 0);
8142     }
8143     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8144   }
8145   
8146   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8147     
8148   // Index into the types.  If we fail, set OrigBase to null.
8149   while (Offset) {
8150     // Indexing into tail padding between struct/array elements.
8151     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8152       return 0;
8153     
8154     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8155       const StructLayout *SL = TD->getStructLayout(STy);
8156       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8157              "Offset must stay within the indexed type");
8158       
8159       unsigned Elt = SL->getElementContainingOffset(Offset);
8160       NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
8161       
8162       Offset -= SL->getElementOffset(Elt);
8163       Ty = STy->getElementType(Elt);
8164     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8165       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8166       assert(EltSize && "Cannot index into a zero-sized array");
8167       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8168       Offset %= EltSize;
8169       Ty = AT->getElementType();
8170     } else {
8171       // Otherwise, we can't index into the middle of this atomic type, bail.
8172       return 0;
8173     }
8174   }
8175   
8176   return Ty;
8177 }
8178
8179 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8180 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8181   Value *Src = CI.getOperand(0);
8182   
8183   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8184     // If casting the result of a getelementptr instruction with no offset, turn
8185     // this into a cast of the original pointer!
8186     if (GEP->hasAllZeroIndices()) {
8187       // Changing the cast operand is usually not a good idea but it is safe
8188       // here because the pointer operand is being replaced with another 
8189       // pointer operand so the opcode doesn't need to change.
8190       Worklist.Add(GEP);
8191       CI.setOperand(0, GEP->getOperand(0));
8192       return &CI;
8193     }
8194     
8195     // If the GEP has a single use, and the base pointer is a bitcast, and the
8196     // GEP computes a constant offset, see if we can convert these three
8197     // instructions into fewer.  This typically happens with unions and other
8198     // non-type-safe code.
8199     if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8200       if (GEP->hasAllConstantIndices()) {
8201         // We are guaranteed to get a constant from EmitGEPOffset.
8202         ConstantInt *OffsetV =
8203                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8204         int64_t Offset = OffsetV->getSExtValue();
8205         
8206         // Get the base pointer input of the bitcast, and the type it points to.
8207         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8208         const Type *GEPIdxTy =
8209           cast<PointerType>(OrigBase->getType())->getElementType();
8210         SmallVector<Value*, 8> NewIndices;
8211         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8212           // If we were able to index down into an element, create the GEP
8213           // and bitcast the result.  This eliminates one bitcast, potentially
8214           // two.
8215           Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8216             Builder->CreateInBoundsGEP(OrigBase,
8217                                        NewIndices.begin(), NewIndices.end()) :
8218             Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
8219           NGEP->takeName(GEP);
8220           
8221           if (isa<BitCastInst>(CI))
8222             return new BitCastInst(NGEP, CI.getType());
8223           assert(isa<PtrToIntInst>(CI));
8224           return new PtrToIntInst(NGEP, CI.getType());
8225         }
8226       }      
8227     }
8228   }
8229     
8230   return commonCastTransforms(CI);
8231 }
8232
8233 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8234 /// type like i42.  We don't want to introduce operations on random non-legal
8235 /// integer types where they don't already exist in the code.  In the future,
8236 /// we should consider making this based off target-data, so that 32-bit targets
8237 /// won't get i64 operations etc.
8238 static bool isSafeIntegerType(const Type *Ty) {
8239   switch (Ty->getPrimitiveSizeInBits()) {
8240   case 8:
8241   case 16:
8242   case 32:
8243   case 64:
8244     return true;
8245   default: 
8246     return false;
8247   }
8248 }
8249
8250 /// commonIntCastTransforms - This function implements the common transforms
8251 /// for trunc, zext, and sext.
8252 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8253   if (Instruction *Result = commonCastTransforms(CI))
8254     return Result;
8255
8256   Value *Src = CI.getOperand(0);
8257   const Type *SrcTy = Src->getType();
8258   const Type *DestTy = CI.getType();
8259   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8260   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8261
8262   // See if we can simplify any instructions used by the LHS whose sole 
8263   // purpose is to compute bits we don't care about.
8264   if (SimplifyDemandedInstructionBits(CI))
8265     return &CI;
8266
8267   // If the source isn't an instruction or has more than one use then we
8268   // can't do anything more. 
8269   Instruction *SrcI = dyn_cast<Instruction>(Src);
8270   if (!SrcI || !Src->hasOneUse())
8271     return 0;
8272
8273   // Attempt to propagate the cast into the instruction for int->int casts.
8274   int NumCastsRemoved = 0;
8275   // Only do this if the dest type is a simple type, don't convert the
8276   // expression tree to something weird like i93 unless the source is also
8277   // strange.
8278   if ((isSafeIntegerType(DestTy->getScalarType()) ||
8279        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8280       CanEvaluateInDifferentType(SrcI, DestTy,
8281                                  CI.getOpcode(), NumCastsRemoved)) {
8282     // If this cast is a truncate, evaluting in a different type always
8283     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8284     // we need to do an AND to maintain the clear top-part of the computation,
8285     // so we require that the input have eliminated at least one cast.  If this
8286     // is a sign extension, we insert two new casts (to do the extension) so we
8287     // require that two casts have been eliminated.
8288     bool DoXForm = false;
8289     bool JustReplace = false;
8290     switch (CI.getOpcode()) {
8291     default:
8292       // All the others use floating point so we shouldn't actually 
8293       // get here because of the check above.
8294       llvm_unreachable("Unknown cast type");
8295     case Instruction::Trunc:
8296       DoXForm = true;
8297       break;
8298     case Instruction::ZExt: {
8299       DoXForm = NumCastsRemoved >= 1;
8300       if (!DoXForm && 0) {
8301         // If it's unnecessary to issue an AND to clear the high bits, it's
8302         // always profitable to do this xform.
8303         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8304         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8305         if (MaskedValueIsZero(TryRes, Mask))
8306           return ReplaceInstUsesWith(CI, TryRes);
8307         
8308         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8309           if (TryI->use_empty())
8310             EraseInstFromFunction(*TryI);
8311       }
8312       break;
8313     }
8314     case Instruction::SExt: {
8315       DoXForm = NumCastsRemoved >= 2;
8316       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8317         // If we do not have to emit the truncate + sext pair, then it's always
8318         // profitable to do this xform.
8319         //
8320         // It's not safe to eliminate the trunc + sext pair if one of the
8321         // eliminated cast is a truncate. e.g.
8322         // t2 = trunc i32 t1 to i16
8323         // t3 = sext i16 t2 to i32
8324         // !=
8325         // i32 t1
8326         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8327         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8328         if (NumSignBits > (DestBitSize - SrcBitSize))
8329           return ReplaceInstUsesWith(CI, TryRes);
8330         
8331         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8332           if (TryI->use_empty())
8333             EraseInstFromFunction(*TryI);
8334       }
8335       break;
8336     }
8337     }
8338     
8339     if (DoXForm) {
8340       DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8341             " to avoid cast: " << CI);
8342       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8343                                            CI.getOpcode() == Instruction::SExt);
8344       if (JustReplace)
8345         // Just replace this cast with the result.
8346         return ReplaceInstUsesWith(CI, Res);
8347
8348       assert(Res->getType() == DestTy);
8349       switch (CI.getOpcode()) {
8350       default: llvm_unreachable("Unknown cast type!");
8351       case Instruction::Trunc:
8352         // Just replace this cast with the result.
8353         return ReplaceInstUsesWith(CI, Res);
8354       case Instruction::ZExt: {
8355         assert(SrcBitSize < DestBitSize && "Not a zext?");
8356
8357         // If the high bits are already zero, just replace this cast with the
8358         // result.
8359         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8360         if (MaskedValueIsZero(Res, Mask))
8361           return ReplaceInstUsesWith(CI, Res);
8362
8363         // We need to emit an AND to clear the high bits.
8364         Constant *C = ConstantInt::get(*Context, 
8365                                  APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8366         return BinaryOperator::CreateAnd(Res, C);
8367       }
8368       case Instruction::SExt: {
8369         // If the high bits are already filled with sign bit, just replace this
8370         // cast with the result.
8371         unsigned NumSignBits = ComputeNumSignBits(Res);
8372         if (NumSignBits > (DestBitSize - SrcBitSize))
8373           return ReplaceInstUsesWith(CI, Res);
8374
8375         // We need to emit a cast to truncate, then a cast to sext.
8376         return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
8377       }
8378       }
8379     }
8380   }
8381   
8382   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8383   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8384
8385   switch (SrcI->getOpcode()) {
8386   case Instruction::Add:
8387   case Instruction::Mul:
8388   case Instruction::And:
8389   case Instruction::Or:
8390   case Instruction::Xor:
8391     // If we are discarding information, rewrite.
8392     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8393       // Don't insert two casts unless at least one can be eliminated.
8394       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8395           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8396         Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8397         Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8398         return BinaryOperator::Create(
8399             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8400       }
8401     }
8402
8403     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8404     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8405         SrcI->getOpcode() == Instruction::Xor &&
8406         Op1 == ConstantInt::getTrue(*Context) &&
8407         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8408       Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
8409       return BinaryOperator::CreateXor(New,
8410                                       ConstantInt::get(CI.getType(), 1));
8411     }
8412     break;
8413
8414   case Instruction::Shl: {
8415     // Canonicalize trunc inside shl, if we can.
8416     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8417     if (CI && DestBitSize < SrcBitSize &&
8418         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8419       Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8420       Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8421       return BinaryOperator::CreateShl(Op0c, Op1c);
8422     }
8423     break;
8424   }
8425   }
8426   return 0;
8427 }
8428
8429 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8430   if (Instruction *Result = commonIntCastTransforms(CI))
8431     return Result;
8432   
8433   Value *Src = CI.getOperand(0);
8434   const Type *Ty = CI.getType();
8435   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8436   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8437
8438   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8439   if (DestBitWidth == 1) {
8440     Constant *One = ConstantInt::get(Src->getType(), 1);
8441     Src = Builder->CreateAnd(Src, One, "tmp");
8442     Value *Zero = Constant::getNullValue(Src->getType());
8443     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8444   }
8445
8446   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8447   ConstantInt *ShAmtV = 0;
8448   Value *ShiftOp = 0;
8449   if (Src->hasOneUse() &&
8450       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8451     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8452     
8453     // Get a mask for the bits shifting in.
8454     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8455     if (MaskedValueIsZero(ShiftOp, Mask)) {
8456       if (ShAmt >= DestBitWidth)        // All zeros.
8457         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8458       
8459       // Okay, we can shrink this.  Truncate the input, then return a new
8460       // shift.
8461       Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
8462       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8463       return BinaryOperator::CreateLShr(V1, V2);
8464     }
8465   }
8466   
8467   return 0;
8468 }
8469
8470 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8471 /// in order to eliminate the icmp.
8472 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8473                                              bool DoXform) {
8474   // If we are just checking for a icmp eq of a single bit and zext'ing it
8475   // to an integer, then shift the bit to the appropriate place and then
8476   // cast to integer to avoid the comparison.
8477   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8478     const APInt &Op1CV = Op1C->getValue();
8479       
8480     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8481     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8482     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8483         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8484       if (!DoXform) return ICI;
8485
8486       Value *In = ICI->getOperand(0);
8487       Value *Sh = ConstantInt::get(In->getType(),
8488                                    In->getType()->getScalarSizeInBits()-1);
8489       In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
8490       if (In->getType() != CI.getType())
8491         In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
8492
8493       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8494         Constant *One = ConstantInt::get(In->getType(), 1);
8495         In = Builder->CreateXor(In, One, In->getName()+".not");
8496       }
8497
8498       return ReplaceInstUsesWith(CI, In);
8499     }
8500       
8501       
8502       
8503     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8504     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8505     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8506     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8507     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8508     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8509     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8510     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8511     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8512         // This only works for EQ and NE
8513         ICI->isEquality()) {
8514       // If Op1C some other power of two, convert:
8515       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8516       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8517       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8518       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8519         
8520       APInt KnownZeroMask(~KnownZero);
8521       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8522         if (!DoXform) return ICI;
8523
8524         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8525         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8526           // (X&4) == 2 --> false
8527           // (X&4) != 2 --> true
8528           Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
8529           Res = ConstantExpr::getZExt(Res, CI.getType());
8530           return ReplaceInstUsesWith(CI, Res);
8531         }
8532           
8533         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8534         Value *In = ICI->getOperand(0);
8535         if (ShiftAmt) {
8536           // Perform a logical shr by shiftamt.
8537           // Insert the shift to put the result in the low bit.
8538           In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8539                                    In->getName()+".lobit");
8540         }
8541           
8542         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8543           Constant *One = ConstantInt::get(In->getType(), 1);
8544           In = Builder->CreateXor(In, One, "tmp");
8545         }
8546           
8547         if (CI.getType() == In->getType())
8548           return ReplaceInstUsesWith(CI, In);
8549         else
8550           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8551       }
8552     }
8553   }
8554
8555   return 0;
8556 }
8557
8558 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8559   // If one of the common conversion will work ..
8560   if (Instruction *Result = commonIntCastTransforms(CI))
8561     return Result;
8562
8563   Value *Src = CI.getOperand(0);
8564
8565   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8566   // types and if the sizes are just right we can convert this into a logical
8567   // 'and' which will be much cheaper than the pair of casts.
8568   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8569     // Get the sizes of the types involved.  We know that the intermediate type
8570     // will be smaller than A or C, but don't know the relation between A and C.
8571     Value *A = CSrc->getOperand(0);
8572     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8573     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8574     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8575     // If we're actually extending zero bits, then if
8576     // SrcSize <  DstSize: zext(a & mask)
8577     // SrcSize == DstSize: a & mask
8578     // SrcSize  > DstSize: trunc(a) & mask
8579     if (SrcSize < DstSize) {
8580       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8581       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8582       Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
8583       return new ZExtInst(And, CI.getType());
8584     }
8585     
8586     if (SrcSize == DstSize) {
8587       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8588       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8589                                                            AndValue));
8590     }
8591     if (SrcSize > DstSize) {
8592       Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
8593       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8594       return BinaryOperator::CreateAnd(Trunc, 
8595                                        ConstantInt::get(Trunc->getType(),
8596                                                                AndValue));
8597     }
8598   }
8599
8600   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8601     return transformZExtICmp(ICI, CI);
8602
8603   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8604   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8605     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8606     // of the (zext icmp) will be transformed.
8607     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8608     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8609     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8610         (transformZExtICmp(LHS, CI, false) ||
8611          transformZExtICmp(RHS, CI, false))) {
8612       Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8613       Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
8614       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8615     }
8616   }
8617
8618   // zext(trunc(t) & C) -> (t & zext(C)).
8619   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8620     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8621       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8622         Value *TI0 = TI->getOperand(0);
8623         if (TI0->getType() == CI.getType())
8624           return
8625             BinaryOperator::CreateAnd(TI0,
8626                                 ConstantExpr::getZExt(C, CI.getType()));
8627       }
8628
8629   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8630   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8631     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8632       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8633         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8634             And->getOperand(1) == C)
8635           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8636             Value *TI0 = TI->getOperand(0);
8637             if (TI0->getType() == CI.getType()) {
8638               Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8639               Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
8640               return BinaryOperator::CreateXor(NewAnd, ZC);
8641             }
8642           }
8643
8644   return 0;
8645 }
8646
8647 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8648   if (Instruction *I = commonIntCastTransforms(CI))
8649     return I;
8650   
8651   Value *Src = CI.getOperand(0);
8652   
8653   // Canonicalize sign-extend from i1 to a select.
8654   if (Src->getType() == Type::getInt1Ty(*Context))
8655     return SelectInst::Create(Src,
8656                               Constant::getAllOnesValue(CI.getType()),
8657                               Constant::getNullValue(CI.getType()));
8658
8659   // See if the value being truncated is already sign extended.  If so, just
8660   // eliminate the trunc/sext pair.
8661   if (Operator::getOpcode(Src) == Instruction::Trunc) {
8662     Value *Op = cast<User>(Src)->getOperand(0);
8663     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8664     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8665     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8666     unsigned NumSignBits = ComputeNumSignBits(Op);
8667
8668     if (OpBits == DestBits) {
8669       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8670       // bits, it is already ready.
8671       if (NumSignBits > DestBits-MidBits)
8672         return ReplaceInstUsesWith(CI, Op);
8673     } else if (OpBits < DestBits) {
8674       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8675       // bits, just sext from i32.
8676       if (NumSignBits > OpBits-MidBits)
8677         return new SExtInst(Op, CI.getType(), "tmp");
8678     } else {
8679       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8680       // bits, just truncate to i32.
8681       if (NumSignBits > OpBits-MidBits)
8682         return new TruncInst(Op, CI.getType(), "tmp");
8683     }
8684   }
8685
8686   // If the input is a shl/ashr pair of a same constant, then this is a sign
8687   // extension from a smaller value.  If we could trust arbitrary bitwidth
8688   // integers, we could turn this into a truncate to the smaller bit and then
8689   // use a sext for the whole extension.  Since we don't, look deeper and check
8690   // for a truncate.  If the source and dest are the same type, eliminate the
8691   // trunc and extend and just do shifts.  For example, turn:
8692   //   %a = trunc i32 %i to i8
8693   //   %b = shl i8 %a, 6
8694   //   %c = ashr i8 %b, 6
8695   //   %d = sext i8 %c to i32
8696   // into:
8697   //   %a = shl i32 %i, 30
8698   //   %d = ashr i32 %a, 30
8699   Value *A = 0;
8700   ConstantInt *BA = 0, *CA = 0;
8701   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8702                         m_ConstantInt(CA))) &&
8703       BA == CA && isa<TruncInst>(A)) {
8704     Value *I = cast<TruncInst>(A)->getOperand(0);
8705     if (I->getType() == CI.getType()) {
8706       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8707       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8708       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8709       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8710       I = Builder->CreateShl(I, ShAmtV, CI.getName());
8711       return BinaryOperator::CreateAShr(I, ShAmtV);
8712     }
8713   }
8714   
8715   return 0;
8716 }
8717
8718 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8719 /// in the specified FP type without changing its value.
8720 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8721                               LLVMContext *Context) {
8722   bool losesInfo;
8723   APFloat F = CFP->getValueAPF();
8724   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8725   if (!losesInfo)
8726     return ConstantFP::get(*Context, F);
8727   return 0;
8728 }
8729
8730 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8731 /// through it until we get the source value.
8732 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8733   if (Instruction *I = dyn_cast<Instruction>(V))
8734     if (I->getOpcode() == Instruction::FPExt)
8735       return LookThroughFPExtensions(I->getOperand(0), Context);
8736   
8737   // If this value is a constant, return the constant in the smallest FP type
8738   // that can accurately represent it.  This allows us to turn
8739   // (float)((double)X+2.0) into x+2.0f.
8740   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8741     if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
8742       return V;  // No constant folding of this.
8743     // See if the value can be truncated to float and then reextended.
8744     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8745       return V;
8746     if (CFP->getType() == Type::getDoubleTy(*Context))
8747       return V;  // Won't shrink.
8748     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8749       return V;
8750     // Don't try to shrink to various long double types.
8751   }
8752   
8753   return V;
8754 }
8755
8756 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8757   if (Instruction *I = commonCastTransforms(CI))
8758     return I;
8759   
8760   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8761   // smaller than the destination type, we can eliminate the truncate by doing
8762   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8763   // many builtins (sqrt, etc).
8764   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8765   if (OpI && OpI->hasOneUse()) {
8766     switch (OpI->getOpcode()) {
8767     default: break;
8768     case Instruction::FAdd:
8769     case Instruction::FSub:
8770     case Instruction::FMul:
8771     case Instruction::FDiv:
8772     case Instruction::FRem:
8773       const Type *SrcTy = OpI->getType();
8774       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8775       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8776       if (LHSTrunc->getType() != SrcTy && 
8777           RHSTrunc->getType() != SrcTy) {
8778         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8779         // If the source types were both smaller than the destination type of
8780         // the cast, do this xform.
8781         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8782             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8783           LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8784           RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
8785           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8786         }
8787       }
8788       break;  
8789     }
8790   }
8791   return 0;
8792 }
8793
8794 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8795   return commonCastTransforms(CI);
8796 }
8797
8798 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8799   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8800   if (OpI == 0)
8801     return commonCastTransforms(FI);
8802
8803   // fptoui(uitofp(X)) --> X
8804   // fptoui(sitofp(X)) --> X
8805   // This is safe if the intermediate type has enough bits in its mantissa to
8806   // accurately represent all values of X.  For example, do not do this with
8807   // i64->float->i64.  This is also safe for sitofp case, because any negative
8808   // 'X' value would cause an undefined result for the fptoui. 
8809   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8810       OpI->getOperand(0)->getType() == FI.getType() &&
8811       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8812                     OpI->getType()->getFPMantissaWidth())
8813     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8814
8815   return commonCastTransforms(FI);
8816 }
8817
8818 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8819   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8820   if (OpI == 0)
8821     return commonCastTransforms(FI);
8822   
8823   // fptosi(sitofp(X)) --> X
8824   // fptosi(uitofp(X)) --> X
8825   // This is safe if the intermediate type has enough bits in its mantissa to
8826   // accurately represent all values of X.  For example, do not do this with
8827   // i64->float->i64.  This is also safe for sitofp case, because any negative
8828   // 'X' value would cause an undefined result for the fptoui. 
8829   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8830       OpI->getOperand(0)->getType() == FI.getType() &&
8831       (int)FI.getType()->getScalarSizeInBits() <=
8832                     OpI->getType()->getFPMantissaWidth())
8833     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8834   
8835   return commonCastTransforms(FI);
8836 }
8837
8838 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8839   return commonCastTransforms(CI);
8840 }
8841
8842 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8843   return commonCastTransforms(CI);
8844 }
8845
8846 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8847   // If the destination integer type is smaller than the intptr_t type for
8848   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8849   // trunc to be exposed to other transforms.  Don't do this for extending
8850   // ptrtoint's, because we don't know if the target sign or zero extends its
8851   // pointers.
8852   if (TD &&
8853       CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8854     Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8855                                        TD->getIntPtrType(CI.getContext()),
8856                                        "tmp");
8857     return new TruncInst(P, CI.getType());
8858   }
8859   
8860   return commonPointerCastTransforms(CI);
8861 }
8862
8863 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8864   // If the source integer type is larger than the intptr_t type for
8865   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8866   // allows the trunc to be exposed to other transforms.  Don't do this for
8867   // extending inttoptr's, because we don't know if the target sign or zero
8868   // extends to pointers.
8869   if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
8870       TD->getPointerSizeInBits()) {
8871     Value *P = Builder->CreateTrunc(CI.getOperand(0),
8872                                     TD->getIntPtrType(CI.getContext()), "tmp");
8873     return new IntToPtrInst(P, CI.getType());
8874   }
8875   
8876   if (Instruction *I = commonCastTransforms(CI))
8877     return I;
8878
8879   return 0;
8880 }
8881
8882 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8883   // If the operands are integer typed then apply the integer transforms,
8884   // otherwise just apply the common ones.
8885   Value *Src = CI.getOperand(0);
8886   const Type *SrcTy = Src->getType();
8887   const Type *DestTy = CI.getType();
8888
8889   if (isa<PointerType>(SrcTy)) {
8890     if (Instruction *I = commonPointerCastTransforms(CI))
8891       return I;
8892   } else {
8893     if (Instruction *Result = commonCastTransforms(CI))
8894       return Result;
8895   }
8896
8897
8898   // Get rid of casts from one type to the same type. These are useless and can
8899   // be replaced by the operand.
8900   if (DestTy == Src->getType())
8901     return ReplaceInstUsesWith(CI, Src);
8902
8903   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8904     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8905     const Type *DstElTy = DstPTy->getElementType();
8906     const Type *SrcElTy = SrcPTy->getElementType();
8907     
8908     // If the address spaces don't match, don't eliminate the bitcast, which is
8909     // required for changing types.
8910     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8911       return 0;
8912     
8913     // If we are casting a alloca to a pointer to a type of the same
8914     // size, rewrite the allocation instruction to allocate the "right" type.
8915     // There is no need to modify malloc calls because it is their bitcast that
8916     // needs to be cleaned up.
8917     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8918       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8919         return V;
8920     
8921     // If the source and destination are pointers, and this cast is equivalent
8922     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8923     // This can enhance SROA and other transforms that want type-safe pointers.
8924     Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
8925     unsigned NumZeros = 0;
8926     while (SrcElTy != DstElTy && 
8927            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8928            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8929       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8930       ++NumZeros;
8931     }
8932
8933     // If we found a path from the src to dest, create the getelementptr now.
8934     if (SrcElTy == DstElTy) {
8935       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8936       return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8937                                                ((Instruction*) NULL));
8938     }
8939   }
8940
8941   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8942     if (DestVTy->getNumElements() == 1) {
8943       if (!isa<VectorType>(SrcTy)) {
8944         Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
8945         return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
8946                             Constant::getNullValue(Type::getInt32Ty(*Context)));
8947       }
8948       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8949     }
8950   }
8951
8952   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8953     if (SrcVTy->getNumElements() == 1) {
8954       if (!isa<VectorType>(DestTy)) {
8955         Value *Elem = 
8956           Builder->CreateExtractElement(Src,
8957                             Constant::getNullValue(Type::getInt32Ty(*Context)));
8958         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8959       }
8960     }
8961   }
8962
8963   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8964     if (SVI->hasOneUse()) {
8965       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8966       // a bitconvert to a vector with the same # elts.
8967       if (isa<VectorType>(DestTy) && 
8968           cast<VectorType>(DestTy)->getNumElements() ==
8969                 SVI->getType()->getNumElements() &&
8970           SVI->getType()->getNumElements() ==
8971             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8972         CastInst *Tmp;
8973         // If either of the operands is a cast from CI.getType(), then
8974         // evaluating the shuffle in the casted destination's type will allow
8975         // us to eliminate at least one cast.
8976         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8977              Tmp->getOperand(0)->getType() == DestTy) ||
8978             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8979              Tmp->getOperand(0)->getType() == DestTy)) {
8980           Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8981           Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
8982           // Return a new shuffle vector.  Use the same element ID's, as we
8983           // know the vector types match #elts.
8984           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8985         }
8986       }
8987     }
8988   }
8989   return 0;
8990 }
8991
8992 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8993 ///   %C = or %A, %B
8994 ///   %D = select %cond, %C, %A
8995 /// into:
8996 ///   %C = select %cond, %B, 0
8997 ///   %D = or %A, %C
8998 ///
8999 /// Assuming that the specified instruction is an operand to the select, return
9000 /// a bitmask indicating which operands of this instruction are foldable if they
9001 /// equal the other incoming value of the select.
9002 ///
9003 static unsigned GetSelectFoldableOperands(Instruction *I) {
9004   switch (I->getOpcode()) {
9005   case Instruction::Add:
9006   case Instruction::Mul:
9007   case Instruction::And:
9008   case Instruction::Or:
9009   case Instruction::Xor:
9010     return 3;              // Can fold through either operand.
9011   case Instruction::Sub:   // Can only fold on the amount subtracted.
9012   case Instruction::Shl:   // Can only fold on the shift amount.
9013   case Instruction::LShr:
9014   case Instruction::AShr:
9015     return 1;
9016   default:
9017     return 0;              // Cannot fold
9018   }
9019 }
9020
9021 /// GetSelectFoldableConstant - For the same transformation as the previous
9022 /// function, return the identity constant that goes into the select.
9023 static Constant *GetSelectFoldableConstant(Instruction *I,
9024                                            LLVMContext *Context) {
9025   switch (I->getOpcode()) {
9026   default: llvm_unreachable("This cannot happen!");
9027   case Instruction::Add:
9028   case Instruction::Sub:
9029   case Instruction::Or:
9030   case Instruction::Xor:
9031   case Instruction::Shl:
9032   case Instruction::LShr:
9033   case Instruction::AShr:
9034     return Constant::getNullValue(I->getType());
9035   case Instruction::And:
9036     return Constant::getAllOnesValue(I->getType());
9037   case Instruction::Mul:
9038     return ConstantInt::get(I->getType(), 1);
9039   }
9040 }
9041
9042 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9043 /// have the same opcode and only one use each.  Try to simplify this.
9044 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9045                                           Instruction *FI) {
9046   if (TI->getNumOperands() == 1) {
9047     // If this is a non-volatile load or a cast from the same type,
9048     // merge.
9049     if (TI->isCast()) {
9050       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9051         return 0;
9052     } else {
9053       return 0;  // unknown unary op.
9054     }
9055
9056     // Fold this by inserting a select from the input values.
9057     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9058                                           FI->getOperand(0), SI.getName()+".v");
9059     InsertNewInstBefore(NewSI, SI);
9060     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9061                             TI->getType());
9062   }
9063
9064   // Only handle binary operators here.
9065   if (!isa<BinaryOperator>(TI))
9066     return 0;
9067
9068   // Figure out if the operations have any operands in common.
9069   Value *MatchOp, *OtherOpT, *OtherOpF;
9070   bool MatchIsOpZero;
9071   if (TI->getOperand(0) == FI->getOperand(0)) {
9072     MatchOp  = TI->getOperand(0);
9073     OtherOpT = TI->getOperand(1);
9074     OtherOpF = FI->getOperand(1);
9075     MatchIsOpZero = true;
9076   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9077     MatchOp  = TI->getOperand(1);
9078     OtherOpT = TI->getOperand(0);
9079     OtherOpF = FI->getOperand(0);
9080     MatchIsOpZero = false;
9081   } else if (!TI->isCommutative()) {
9082     return 0;
9083   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9084     MatchOp  = TI->getOperand(0);
9085     OtherOpT = TI->getOperand(1);
9086     OtherOpF = FI->getOperand(0);
9087     MatchIsOpZero = true;
9088   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9089     MatchOp  = TI->getOperand(1);
9090     OtherOpT = TI->getOperand(0);
9091     OtherOpF = FI->getOperand(1);
9092     MatchIsOpZero = true;
9093   } else {
9094     return 0;
9095   }
9096
9097   // If we reach here, they do have operations in common.
9098   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9099                                          OtherOpF, SI.getName()+".v");
9100   InsertNewInstBefore(NewSI, SI);
9101
9102   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9103     if (MatchIsOpZero)
9104       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9105     else
9106       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9107   }
9108   llvm_unreachable("Shouldn't get here");
9109   return 0;
9110 }
9111
9112 static bool isSelect01(Constant *C1, Constant *C2) {
9113   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9114   if (!C1I)
9115     return false;
9116   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9117   if (!C2I)
9118     return false;
9119   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9120 }
9121
9122 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9123 /// facilitate further optimization.
9124 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9125                                             Value *FalseVal) {
9126   // See the comment above GetSelectFoldableOperands for a description of the
9127   // transformation we are doing here.
9128   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9129     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9130         !isa<Constant>(FalseVal)) {
9131       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9132         unsigned OpToFold = 0;
9133         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9134           OpToFold = 1;
9135         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9136           OpToFold = 2;
9137         }
9138
9139         if (OpToFold) {
9140           Constant *C = GetSelectFoldableConstant(TVI, Context);
9141           Value *OOp = TVI->getOperand(2-OpToFold);
9142           // Avoid creating select between 2 constants unless it's selecting
9143           // between 0 and 1.
9144           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9145             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9146             InsertNewInstBefore(NewSel, SI);
9147             NewSel->takeName(TVI);
9148             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9149               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9150             llvm_unreachable("Unknown instruction!!");
9151           }
9152         }
9153       }
9154     }
9155   }
9156
9157   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9158     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9159         !isa<Constant>(TrueVal)) {
9160       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9161         unsigned OpToFold = 0;
9162         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9163           OpToFold = 1;
9164         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9165           OpToFold = 2;
9166         }
9167
9168         if (OpToFold) {
9169           Constant *C = GetSelectFoldableConstant(FVI, Context);
9170           Value *OOp = FVI->getOperand(2-OpToFold);
9171           // Avoid creating select between 2 constants unless it's selecting
9172           // between 0 and 1.
9173           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9174             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9175             InsertNewInstBefore(NewSel, SI);
9176             NewSel->takeName(FVI);
9177             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9178               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9179             llvm_unreachable("Unknown instruction!!");
9180           }
9181         }
9182       }
9183     }
9184   }
9185
9186   return 0;
9187 }
9188
9189 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9190 /// ICmpInst as its first operand.
9191 ///
9192 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9193                                                    ICmpInst *ICI) {
9194   bool Changed = false;
9195   ICmpInst::Predicate Pred = ICI->getPredicate();
9196   Value *CmpLHS = ICI->getOperand(0);
9197   Value *CmpRHS = ICI->getOperand(1);
9198   Value *TrueVal = SI.getTrueValue();
9199   Value *FalseVal = SI.getFalseValue();
9200
9201   // Check cases where the comparison is with a constant that
9202   // can be adjusted to fit the min/max idiom. We may edit ICI in
9203   // place here, so make sure the select is the only user.
9204   if (ICI->hasOneUse())
9205     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9206       switch (Pred) {
9207       default: break;
9208       case ICmpInst::ICMP_ULT:
9209       case ICmpInst::ICMP_SLT: {
9210         // X < MIN ? T : F  -->  F
9211         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9212           return ReplaceInstUsesWith(SI, FalseVal);
9213         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9214         Constant *AdjustedRHS = SubOne(CI);
9215         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9216             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9217           Pred = ICmpInst::getSwappedPredicate(Pred);
9218           CmpRHS = AdjustedRHS;
9219           std::swap(FalseVal, TrueVal);
9220           ICI->setPredicate(Pred);
9221           ICI->setOperand(1, CmpRHS);
9222           SI.setOperand(1, TrueVal);
9223           SI.setOperand(2, FalseVal);
9224           Changed = true;
9225         }
9226         break;
9227       }
9228       case ICmpInst::ICMP_UGT:
9229       case ICmpInst::ICMP_SGT: {
9230         // X > MAX ? T : F  -->  F
9231         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9232           return ReplaceInstUsesWith(SI, FalseVal);
9233         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9234         Constant *AdjustedRHS = AddOne(CI);
9235         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9236             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9237           Pred = ICmpInst::getSwappedPredicate(Pred);
9238           CmpRHS = AdjustedRHS;
9239           std::swap(FalseVal, TrueVal);
9240           ICI->setPredicate(Pred);
9241           ICI->setOperand(1, CmpRHS);
9242           SI.setOperand(1, TrueVal);
9243           SI.setOperand(2, FalseVal);
9244           Changed = true;
9245         }
9246         break;
9247       }
9248       }
9249
9250       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9251       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9252       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9253       if (match(TrueVal, m_ConstantInt<-1>()) &&
9254           match(FalseVal, m_ConstantInt<0>()))
9255         Pred = ICI->getPredicate();
9256       else if (match(TrueVal, m_ConstantInt<0>()) &&
9257                match(FalseVal, m_ConstantInt<-1>()))
9258         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9259       
9260       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9261         // If we are just checking for a icmp eq of a single bit and zext'ing it
9262         // to an integer, then shift the bit to the appropriate place and then
9263         // cast to integer to avoid the comparison.
9264         const APInt &Op1CV = CI->getValue();
9265     
9266         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9267         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9268         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9269             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9270           Value *In = ICI->getOperand(0);
9271           Value *Sh = ConstantInt::get(In->getType(),
9272                                        In->getType()->getScalarSizeInBits()-1);
9273           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9274                                                         In->getName()+".lobit"),
9275                                    *ICI);
9276           if (In->getType() != SI.getType())
9277             In = CastInst::CreateIntegerCast(In, SI.getType(),
9278                                              true/*SExt*/, "tmp", ICI);
9279     
9280           if (Pred == ICmpInst::ICMP_SGT)
9281             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9282                                        In->getName()+".not"), *ICI);
9283     
9284           return ReplaceInstUsesWith(SI, In);
9285         }
9286       }
9287     }
9288
9289   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9290     // Transform (X == Y) ? X : Y  -> Y
9291     if (Pred == ICmpInst::ICMP_EQ)
9292       return ReplaceInstUsesWith(SI, FalseVal);
9293     // Transform (X != Y) ? X : Y  -> X
9294     if (Pred == ICmpInst::ICMP_NE)
9295       return ReplaceInstUsesWith(SI, TrueVal);
9296     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9297
9298   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9299     // Transform (X == Y) ? Y : X  -> X
9300     if (Pred == ICmpInst::ICMP_EQ)
9301       return ReplaceInstUsesWith(SI, FalseVal);
9302     // Transform (X != Y) ? Y : X  -> Y
9303     if (Pred == ICmpInst::ICMP_NE)
9304       return ReplaceInstUsesWith(SI, TrueVal);
9305     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9306   }
9307
9308   /// NOTE: if we wanted to, this is where to detect integer ABS
9309
9310   return Changed ? &SI : 0;
9311 }
9312
9313 /// isDefinedInBB - Return true if the value is an instruction defined in the
9314 /// specified basicblock.
9315 static bool isDefinedInBB(const Value *V, const BasicBlock *BB) {
9316   const Instruction *I = dyn_cast<Instruction>(V);
9317   return I != 0 && I->getParent() == BB;
9318 }
9319
9320
9321 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9322   Value *CondVal = SI.getCondition();
9323   Value *TrueVal = SI.getTrueValue();
9324   Value *FalseVal = SI.getFalseValue();
9325
9326   // select true, X, Y  -> X
9327   // select false, X, Y -> Y
9328   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9329     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9330
9331   // select C, X, X -> X
9332   if (TrueVal == FalseVal)
9333     return ReplaceInstUsesWith(SI, TrueVal);
9334
9335   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9336     return ReplaceInstUsesWith(SI, FalseVal);
9337   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9338     return ReplaceInstUsesWith(SI, TrueVal);
9339   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9340     if (isa<Constant>(TrueVal))
9341       return ReplaceInstUsesWith(SI, TrueVal);
9342     else
9343       return ReplaceInstUsesWith(SI, FalseVal);
9344   }
9345
9346   if (SI.getType() == Type::getInt1Ty(*Context)) {
9347     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9348       if (C->getZExtValue()) {
9349         // Change: A = select B, true, C --> A = or B, C
9350         return BinaryOperator::CreateOr(CondVal, FalseVal);
9351       } else {
9352         // Change: A = select B, false, C --> A = and !B, C
9353         Value *NotCond =
9354           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9355                                              "not."+CondVal->getName()), SI);
9356         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9357       }
9358     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9359       if (C->getZExtValue() == false) {
9360         // Change: A = select B, C, false --> A = and B, C
9361         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9362       } else {
9363         // Change: A = select B, C, true --> A = or !B, C
9364         Value *NotCond =
9365           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9366                                              "not."+CondVal->getName()), SI);
9367         return BinaryOperator::CreateOr(NotCond, TrueVal);
9368       }
9369     }
9370     
9371     // select a, b, a  -> a&b
9372     // select a, a, b  -> a|b
9373     if (CondVal == TrueVal)
9374       return BinaryOperator::CreateOr(CondVal, FalseVal);
9375     else if (CondVal == FalseVal)
9376       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9377   }
9378
9379   // Selecting between two integer constants?
9380   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9381     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9382       // select C, 1, 0 -> zext C to int
9383       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9384         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9385       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9386         // select C, 0, 1 -> zext !C to int
9387         Value *NotCond =
9388           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9389                                                "not."+CondVal->getName()), SI);
9390         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9391       }
9392
9393       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9394         // If one of the constants is zero (we know they can't both be) and we
9395         // have an icmp instruction with zero, and we have an 'and' with the
9396         // non-constant value, eliminate this whole mess.  This corresponds to
9397         // cases like this: ((X & 27) ? 27 : 0)
9398         if (TrueValC->isZero() || FalseValC->isZero())
9399           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9400               cast<Constant>(IC->getOperand(1))->isNullValue())
9401             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9402               if (ICA->getOpcode() == Instruction::And &&
9403                   isa<ConstantInt>(ICA->getOperand(1)) &&
9404                   (ICA->getOperand(1) == TrueValC ||
9405                    ICA->getOperand(1) == FalseValC) &&
9406                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9407                 // Okay, now we know that everything is set up, we just don't
9408                 // know whether we have a icmp_ne or icmp_eq and whether the 
9409                 // true or false val is the zero.
9410                 bool ShouldNotVal = !TrueValC->isZero();
9411                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9412                 Value *V = ICA;
9413                 if (ShouldNotVal)
9414                   V = InsertNewInstBefore(BinaryOperator::Create(
9415                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9416                 return ReplaceInstUsesWith(SI, V);
9417               }
9418       }
9419     }
9420
9421   // See if we are selecting two values based on a comparison of the two values.
9422   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9423     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9424       // Transform (X == Y) ? X : Y  -> Y
9425       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9426         // This is not safe in general for floating point:  
9427         // consider X== -0, Y== +0.
9428         // It becomes safe if either operand is a nonzero constant.
9429         ConstantFP *CFPt, *CFPf;
9430         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9431               !CFPt->getValueAPF().isZero()) ||
9432             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9433              !CFPf->getValueAPF().isZero()))
9434         return ReplaceInstUsesWith(SI, FalseVal);
9435       }
9436       // Transform (X != Y) ? X : Y  -> X
9437       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9438         return ReplaceInstUsesWith(SI, TrueVal);
9439       // NOTE: if we wanted to, this is where to detect MIN/MAX
9440
9441     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9442       // Transform (X == Y) ? Y : X  -> X
9443       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9444         // This is not safe in general for floating point:  
9445         // consider X== -0, Y== +0.
9446         // It becomes safe if either operand is a nonzero constant.
9447         ConstantFP *CFPt, *CFPf;
9448         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9449               !CFPt->getValueAPF().isZero()) ||
9450             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9451              !CFPf->getValueAPF().isZero()))
9452           return ReplaceInstUsesWith(SI, FalseVal);
9453       }
9454       // Transform (X != Y) ? Y : X  -> Y
9455       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9456         return ReplaceInstUsesWith(SI, TrueVal);
9457       // NOTE: if we wanted to, this is where to detect MIN/MAX
9458     }
9459     // NOTE: if we wanted to, this is where to detect ABS
9460   }
9461
9462   // See if we are selecting two values based on a comparison of the two values.
9463   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9464     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9465       return Result;
9466
9467   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9468     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9469       if (TI->hasOneUse() && FI->hasOneUse()) {
9470         Instruction *AddOp = 0, *SubOp = 0;
9471
9472         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9473         if (TI->getOpcode() == FI->getOpcode())
9474           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9475             return IV;
9476
9477         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9478         // even legal for FP.
9479         if ((TI->getOpcode() == Instruction::Sub &&
9480              FI->getOpcode() == Instruction::Add) ||
9481             (TI->getOpcode() == Instruction::FSub &&
9482              FI->getOpcode() == Instruction::FAdd)) {
9483           AddOp = FI; SubOp = TI;
9484         } else if ((FI->getOpcode() == Instruction::Sub &&
9485                     TI->getOpcode() == Instruction::Add) ||
9486                    (FI->getOpcode() == Instruction::FSub &&
9487                     TI->getOpcode() == Instruction::FAdd)) {
9488           AddOp = TI; SubOp = FI;
9489         }
9490
9491         if (AddOp) {
9492           Value *OtherAddOp = 0;
9493           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9494             OtherAddOp = AddOp->getOperand(1);
9495           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9496             OtherAddOp = AddOp->getOperand(0);
9497           }
9498
9499           if (OtherAddOp) {
9500             // So at this point we know we have (Y -> OtherAddOp):
9501             //        select C, (add X, Y), (sub X, Z)
9502             Value *NegVal;  // Compute -Z
9503             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9504               NegVal = ConstantExpr::getNeg(C);
9505             } else {
9506               NegVal = InsertNewInstBefore(
9507                     BinaryOperator::CreateNeg(SubOp->getOperand(1),
9508                                               "tmp"), SI);
9509             }
9510
9511             Value *NewTrueOp = OtherAddOp;
9512             Value *NewFalseOp = NegVal;
9513             if (AddOp != TI)
9514               std::swap(NewTrueOp, NewFalseOp);
9515             Instruction *NewSel =
9516               SelectInst::Create(CondVal, NewTrueOp,
9517                                  NewFalseOp, SI.getName() + ".p");
9518
9519             NewSel = InsertNewInstBefore(NewSel, SI);
9520             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9521           }
9522         }
9523       }
9524
9525   // See if we can fold the select into one of our operands.
9526   if (SI.getType()->isInteger()) {
9527     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9528     if (FoldI)
9529       return FoldI;
9530   }
9531
9532   // See if we can fold the select into a phi node.  The true/false values have
9533   // to be live in the predecessor blocks.  If they are instructions in SI's
9534   // block, we can't map to the predecessor.
9535   if (isa<PHINode>(SI.getCondition()) &&
9536       (!isDefinedInBB(SI.getTrueValue(), SI.getParent()) ||
9537        isa<PHINode>(SI.getTrueValue())) &&
9538       (!isDefinedInBB(SI.getFalseValue(), SI.getParent()) ||
9539        isa<PHINode>(SI.getFalseValue())))
9540     if (Instruction *NV = FoldOpIntoPhi(SI))
9541       return NV;
9542
9543   if (BinaryOperator::isNot(CondVal)) {
9544     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9545     SI.setOperand(1, FalseVal);
9546     SI.setOperand(2, TrueVal);
9547     return &SI;
9548   }
9549
9550   return 0;
9551 }
9552
9553 /// EnforceKnownAlignment - If the specified pointer points to an object that
9554 /// we control, modify the object's alignment to PrefAlign. This isn't
9555 /// often possible though. If alignment is important, a more reliable approach
9556 /// is to simply align all global variables and allocation instructions to
9557 /// their preferred alignment from the beginning.
9558 ///
9559 static unsigned EnforceKnownAlignment(Value *V,
9560                                       unsigned Align, unsigned PrefAlign) {
9561
9562   User *U = dyn_cast<User>(V);
9563   if (!U) return Align;
9564
9565   switch (Operator::getOpcode(U)) {
9566   default: break;
9567   case Instruction::BitCast:
9568     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9569   case Instruction::GetElementPtr: {
9570     // If all indexes are zero, it is just the alignment of the base pointer.
9571     bool AllZeroOperands = true;
9572     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9573       if (!isa<Constant>(*i) ||
9574           !cast<Constant>(*i)->isNullValue()) {
9575         AllZeroOperands = false;
9576         break;
9577       }
9578
9579     if (AllZeroOperands) {
9580       // Treat this like a bitcast.
9581       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9582     }
9583     break;
9584   }
9585   }
9586
9587   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9588     // If there is a large requested alignment and we can, bump up the alignment
9589     // of the global.
9590     if (!GV->isDeclaration()) {
9591       if (GV->getAlignment() >= PrefAlign)
9592         Align = GV->getAlignment();
9593       else {
9594         GV->setAlignment(PrefAlign);
9595         Align = PrefAlign;
9596       }
9597     }
9598   } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9599     // If there is a requested alignment and if this is an alloca, round up.
9600     if (AI->getAlignment() >= PrefAlign)
9601       Align = AI->getAlignment();
9602     else {
9603       AI->setAlignment(PrefAlign);
9604       Align = PrefAlign;
9605     }
9606   }
9607
9608   return Align;
9609 }
9610
9611 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9612 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9613 /// and it is more than the alignment of the ultimate object, see if we can
9614 /// increase the alignment of the ultimate object, making this check succeed.
9615 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9616                                                   unsigned PrefAlign) {
9617   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9618                       sizeof(PrefAlign) * CHAR_BIT;
9619   APInt Mask = APInt::getAllOnesValue(BitWidth);
9620   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9621   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9622   unsigned TrailZ = KnownZero.countTrailingOnes();
9623   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9624
9625   if (PrefAlign > Align)
9626     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9627   
9628     // We don't need to make any adjustment.
9629   return Align;
9630 }
9631
9632 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9633   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9634   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9635   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9636   unsigned CopyAlign = MI->getAlignment();
9637
9638   if (CopyAlign < MinAlign) {
9639     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), 
9640                                              MinAlign, false));
9641     return MI;
9642   }
9643   
9644   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9645   // load/store.
9646   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9647   if (MemOpLength == 0) return 0;
9648   
9649   // Source and destination pointer types are always "i8*" for intrinsic.  See
9650   // if the size is something we can handle with a single primitive load/store.
9651   // A single load+store correctly handles overlapping memory in the memmove
9652   // case.
9653   unsigned Size = MemOpLength->getZExtValue();
9654   if (Size == 0) return MI;  // Delete this mem transfer.
9655   
9656   if (Size > 8 || (Size&(Size-1)))
9657     return 0;  // If not 1/2/4/8 bytes, exit.
9658   
9659   // Use an integer load+store unless we can find something better.
9660   Type *NewPtrTy =
9661                 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
9662   
9663   // Memcpy forces the use of i8* for the source and destination.  That means
9664   // that if you're using memcpy to move one double around, you'll get a cast
9665   // from double* to i8*.  We'd much rather use a double load+store rather than
9666   // an i64 load+store, here because this improves the odds that the source or
9667   // dest address will be promotable.  See if we can find a better type than the
9668   // integer datatype.
9669   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9670     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9671     if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9672       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9673       // down through these levels if so.
9674       while (!SrcETy->isSingleValueType()) {
9675         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9676           if (STy->getNumElements() == 1)
9677             SrcETy = STy->getElementType(0);
9678           else
9679             break;
9680         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9681           if (ATy->getNumElements() == 1)
9682             SrcETy = ATy->getElementType();
9683           else
9684             break;
9685         } else
9686           break;
9687       }
9688       
9689       if (SrcETy->isSingleValueType())
9690         NewPtrTy = PointerType::getUnqual(SrcETy);
9691     }
9692   }
9693   
9694   
9695   // If the memcpy/memmove provides better alignment info than we can
9696   // infer, use it.
9697   SrcAlign = std::max(SrcAlign, CopyAlign);
9698   DstAlign = std::max(DstAlign, CopyAlign);
9699   
9700   Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9701   Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
9702   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9703   InsertNewInstBefore(L, *MI);
9704   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9705
9706   // Set the size of the copy to 0, it will be deleted on the next iteration.
9707   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9708   return MI;
9709 }
9710
9711 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9712   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9713   if (MI->getAlignment() < Alignment) {
9714     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9715                                              Alignment, false));
9716     return MI;
9717   }
9718   
9719   // Extract the length and alignment and fill if they are constant.
9720   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9721   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9722   if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
9723     return 0;
9724   uint64_t Len = LenC->getZExtValue();
9725   Alignment = MI->getAlignment();
9726   
9727   // If the length is zero, this is a no-op
9728   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9729   
9730   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9731   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9732     const Type *ITy = IntegerType::get(*Context, Len*8);  // n=1 -> i8.
9733     
9734     Value *Dest = MI->getDest();
9735     Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
9736
9737     // Alignment 0 is identity for alignment 1 for memset, but not store.
9738     if (Alignment == 0) Alignment = 1;
9739     
9740     // Extract the fill value and store.
9741     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9742     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
9743                                       Dest, false, Alignment), *MI);
9744     
9745     // Set the size of the copy to 0, it will be deleted on the next iteration.
9746     MI->setLength(Constant::getNullValue(LenC->getType()));
9747     return MI;
9748   }
9749
9750   return 0;
9751 }
9752
9753
9754 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9755 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9756 /// the heavy lifting.
9757 ///
9758 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9759   // If the caller function is nounwind, mark the call as nounwind, even if the
9760   // callee isn't.
9761   if (CI.getParent()->getParent()->doesNotThrow() &&
9762       !CI.doesNotThrow()) {
9763     CI.setDoesNotThrow();
9764     return &CI;
9765   }
9766   
9767   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9768   if (!II) return visitCallSite(&CI);
9769   
9770   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9771   // visitCallSite.
9772   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9773     bool Changed = false;
9774
9775     // memmove/cpy/set of zero bytes is a noop.
9776     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9777       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9778
9779       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9780         if (CI->getZExtValue() == 1) {
9781           // Replace the instruction with just byte operations.  We would
9782           // transform other cases to loads/stores, but we don't know if
9783           // alignment is sufficient.
9784         }
9785     }
9786
9787     // If we have a memmove and the source operation is a constant global,
9788     // then the source and dest pointers can't alias, so we can change this
9789     // into a call to memcpy.
9790     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9791       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9792         if (GVSrc->isConstant()) {
9793           Module *M = CI.getParent()->getParent()->getParent();
9794           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9795           const Type *Tys[1];
9796           Tys[0] = CI.getOperand(3)->getType();
9797           CI.setOperand(0, 
9798                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9799           Changed = true;
9800         }
9801
9802       // memmove(x,x,size) -> noop.
9803       if (MMI->getSource() == MMI->getDest())
9804         return EraseInstFromFunction(CI);
9805     }
9806
9807     // If we can determine a pointer alignment that is bigger than currently
9808     // set, update the alignment.
9809     if (isa<MemTransferInst>(MI)) {
9810       if (Instruction *I = SimplifyMemTransfer(MI))
9811         return I;
9812     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9813       if (Instruction *I = SimplifyMemSet(MSI))
9814         return I;
9815     }
9816           
9817     if (Changed) return II;
9818   }
9819   
9820   switch (II->getIntrinsicID()) {
9821   default: break;
9822   case Intrinsic::bswap:
9823     // bswap(bswap(x)) -> x
9824     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9825       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9826         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9827     break;
9828   case Intrinsic::ppc_altivec_lvx:
9829   case Intrinsic::ppc_altivec_lvxl:
9830   case Intrinsic::x86_sse_loadu_ps:
9831   case Intrinsic::x86_sse2_loadu_pd:
9832   case Intrinsic::x86_sse2_loadu_dq:
9833     // Turn PPC lvx     -> load if the pointer is known aligned.
9834     // Turn X86 loadups -> load if the pointer is known aligned.
9835     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9836       Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9837                                          PointerType::getUnqual(II->getType()));
9838       return new LoadInst(Ptr);
9839     }
9840     break;
9841   case Intrinsic::ppc_altivec_stvx:
9842   case Intrinsic::ppc_altivec_stvxl:
9843     // Turn stvx -> store if the pointer is known aligned.
9844     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9845       const Type *OpPtrTy = 
9846         PointerType::getUnqual(II->getOperand(1)->getType());
9847       Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
9848       return new StoreInst(II->getOperand(1), Ptr);
9849     }
9850     break;
9851   case Intrinsic::x86_sse_storeu_ps:
9852   case Intrinsic::x86_sse2_storeu_pd:
9853   case Intrinsic::x86_sse2_storeu_dq:
9854     // Turn X86 storeu -> store if the pointer is known aligned.
9855     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9856       const Type *OpPtrTy = 
9857         PointerType::getUnqual(II->getOperand(2)->getType());
9858       Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
9859       return new StoreInst(II->getOperand(2), Ptr);
9860     }
9861     break;
9862     
9863   case Intrinsic::x86_sse_cvttss2si: {
9864     // These intrinsics only demands the 0th element of its input vector.  If
9865     // we can simplify the input based on that, do so now.
9866     unsigned VWidth =
9867       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9868     APInt DemandedElts(VWidth, 1);
9869     APInt UndefElts(VWidth, 0);
9870     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9871                                               UndefElts)) {
9872       II->setOperand(1, V);
9873       return II;
9874     }
9875     break;
9876   }
9877     
9878   case Intrinsic::ppc_altivec_vperm:
9879     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9880     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9881       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9882       
9883       // Check that all of the elements are integer constants or undefs.
9884       bool AllEltsOk = true;
9885       for (unsigned i = 0; i != 16; ++i) {
9886         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9887             !isa<UndefValue>(Mask->getOperand(i))) {
9888           AllEltsOk = false;
9889           break;
9890         }
9891       }
9892       
9893       if (AllEltsOk) {
9894         // Cast the input vectors to byte vectors.
9895         Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9896         Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
9897         Value *Result = UndefValue::get(Op0->getType());
9898         
9899         // Only extract each element once.
9900         Value *ExtractedElts[32];
9901         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9902         
9903         for (unsigned i = 0; i != 16; ++i) {
9904           if (isa<UndefValue>(Mask->getOperand(i)))
9905             continue;
9906           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9907           Idx &= 31;  // Match the hardware behavior.
9908           
9909           if (ExtractedElts[Idx] == 0) {
9910             ExtractedElts[Idx] = 
9911               Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1, 
9912                   ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9913                                             "tmp");
9914           }
9915         
9916           // Insert this value into the result vector.
9917           Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9918                          ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9919                                                 "tmp");
9920         }
9921         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9922       }
9923     }
9924     break;
9925
9926   case Intrinsic::stackrestore: {
9927     // If the save is right next to the restore, remove the restore.  This can
9928     // happen when variable allocas are DCE'd.
9929     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9930       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9931         BasicBlock::iterator BI = SS;
9932         if (&*++BI == II)
9933           return EraseInstFromFunction(CI);
9934       }
9935     }
9936     
9937     // Scan down this block to see if there is another stack restore in the
9938     // same block without an intervening call/alloca.
9939     BasicBlock::iterator BI = II;
9940     TerminatorInst *TI = II->getParent()->getTerminator();
9941     bool CannotRemove = false;
9942     for (++BI; &*BI != TI; ++BI) {
9943       if (isa<AllocaInst>(BI) || isMalloc(BI)) {
9944         CannotRemove = true;
9945         break;
9946       }
9947       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9948         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9949           // If there is a stackrestore below this one, remove this one.
9950           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9951             return EraseInstFromFunction(CI);
9952           // Otherwise, ignore the intrinsic.
9953         } else {
9954           // If we found a non-intrinsic call, we can't remove the stack
9955           // restore.
9956           CannotRemove = true;
9957           break;
9958         }
9959       }
9960     }
9961     
9962     // If the stack restore is in a return/unwind block and if there are no
9963     // allocas or calls between the restore and the return, nuke the restore.
9964     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9965       return EraseInstFromFunction(CI);
9966     break;
9967   }
9968   }
9969
9970   return visitCallSite(II);
9971 }
9972
9973 // InvokeInst simplification
9974 //
9975 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9976   return visitCallSite(&II);
9977 }
9978
9979 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9980 /// passed through the varargs area, we can eliminate the use of the cast.
9981 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9982                                          const CastInst * const CI,
9983                                          const TargetData * const TD,
9984                                          const int ix) {
9985   if (!CI->isLosslessCast())
9986     return false;
9987
9988   // The size of ByVal arguments is derived from the type, so we
9989   // can't change to a type with a different size.  If the size were
9990   // passed explicitly we could avoid this check.
9991   if (!CS.paramHasAttr(ix, Attribute::ByVal))
9992     return true;
9993
9994   const Type* SrcTy = 
9995             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9996   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9997   if (!SrcTy->isSized() || !DstTy->isSized())
9998     return false;
9999   if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10000     return false;
10001   return true;
10002 }
10003
10004 // visitCallSite - Improvements for call and invoke instructions.
10005 //
10006 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10007   bool Changed = false;
10008
10009   // If the callee is a constexpr cast of a function, attempt to move the cast
10010   // to the arguments of the call/invoke.
10011   if (transformConstExprCastCall(CS)) return 0;
10012
10013   Value *Callee = CS.getCalledValue();
10014
10015   if (Function *CalleeF = dyn_cast<Function>(Callee))
10016     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10017       Instruction *OldCall = CS.getInstruction();
10018       // If the call and callee calling conventions don't match, this call must
10019       // be unreachable, as the call is undefined.
10020       new StoreInst(ConstantInt::getTrue(*Context),
10021                 UndefValue::get(Type::getInt1PtrTy(*Context)), 
10022                                   OldCall);
10023       // If OldCall dues not return void then replaceAllUsesWith undef.
10024       // This allows ValueHandlers and custom metadata to adjust itself.
10025       if (!OldCall->getType()->isVoidTy())
10026         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
10027       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10028         return EraseInstFromFunction(*OldCall);
10029       return 0;
10030     }
10031
10032   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10033     // This instruction is not reachable, just remove it.  We insert a store to
10034     // undef so that we know that this code is not reachable, despite the fact
10035     // that we can't modify the CFG here.
10036     new StoreInst(ConstantInt::getTrue(*Context),
10037                UndefValue::get(Type::getInt1PtrTy(*Context)),
10038                   CS.getInstruction());
10039
10040     // If CS dues not return void then replaceAllUsesWith undef.
10041     // This allows ValueHandlers and custom metadata to adjust itself.
10042     if (!CS.getInstruction()->getType()->isVoidTy())
10043       CS.getInstruction()->
10044         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
10045
10046     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10047       // Don't break the CFG, insert a dummy cond branch.
10048       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10049                          ConstantInt::getTrue(*Context), II);
10050     }
10051     return EraseInstFromFunction(*CS.getInstruction());
10052   }
10053
10054   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10055     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10056       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10057         return transformCallThroughTrampoline(CS);
10058
10059   const PointerType *PTy = cast<PointerType>(Callee->getType());
10060   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10061   if (FTy->isVarArg()) {
10062     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10063     // See if we can optimize any arguments passed through the varargs area of
10064     // the call.
10065     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10066            E = CS.arg_end(); I != E; ++I, ++ix) {
10067       CastInst *CI = dyn_cast<CastInst>(*I);
10068       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10069         *I = CI->getOperand(0);
10070         Changed = true;
10071       }
10072     }
10073   }
10074
10075   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10076     // Inline asm calls cannot throw - mark them 'nounwind'.
10077     CS.setDoesNotThrow();
10078     Changed = true;
10079   }
10080
10081   return Changed ? CS.getInstruction() : 0;
10082 }
10083
10084 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10085 // attempt to move the cast to the arguments of the call/invoke.
10086 //
10087 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10088   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10089   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10090   if (CE->getOpcode() != Instruction::BitCast || 
10091       !isa<Function>(CE->getOperand(0)))
10092     return false;
10093   Function *Callee = cast<Function>(CE->getOperand(0));
10094   Instruction *Caller = CS.getInstruction();
10095   const AttrListPtr &CallerPAL = CS.getAttributes();
10096
10097   // Okay, this is a cast from a function to a different type.  Unless doing so
10098   // would cause a type conversion of one of our arguments, change this call to
10099   // be a direct call with arguments casted to the appropriate types.
10100   //
10101   const FunctionType *FT = Callee->getFunctionType();
10102   const Type *OldRetTy = Caller->getType();
10103   const Type *NewRetTy = FT->getReturnType();
10104
10105   if (isa<StructType>(NewRetTy))
10106     return false; // TODO: Handle multiple return values.
10107
10108   // Check to see if we are changing the return type...
10109   if (OldRetTy != NewRetTy) {
10110     if (Callee->isDeclaration() &&
10111         // Conversion is ok if changing from one pointer type to another or from
10112         // a pointer to an integer of the same size.
10113         !((isa<PointerType>(OldRetTy) || !TD ||
10114            OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
10115           (isa<PointerType>(NewRetTy) || !TD ||
10116            NewRetTy == TD->getIntPtrType(Caller->getContext()))))
10117       return false;   // Cannot transform this return value.
10118
10119     if (!Caller->use_empty() &&
10120         // void -> non-void is handled specially
10121         !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
10122       return false;   // Cannot transform this return value.
10123
10124     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10125       Attributes RAttrs = CallerPAL.getRetAttributes();
10126       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10127         return false;   // Attribute not compatible with transformed value.
10128     }
10129
10130     // If the callsite is an invoke instruction, and the return value is used by
10131     // a PHI node in a successor, we cannot change the return type of the call
10132     // because there is no place to put the cast instruction (without breaking
10133     // the critical edge).  Bail out in this case.
10134     if (!Caller->use_empty())
10135       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10136         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10137              UI != E; ++UI)
10138           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10139             if (PN->getParent() == II->getNormalDest() ||
10140                 PN->getParent() == II->getUnwindDest())
10141               return false;
10142   }
10143
10144   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10145   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10146
10147   CallSite::arg_iterator AI = CS.arg_begin();
10148   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10149     const Type *ParamTy = FT->getParamType(i);
10150     const Type *ActTy = (*AI)->getType();
10151
10152     if (!CastInst::isCastable(ActTy, ParamTy))
10153       return false;   // Cannot transform this parameter value.
10154
10155     if (CallerPAL.getParamAttributes(i + 1) 
10156         & Attribute::typeIncompatible(ParamTy))
10157       return false;   // Attribute not compatible with transformed value.
10158
10159     // Converting from one pointer type to another or between a pointer and an
10160     // integer of the same size is safe even if we do not have a body.
10161     bool isConvertible = ActTy == ParamTy ||
10162       (TD && ((isa<PointerType>(ParamTy) ||
10163       ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10164               (isa<PointerType>(ActTy) ||
10165               ActTy == TD->getIntPtrType(Caller->getContext()))));
10166     if (Callee->isDeclaration() && !isConvertible) return false;
10167   }
10168
10169   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10170       Callee->isDeclaration())
10171     return false;   // Do not delete arguments unless we have a function body.
10172
10173   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10174       !CallerPAL.isEmpty())
10175     // In this case we have more arguments than the new function type, but we
10176     // won't be dropping them.  Check that these extra arguments have attributes
10177     // that are compatible with being a vararg call argument.
10178     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10179       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10180         break;
10181       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10182       if (PAttrs & Attribute::VarArgsIncompatible)
10183         return false;
10184     }
10185
10186   // Okay, we decided that this is a safe thing to do: go ahead and start
10187   // inserting cast instructions as necessary...
10188   std::vector<Value*> Args;
10189   Args.reserve(NumActualArgs);
10190   SmallVector<AttributeWithIndex, 8> attrVec;
10191   attrVec.reserve(NumCommonArgs);
10192
10193   // Get any return attributes.
10194   Attributes RAttrs = CallerPAL.getRetAttributes();
10195
10196   // If the return value is not being used, the type may not be compatible
10197   // with the existing attributes.  Wipe out any problematic attributes.
10198   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10199
10200   // Add the new return attributes.
10201   if (RAttrs)
10202     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10203
10204   AI = CS.arg_begin();
10205   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10206     const Type *ParamTy = FT->getParamType(i);
10207     if ((*AI)->getType() == ParamTy) {
10208       Args.push_back(*AI);
10209     } else {
10210       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10211           false, ParamTy, false);
10212       Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
10213     }
10214
10215     // Add any parameter attributes.
10216     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10217       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10218   }
10219
10220   // If the function takes more arguments than the call was taking, add them
10221   // now.
10222   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10223     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10224
10225   // If we are removing arguments to the function, emit an obnoxious warning.
10226   if (FT->getNumParams() < NumActualArgs) {
10227     if (!FT->isVarArg()) {
10228       errs() << "WARNING: While resolving call to function '"
10229              << Callee->getName() << "' arguments were dropped!\n";
10230     } else {
10231       // Add all of the arguments in their promoted form to the arg list.
10232       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10233         const Type *PTy = getPromotedType((*AI)->getType());
10234         if (PTy != (*AI)->getType()) {
10235           // Must promote to pass through va_arg area!
10236           Instruction::CastOps opcode =
10237             CastInst::getCastOpcode(*AI, false, PTy, false);
10238           Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
10239         } else {
10240           Args.push_back(*AI);
10241         }
10242
10243         // Add any parameter attributes.
10244         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10245           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10246       }
10247     }
10248   }
10249
10250   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10251     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10252
10253   if (NewRetTy->isVoidTy())
10254     Caller->setName("");   // Void type should not have a name.
10255
10256   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10257                                                      attrVec.end());
10258
10259   Instruction *NC;
10260   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10261     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10262                             Args.begin(), Args.end(),
10263                             Caller->getName(), Caller);
10264     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10265     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10266   } else {
10267     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10268                           Caller->getName(), Caller);
10269     CallInst *CI = cast<CallInst>(Caller);
10270     if (CI->isTailCall())
10271       cast<CallInst>(NC)->setTailCall();
10272     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10273     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10274   }
10275
10276   // Insert a cast of the return type as necessary.
10277   Value *NV = NC;
10278   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10279     if (!NV->getType()->isVoidTy()) {
10280       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10281                                                             OldRetTy, false);
10282       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10283
10284       // If this is an invoke instruction, we should insert it after the first
10285       // non-phi, instruction in the normal successor block.
10286       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10287         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10288         InsertNewInstBefore(NC, *I);
10289       } else {
10290         // Otherwise, it's a call, just insert cast right after the call instr
10291         InsertNewInstBefore(NC, *Caller);
10292       }
10293       Worklist.AddUsersToWorkList(*Caller);
10294     } else {
10295       NV = UndefValue::get(Caller->getType());
10296     }
10297   }
10298
10299
10300   if (!Caller->use_empty())
10301     Caller->replaceAllUsesWith(NV);
10302   
10303   EraseInstFromFunction(*Caller);
10304   return true;
10305 }
10306
10307 // transformCallThroughTrampoline - Turn a call to a function created by the
10308 // init_trampoline intrinsic into a direct call to the underlying function.
10309 //
10310 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10311   Value *Callee = CS.getCalledValue();
10312   const PointerType *PTy = cast<PointerType>(Callee->getType());
10313   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10314   const AttrListPtr &Attrs = CS.getAttributes();
10315
10316   // If the call already has the 'nest' attribute somewhere then give up -
10317   // otherwise 'nest' would occur twice after splicing in the chain.
10318   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10319     return 0;
10320
10321   IntrinsicInst *Tramp =
10322     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10323
10324   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10325   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10326   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10327
10328   const AttrListPtr &NestAttrs = NestF->getAttributes();
10329   if (!NestAttrs.isEmpty()) {
10330     unsigned NestIdx = 1;
10331     const Type *NestTy = 0;
10332     Attributes NestAttr = Attribute::None;
10333
10334     // Look for a parameter marked with the 'nest' attribute.
10335     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10336          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10337       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10338         // Record the parameter type and any other attributes.
10339         NestTy = *I;
10340         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10341         break;
10342       }
10343
10344     if (NestTy) {
10345       Instruction *Caller = CS.getInstruction();
10346       std::vector<Value*> NewArgs;
10347       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10348
10349       SmallVector<AttributeWithIndex, 8> NewAttrs;
10350       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10351
10352       // Insert the nest argument into the call argument list, which may
10353       // mean appending it.  Likewise for attributes.
10354
10355       // Add any result attributes.
10356       if (Attributes Attr = Attrs.getRetAttributes())
10357         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10358
10359       {
10360         unsigned Idx = 1;
10361         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10362         do {
10363           if (Idx == NestIdx) {
10364             // Add the chain argument and attributes.
10365             Value *NestVal = Tramp->getOperand(3);
10366             if (NestVal->getType() != NestTy)
10367               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10368             NewArgs.push_back(NestVal);
10369             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10370           }
10371
10372           if (I == E)
10373             break;
10374
10375           // Add the original argument and attributes.
10376           NewArgs.push_back(*I);
10377           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10378             NewAttrs.push_back
10379               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10380
10381           ++Idx, ++I;
10382         } while (1);
10383       }
10384
10385       // Add any function attributes.
10386       if (Attributes Attr = Attrs.getFnAttributes())
10387         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10388
10389       // The trampoline may have been bitcast to a bogus type (FTy).
10390       // Handle this by synthesizing a new function type, equal to FTy
10391       // with the chain parameter inserted.
10392
10393       std::vector<const Type*> NewTypes;
10394       NewTypes.reserve(FTy->getNumParams()+1);
10395
10396       // Insert the chain's type into the list of parameter types, which may
10397       // mean appending it.
10398       {
10399         unsigned Idx = 1;
10400         FunctionType::param_iterator I = FTy->param_begin(),
10401           E = FTy->param_end();
10402
10403         do {
10404           if (Idx == NestIdx)
10405             // Add the chain's type.
10406             NewTypes.push_back(NestTy);
10407
10408           if (I == E)
10409             break;
10410
10411           // Add the original type.
10412           NewTypes.push_back(*I);
10413
10414           ++Idx, ++I;
10415         } while (1);
10416       }
10417
10418       // Replace the trampoline call with a direct call.  Let the generic
10419       // code sort out any function type mismatches.
10420       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 
10421                                                 FTy->isVarArg());
10422       Constant *NewCallee =
10423         NestF->getType() == PointerType::getUnqual(NewFTy) ?
10424         NestF : ConstantExpr::getBitCast(NestF, 
10425                                          PointerType::getUnqual(NewFTy));
10426       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10427                                                    NewAttrs.end());
10428
10429       Instruction *NewCaller;
10430       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10431         NewCaller = InvokeInst::Create(NewCallee,
10432                                        II->getNormalDest(), II->getUnwindDest(),
10433                                        NewArgs.begin(), NewArgs.end(),
10434                                        Caller->getName(), Caller);
10435         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10436         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10437       } else {
10438         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10439                                      Caller->getName(), Caller);
10440         if (cast<CallInst>(Caller)->isTailCall())
10441           cast<CallInst>(NewCaller)->setTailCall();
10442         cast<CallInst>(NewCaller)->
10443           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10444         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10445       }
10446       if (!Caller->getType()->isVoidTy())
10447         Caller->replaceAllUsesWith(NewCaller);
10448       Caller->eraseFromParent();
10449       Worklist.Remove(Caller);
10450       return 0;
10451     }
10452   }
10453
10454   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10455   // parameter, there is no need to adjust the argument list.  Let the generic
10456   // code sort out any function type mismatches.
10457   Constant *NewCallee =
10458     NestF->getType() == PTy ? NestF : 
10459                               ConstantExpr::getBitCast(NestF, PTy);
10460   CS.setCalledFunction(NewCallee);
10461   return CS.getInstruction();
10462 }
10463
10464 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10465 /// and if a/b/c and the add's all have a single use, turn this into a phi
10466 /// and a single binop.
10467 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10468   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10469   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10470   unsigned Opc = FirstInst->getOpcode();
10471   Value *LHSVal = FirstInst->getOperand(0);
10472   Value *RHSVal = FirstInst->getOperand(1);
10473     
10474   const Type *LHSType = LHSVal->getType();
10475   const Type *RHSType = RHSVal->getType();
10476   
10477   // Scan to see if all operands are the same opcode, and all have one use.
10478   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10479     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10480     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10481         // Verify type of the LHS matches so we don't fold cmp's of different
10482         // types or GEP's with different index types.
10483         I->getOperand(0)->getType() != LHSType ||
10484         I->getOperand(1)->getType() != RHSType)
10485       return 0;
10486
10487     // If they are CmpInst instructions, check their predicates
10488     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10489       if (cast<CmpInst>(I)->getPredicate() !=
10490           cast<CmpInst>(FirstInst)->getPredicate())
10491         return 0;
10492     
10493     // Keep track of which operand needs a phi node.
10494     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10495     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10496   }
10497
10498   // If both LHS and RHS would need a PHI, don't do this transformation,
10499   // because it would increase the number of PHIs entering the block,
10500   // which leads to higher register pressure. This is especially
10501   // bad when the PHIs are in the header of a loop.
10502   if (!LHSVal && !RHSVal)
10503     return 0;
10504   
10505   // Otherwise, this is safe to transform!
10506   
10507   Value *InLHS = FirstInst->getOperand(0);
10508   Value *InRHS = FirstInst->getOperand(1);
10509   PHINode *NewLHS = 0, *NewRHS = 0;
10510   if (LHSVal == 0) {
10511     NewLHS = PHINode::Create(LHSType,
10512                              FirstInst->getOperand(0)->getName() + ".pn");
10513     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10514     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10515     InsertNewInstBefore(NewLHS, PN);
10516     LHSVal = NewLHS;
10517   }
10518   
10519   if (RHSVal == 0) {
10520     NewRHS = PHINode::Create(RHSType,
10521                              FirstInst->getOperand(1)->getName() + ".pn");
10522     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10523     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10524     InsertNewInstBefore(NewRHS, PN);
10525     RHSVal = NewRHS;
10526   }
10527   
10528   // Add all operands to the new PHIs.
10529   if (NewLHS || NewRHS) {
10530     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10531       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10532       if (NewLHS) {
10533         Value *NewInLHS = InInst->getOperand(0);
10534         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10535       }
10536       if (NewRHS) {
10537         Value *NewInRHS = InInst->getOperand(1);
10538         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10539       }
10540     }
10541   }
10542     
10543   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10544     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10545   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10546   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10547                          LHSVal, RHSVal);
10548 }
10549
10550 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10551   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10552   
10553   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10554                                         FirstInst->op_end());
10555   // This is true if all GEP bases are allocas and if all indices into them are
10556   // constants.
10557   bool AllBasePointersAreAllocas = true;
10558
10559   // We don't want to replace this phi if the replacement would require
10560   // more than one phi, which leads to higher register pressure. This is
10561   // especially bad when the PHIs are in the header of a loop.
10562   bool NeededPhi = false;
10563   
10564   // Scan to see if all operands are the same opcode, and all have one use.
10565   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10566     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10567     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10568       GEP->getNumOperands() != FirstInst->getNumOperands())
10569       return 0;
10570
10571     // Keep track of whether or not all GEPs are of alloca pointers.
10572     if (AllBasePointersAreAllocas &&
10573         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10574          !GEP->hasAllConstantIndices()))
10575       AllBasePointersAreAllocas = false;
10576     
10577     // Compare the operand lists.
10578     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10579       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10580         continue;
10581       
10582       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10583       // if one of the PHIs has a constant for the index.  The index may be
10584       // substantially cheaper to compute for the constants, so making it a
10585       // variable index could pessimize the path.  This also handles the case
10586       // for struct indices, which must always be constant.
10587       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10588           isa<ConstantInt>(GEP->getOperand(op)))
10589         return 0;
10590       
10591       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10592         return 0;
10593
10594       // If we already needed a PHI for an earlier operand, and another operand
10595       // also requires a PHI, we'd be introducing more PHIs than we're
10596       // eliminating, which increases register pressure on entry to the PHI's
10597       // block.
10598       if (NeededPhi)
10599         return 0;
10600
10601       FixedOperands[op] = 0;  // Needs a PHI.
10602       NeededPhi = true;
10603     }
10604   }
10605   
10606   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10607   // bother doing this transformation.  At best, this will just save a bit of
10608   // offset calculation, but all the predecessors will have to materialize the
10609   // stack address into a register anyway.  We'd actually rather *clone* the
10610   // load up into the predecessors so that we have a load of a gep of an alloca,
10611   // which can usually all be folded into the load.
10612   if (AllBasePointersAreAllocas)
10613     return 0;
10614   
10615   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10616   // that is variable.
10617   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10618   
10619   bool HasAnyPHIs = false;
10620   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10621     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10622     Value *FirstOp = FirstInst->getOperand(i);
10623     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10624                                      FirstOp->getName()+".pn");
10625     InsertNewInstBefore(NewPN, PN);
10626     
10627     NewPN->reserveOperandSpace(e);
10628     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10629     OperandPhis[i] = NewPN;
10630     FixedOperands[i] = NewPN;
10631     HasAnyPHIs = true;
10632   }
10633
10634   
10635   // Add all operands to the new PHIs.
10636   if (HasAnyPHIs) {
10637     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10638       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10639       BasicBlock *InBB = PN.getIncomingBlock(i);
10640       
10641       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10642         if (PHINode *OpPhi = OperandPhis[op])
10643           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10644     }
10645   }
10646   
10647   Value *Base = FixedOperands[0];
10648   return cast<GEPOperator>(FirstInst)->isInBounds() ?
10649     GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10650                                       FixedOperands.end()) :
10651     GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10652                               FixedOperands.end());
10653 }
10654
10655
10656 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10657 /// sink the load out of the block that defines it.  This means that it must be
10658 /// obvious the value of the load is not changed from the point of the load to
10659 /// the end of the block it is in.
10660 ///
10661 /// Finally, it is safe, but not profitable, to sink a load targetting a
10662 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10663 /// to a register.
10664 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10665   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10666   
10667   for (++BBI; BBI != E; ++BBI)
10668     if (BBI->mayWriteToMemory())
10669       return false;
10670   
10671   // Check for non-address taken alloca.  If not address-taken already, it isn't
10672   // profitable to do this xform.
10673   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10674     bool isAddressTaken = false;
10675     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10676          UI != E; ++UI) {
10677       if (isa<LoadInst>(UI)) continue;
10678       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10679         // If storing TO the alloca, then the address isn't taken.
10680         if (SI->getOperand(1) == AI) continue;
10681       }
10682       isAddressTaken = true;
10683       break;
10684     }
10685     
10686     if (!isAddressTaken && AI->isStaticAlloca())
10687       return false;
10688   }
10689   
10690   // If this load is a load from a GEP with a constant offset from an alloca,
10691   // then we don't want to sink it.  In its present form, it will be
10692   // load [constant stack offset].  Sinking it will cause us to have to
10693   // materialize the stack addresses in each predecessor in a register only to
10694   // do a shared load from register in the successor.
10695   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10696     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10697       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10698         return false;
10699   
10700   return true;
10701 }
10702
10703
10704 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10705 // operator and they all are only used by the PHI, PHI together their
10706 // inputs, and do the operation once, to the result of the PHI.
10707 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10708   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10709
10710   // Scan the instruction, looking for input operations that can be folded away.
10711   // If all input operands to the phi are the same instruction (e.g. a cast from
10712   // the same type or "+42") we can pull the operation through the PHI, reducing
10713   // code size and simplifying code.
10714   Constant *ConstantOp = 0;
10715   const Type *CastSrcTy = 0;
10716   bool isVolatile = false;
10717   if (isa<CastInst>(FirstInst)) {
10718     CastSrcTy = FirstInst->getOperand(0)->getType();
10719   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10720     // Can fold binop, compare or shift here if the RHS is a constant, 
10721     // otherwise call FoldPHIArgBinOpIntoPHI.
10722     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10723     if (ConstantOp == 0)
10724       return FoldPHIArgBinOpIntoPHI(PN);
10725   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10726     isVolatile = LI->isVolatile();
10727     // We can't sink the load if the loaded value could be modified between the
10728     // load and the PHI.
10729     if (LI->getParent() != PN.getIncomingBlock(0) ||
10730         !isSafeAndProfitableToSinkLoad(LI))
10731       return 0;
10732     
10733     // If the PHI is of volatile loads and the load block has multiple
10734     // successors, sinking it would remove a load of the volatile value from
10735     // the path through the other successor.
10736     if (isVolatile &&
10737         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10738       return 0;
10739     
10740   } else if (isa<GetElementPtrInst>(FirstInst)) {
10741     return FoldPHIArgGEPIntoPHI(PN);
10742   } else {
10743     return 0;  // Cannot fold this operation.
10744   }
10745
10746   // Check to see if all arguments are the same operation.
10747   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10748     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10749     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10750     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10751       return 0;
10752     if (CastSrcTy) {
10753       if (I->getOperand(0)->getType() != CastSrcTy)
10754         return 0;  // Cast operation must match.
10755     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10756       // We can't sink the load if the loaded value could be modified between 
10757       // the load and the PHI.
10758       if (LI->isVolatile() != isVolatile ||
10759           LI->getParent() != PN.getIncomingBlock(i) ||
10760           !isSafeAndProfitableToSinkLoad(LI))
10761         return 0;
10762       
10763       // If the PHI is of volatile loads and the load block has multiple
10764       // successors, sinking it would remove a load of the volatile value from
10765       // the path through the other successor.
10766       if (isVolatile &&
10767           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10768         return 0;
10769       
10770     } else if (I->getOperand(1) != ConstantOp) {
10771       return 0;
10772     }
10773   }
10774
10775   // Okay, they are all the same operation.  Create a new PHI node of the
10776   // correct type, and PHI together all of the LHS's of the instructions.
10777   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10778                                    PN.getName()+".in");
10779   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10780
10781   Value *InVal = FirstInst->getOperand(0);
10782   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10783
10784   // Add all operands to the new PHI.
10785   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10786     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10787     if (NewInVal != InVal)
10788       InVal = 0;
10789     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10790   }
10791
10792   Value *PhiVal;
10793   if (InVal) {
10794     // The new PHI unions all of the same values together.  This is really
10795     // common, so we handle it intelligently here for compile-time speed.
10796     PhiVal = InVal;
10797     delete NewPN;
10798   } else {
10799     InsertNewInstBefore(NewPN, PN);
10800     PhiVal = NewPN;
10801   }
10802
10803   // Insert and return the new operation.
10804   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10805     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10806   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10807     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10808   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10809     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10810                            PhiVal, ConstantOp);
10811   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10812   
10813   // If this was a volatile load that we are merging, make sure to loop through
10814   // and mark all the input loads as non-volatile.  If we don't do this, we will
10815   // insert a new volatile load and the old ones will not be deletable.
10816   if (isVolatile)
10817     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10818       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10819   
10820   return new LoadInst(PhiVal, "", isVolatile);
10821 }
10822
10823 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10824 /// that is dead.
10825 static bool DeadPHICycle(PHINode *PN,
10826                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10827   if (PN->use_empty()) return true;
10828   if (!PN->hasOneUse()) return false;
10829
10830   // Remember this node, and if we find the cycle, return.
10831   if (!PotentiallyDeadPHIs.insert(PN))
10832     return true;
10833   
10834   // Don't scan crazily complex things.
10835   if (PotentiallyDeadPHIs.size() == 16)
10836     return false;
10837
10838   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10839     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10840
10841   return false;
10842 }
10843
10844 /// PHIsEqualValue - Return true if this phi node is always equal to
10845 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10846 ///   z = some value; x = phi (y, z); y = phi (x, z)
10847 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10848                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10849   // See if we already saw this PHI node.
10850   if (!ValueEqualPHIs.insert(PN))
10851     return true;
10852   
10853   // Don't scan crazily complex things.
10854   if (ValueEqualPHIs.size() == 16)
10855     return false;
10856  
10857   // Scan the operands to see if they are either phi nodes or are equal to
10858   // the value.
10859   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10860     Value *Op = PN->getIncomingValue(i);
10861     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10862       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10863         return false;
10864     } else if (Op != NonPhiInVal)
10865       return false;
10866   }
10867   
10868   return true;
10869 }
10870
10871
10872 // PHINode simplification
10873 //
10874 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10875   // If LCSSA is around, don't mess with Phi nodes
10876   if (MustPreserveLCSSA) return 0;
10877   
10878   if (Value *V = PN.hasConstantValue())
10879     return ReplaceInstUsesWith(PN, V);
10880
10881   // If all PHI operands are the same operation, pull them through the PHI,
10882   // reducing code size.
10883   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10884       isa<Instruction>(PN.getIncomingValue(1)) &&
10885       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10886       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10887       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10888       // than themselves more than once.
10889       PN.getIncomingValue(0)->hasOneUse())
10890     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10891       return Result;
10892
10893   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10894   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10895   // PHI)... break the cycle.
10896   if (PN.hasOneUse()) {
10897     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10898     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10899       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10900       PotentiallyDeadPHIs.insert(&PN);
10901       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10902         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10903     }
10904    
10905     // If this phi has a single use, and if that use just computes a value for
10906     // the next iteration of a loop, delete the phi.  This occurs with unused
10907     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10908     // common case here is good because the only other things that catch this
10909     // are induction variable analysis (sometimes) and ADCE, which is only run
10910     // late.
10911     if (PHIUser->hasOneUse() &&
10912         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10913         PHIUser->use_back() == &PN) {
10914       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10915     }
10916   }
10917
10918   // We sometimes end up with phi cycles that non-obviously end up being the
10919   // same value, for example:
10920   //   z = some value; x = phi (y, z); y = phi (x, z)
10921   // where the phi nodes don't necessarily need to be in the same block.  Do a
10922   // quick check to see if the PHI node only contains a single non-phi value, if
10923   // so, scan to see if the phi cycle is actually equal to that value.
10924   {
10925     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10926     // Scan for the first non-phi operand.
10927     while (InValNo != NumOperandVals && 
10928            isa<PHINode>(PN.getIncomingValue(InValNo)))
10929       ++InValNo;
10930
10931     if (InValNo != NumOperandVals) {
10932       Value *NonPhiInVal = PN.getOperand(InValNo);
10933       
10934       // Scan the rest of the operands to see if there are any conflicts, if so
10935       // there is no need to recursively scan other phis.
10936       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10937         Value *OpVal = PN.getIncomingValue(InValNo);
10938         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10939           break;
10940       }
10941       
10942       // If we scanned over all operands, then we have one unique value plus
10943       // phi values.  Scan PHI nodes to see if they all merge in each other or
10944       // the value.
10945       if (InValNo == NumOperandVals) {
10946         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10947         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10948           return ReplaceInstUsesWith(PN, NonPhiInVal);
10949       }
10950     }
10951   }
10952   return 0;
10953 }
10954
10955 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10956   Value *PtrOp = GEP.getOperand(0);
10957   // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
10958   if (GEP.getNumOperands() == 1)
10959     return ReplaceInstUsesWith(GEP, PtrOp);
10960
10961   if (isa<UndefValue>(GEP.getOperand(0)))
10962     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10963
10964   bool HasZeroPointerIndex = false;
10965   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10966     HasZeroPointerIndex = C->isNullValue();
10967
10968   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10969     return ReplaceInstUsesWith(GEP, PtrOp);
10970
10971   // Eliminate unneeded casts for indices.
10972   if (TD) {
10973     bool MadeChange = false;
10974     unsigned PtrSize = TD->getPointerSizeInBits();
10975     
10976     gep_type_iterator GTI = gep_type_begin(GEP);
10977     for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10978          I != E; ++I, ++GTI) {
10979       if (!isa<SequentialType>(*GTI)) continue;
10980       
10981       // If we are using a wider index than needed for this platform, shrink it
10982       // to what we need.  If narrower, sign-extend it to what we need.  This
10983       // explicit cast can make subsequent optimizations more obvious.
10984       unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
10985       if (OpBits == PtrSize)
10986         continue;
10987       
10988       *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
10989       MadeChange = true;
10990     }
10991     if (MadeChange) return &GEP;
10992   }
10993
10994   // Combine Indices - If the source pointer to this getelementptr instruction
10995   // is a getelementptr instruction, combine the indices of the two
10996   // getelementptr instructions into a single instruction.
10997   //
10998   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
10999     // Note that if our source is a gep chain itself that we wait for that
11000     // chain to be resolved before we perform this transformation.  This
11001     // avoids us creating a TON of code in some cases.
11002     //
11003     if (GetElementPtrInst *SrcGEP =
11004           dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11005       if (SrcGEP->getNumOperands() == 2)
11006         return 0;   // Wait until our source is folded to completion.
11007
11008     SmallVector<Value*, 8> Indices;
11009
11010     // Find out whether the last index in the source GEP is a sequential idx.
11011     bool EndsWithSequential = false;
11012     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11013          I != E; ++I)
11014       EndsWithSequential = !isa<StructType>(*I);
11015
11016     // Can we combine the two pointer arithmetics offsets?
11017     if (EndsWithSequential) {
11018       // Replace: gep (gep %P, long B), long A, ...
11019       // With:    T = long A+B; gep %P, T, ...
11020       //
11021       Value *Sum;
11022       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11023       Value *GO1 = GEP.getOperand(1);
11024       if (SO1 == Constant::getNullValue(SO1->getType())) {
11025         Sum = GO1;
11026       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
11027         Sum = SO1;
11028       } else {
11029         // If they aren't the same type, then the input hasn't been processed
11030         // by the loop above yet (which canonicalizes sequential index types to
11031         // intptr_t).  Just avoid transforming this until the input has been
11032         // normalized.
11033         if (SO1->getType() != GO1->getType())
11034           return 0;
11035         Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11036       }
11037
11038       // Update the GEP in place if possible.
11039       if (Src->getNumOperands() == 2) {
11040         GEP.setOperand(0, Src->getOperand(0));
11041         GEP.setOperand(1, Sum);
11042         return &GEP;
11043       }
11044       Indices.append(Src->op_begin()+1, Src->op_end()-1);
11045       Indices.push_back(Sum);
11046       Indices.append(GEP.op_begin()+2, GEP.op_end());
11047     } else if (isa<Constant>(*GEP.idx_begin()) &&
11048                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11049                Src->getNumOperands() != 1) {
11050       // Otherwise we can do the fold if the first index of the GEP is a zero
11051       Indices.append(Src->op_begin()+1, Src->op_end());
11052       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
11053     }
11054
11055     if (!Indices.empty())
11056       return (cast<GEPOperator>(&GEP)->isInBounds() &&
11057               Src->isInBounds()) ?
11058         GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11059                                           Indices.end(), GEP.getName()) :
11060         GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
11061                                   Indices.end(), GEP.getName());
11062   }
11063   
11064   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11065   if (Value *X = getBitCastOperand(PtrOp)) {
11066     assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
11067
11068     // If the input bitcast is actually "bitcast(bitcast(x))", then we don't 
11069     // want to change the gep until the bitcasts are eliminated.
11070     if (getBitCastOperand(X)) {
11071       Worklist.AddValue(PtrOp);
11072       return 0;
11073     }
11074     
11075     // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11076     // into     : GEP [10 x i8]* X, i32 0, ...
11077     //
11078     // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11079     //           into     : GEP i8* X, ...
11080     // 
11081     // This occurs when the program declares an array extern like "int X[];"
11082     if (HasZeroPointerIndex) {
11083       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11084       const PointerType *XTy = cast<PointerType>(X->getType());
11085       if (const ArrayType *CATy =
11086           dyn_cast<ArrayType>(CPTy->getElementType())) {
11087         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11088         if (CATy->getElementType() == XTy->getElementType()) {
11089           // -> GEP i8* X, ...
11090           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11091           return cast<GEPOperator>(&GEP)->isInBounds() ?
11092             GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11093                                               GEP.getName()) :
11094             GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11095                                       GEP.getName());
11096         }
11097         
11098         if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
11099           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11100           if (CATy->getElementType() == XATy->getElementType()) {
11101             // -> GEP [10 x i8]* X, i32 0, ...
11102             // At this point, we know that the cast source type is a pointer
11103             // to an array of the same type as the destination pointer
11104             // array.  Because the array type is never stepped over (there
11105             // is a leading zero) we can fold the cast into this GEP.
11106             GEP.setOperand(0, X);
11107             return &GEP;
11108           }
11109         }
11110       }
11111     } else if (GEP.getNumOperands() == 2) {
11112       // Transform things like:
11113       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11114       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11115       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11116       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11117       if (TD && isa<ArrayType>(SrcElTy) &&
11118           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11119           TD->getTypeAllocSize(ResElTy)) {
11120         Value *Idx[2];
11121         Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11122         Idx[1] = GEP.getOperand(1);
11123         Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11124           Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11125           Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11126         // V and GEP are both pointer types --> BitCast
11127         return new BitCastInst(NewGEP, GEP.getType());
11128       }
11129       
11130       // Transform things like:
11131       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11132       //   (where tmp = 8*tmp2) into:
11133       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11134       
11135       if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
11136         uint64_t ArrayEltSize =
11137             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11138         
11139         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11140         // allow either a mul, shift, or constant here.
11141         Value *NewIdx = 0;
11142         ConstantInt *Scale = 0;
11143         if (ArrayEltSize == 1) {
11144           NewIdx = GEP.getOperand(1);
11145           Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
11146         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11147           NewIdx = ConstantInt::get(CI->getType(), 1);
11148           Scale = CI;
11149         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11150           if (Inst->getOpcode() == Instruction::Shl &&
11151               isa<ConstantInt>(Inst->getOperand(1))) {
11152             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11153             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11154             Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11155                                      1ULL << ShAmtVal);
11156             NewIdx = Inst->getOperand(0);
11157           } else if (Inst->getOpcode() == Instruction::Mul &&
11158                      isa<ConstantInt>(Inst->getOperand(1))) {
11159             Scale = cast<ConstantInt>(Inst->getOperand(1));
11160             NewIdx = Inst->getOperand(0);
11161           }
11162         }
11163         
11164         // If the index will be to exactly the right offset with the scale taken
11165         // out, perform the transformation. Note, we don't know whether Scale is
11166         // signed or not. We'll use unsigned version of division/modulo
11167         // operation after making sure Scale doesn't have the sign bit set.
11168         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11169             Scale->getZExtValue() % ArrayEltSize == 0) {
11170           Scale = ConstantInt::get(Scale->getType(),
11171                                    Scale->getZExtValue() / ArrayEltSize);
11172           if (Scale->getZExtValue() != 1) {
11173             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11174                                                        false /*ZExt*/);
11175             NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
11176           }
11177
11178           // Insert the new GEP instruction.
11179           Value *Idx[2];
11180           Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11181           Idx[1] = NewIdx;
11182           Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11183             Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11184             Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11185           // The NewGEP must be pointer typed, so must the old one -> BitCast
11186           return new BitCastInst(NewGEP, GEP.getType());
11187         }
11188       }
11189     }
11190   }
11191   
11192   /// See if we can simplify:
11193   ///   X = bitcast A* to B*
11194   ///   Y = gep X, <...constant indices...>
11195   /// into a gep of the original struct.  This is important for SROA and alias
11196   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11197   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11198     if (TD &&
11199         !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11200       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11201       // a constant back from EmitGEPOffset.
11202       ConstantInt *OffsetV =
11203                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11204       int64_t Offset = OffsetV->getSExtValue();
11205       
11206       // If this GEP instruction doesn't move the pointer, just replace the GEP
11207       // with a bitcast of the real input to the dest type.
11208       if (Offset == 0) {
11209         // If the bitcast is of an allocation, and the allocation will be
11210         // converted to match the type of the cast, don't touch this.
11211         if (isa<AllocationInst>(BCI->getOperand(0)) ||
11212             isMalloc(BCI->getOperand(0))) {
11213           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11214           if (Instruction *I = visitBitCast(*BCI)) {
11215             if (I != BCI) {
11216               I->takeName(BCI);
11217               BCI->getParent()->getInstList().insert(BCI, I);
11218               ReplaceInstUsesWith(*BCI, I);
11219             }
11220             return &GEP;
11221           }
11222         }
11223         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11224       }
11225       
11226       // Otherwise, if the offset is non-zero, we need to find out if there is a
11227       // field at Offset in 'A's type.  If so, we can pull the cast through the
11228       // GEP.
11229       SmallVector<Value*, 8> NewIndices;
11230       const Type *InTy =
11231         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11232       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11233         Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11234           Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11235                                      NewIndices.end()) :
11236           Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11237                              NewIndices.end());
11238         
11239         if (NGEP->getType() == GEP.getType())
11240           return ReplaceInstUsesWith(GEP, NGEP);
11241         NGEP->takeName(&GEP);
11242         return new BitCastInst(NGEP, GEP.getType());
11243       }
11244     }
11245   }    
11246     
11247   return 0;
11248 }
11249
11250 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11251   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11252   if (AI.isArrayAllocation()) {  // Check C != 1
11253     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11254       const Type *NewTy = 
11255         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11256       assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11257       AllocationInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
11258       New->setAlignment(AI.getAlignment());
11259
11260       // Scan to the end of the allocation instructions, to skip over a block of
11261       // allocas if possible...also skip interleaved debug info
11262       //
11263       BasicBlock::iterator It = New;
11264       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11265
11266       // Now that I is pointing to the first non-allocation-inst in the block,
11267       // insert our getelementptr instruction...
11268       //
11269       Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
11270       Value *Idx[2];
11271       Idx[0] = NullIdx;
11272       Idx[1] = NullIdx;
11273       Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11274                                                    New->getName()+".sub", It);
11275
11276       // Now make everything use the getelementptr instead of the original
11277       // allocation.
11278       return ReplaceInstUsesWith(AI, V);
11279     } else if (isa<UndefValue>(AI.getArraySize())) {
11280       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11281     }
11282   }
11283
11284   if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11285     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11286     // Note that we only do this for alloca's, because malloc should allocate
11287     // and return a unique pointer, even for a zero byte allocation.
11288     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11289       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11290
11291     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11292     if (AI.getAlignment() == 0)
11293       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11294   }
11295
11296   return 0;
11297 }
11298
11299 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11300   Value *Op = FI.getOperand(0);
11301
11302   // free undef -> unreachable.
11303   if (isa<UndefValue>(Op)) {
11304     // Insert a new store to null because we cannot modify the CFG here.
11305     new StoreInst(ConstantInt::getTrue(*Context),
11306            UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
11307     return EraseInstFromFunction(FI);
11308   }
11309   
11310   // If we have 'free null' delete the instruction.  This can happen in stl code
11311   // when lots of inlining happens.
11312   if (isa<ConstantPointerNull>(Op))
11313     return EraseInstFromFunction(FI);
11314   
11315   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11316   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11317     FI.setOperand(0, CI->getOperand(0));
11318     return &FI;
11319   }
11320   
11321   // Change free (gep X, 0,0,0,0) into free(X)
11322   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11323     if (GEPI->hasAllZeroIndices()) {
11324       Worklist.Add(GEPI);
11325       FI.setOperand(0, GEPI->getOperand(0));
11326       return &FI;
11327     }
11328   }
11329   
11330   if (isMalloc(Op)) {
11331     if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11332       if (Op->hasOneUse() && CI->hasOneUse()) {
11333         EraseInstFromFunction(FI);
11334         EraseInstFromFunction(*CI);
11335         return EraseInstFromFunction(*cast<Instruction>(Op));
11336       }
11337     } else {
11338       // Op is a call to malloc
11339       if (Op->hasOneUse()) {
11340         EraseInstFromFunction(FI);
11341         return EraseInstFromFunction(*cast<Instruction>(Op));
11342       }
11343     }
11344   }
11345
11346   return 0;
11347 }
11348
11349
11350 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11351 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11352                                         const TargetData *TD) {
11353   User *CI = cast<User>(LI.getOperand(0));
11354   Value *CastOp = CI->getOperand(0);
11355   LLVMContext *Context = IC.getContext();
11356
11357   if (TD) {
11358     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11359       // Instead of loading constant c string, use corresponding integer value
11360       // directly if string length is small enough.
11361       std::string Str;
11362       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11363         unsigned len = Str.length();
11364         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11365         unsigned numBits = Ty->getPrimitiveSizeInBits();
11366         // Replace LI with immediate integer store.
11367         if ((numBits >> 3) == len + 1) {
11368           APInt StrVal(numBits, 0);
11369           APInt SingleChar(numBits, 0);
11370           if (TD->isLittleEndian()) {
11371             for (signed i = len-1; i >= 0; i--) {
11372               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11373               StrVal = (StrVal << 8) | SingleChar;
11374             }
11375           } else {
11376             for (unsigned i = 0; i < len; i++) {
11377               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11378               StrVal = (StrVal << 8) | SingleChar;
11379             }
11380             // Append NULL at the end.
11381             SingleChar = 0;
11382             StrVal = (StrVal << 8) | SingleChar;
11383           }
11384           Value *NL = ConstantInt::get(*Context, StrVal);
11385           return IC.ReplaceInstUsesWith(LI, NL);
11386         }
11387       }
11388     }
11389   }
11390
11391   const PointerType *DestTy = cast<PointerType>(CI->getType());
11392   const Type *DestPTy = DestTy->getElementType();
11393   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11394
11395     // If the address spaces don't match, don't eliminate the cast.
11396     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11397       return 0;
11398
11399     const Type *SrcPTy = SrcTy->getElementType();
11400
11401     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11402          isa<VectorType>(DestPTy)) {
11403       // If the source is an array, the code below will not succeed.  Check to
11404       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11405       // constants.
11406       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11407         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11408           if (ASrcTy->getNumElements() != 0) {
11409             Value *Idxs[2];
11410             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
11411             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11412             SrcTy = cast<PointerType>(CastOp->getType());
11413             SrcPTy = SrcTy->getElementType();
11414           }
11415
11416       if (IC.getTargetData() &&
11417           (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11418             isa<VectorType>(SrcPTy)) &&
11419           // Do not allow turning this into a load of an integer, which is then
11420           // casted to a pointer, this pessimizes pointer analysis a lot.
11421           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11422           IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11423                IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11424
11425         // Okay, we are casting from one integer or pointer type to another of
11426         // the same size.  Instead of casting the pointer before the load, cast
11427         // the result of the loaded value.
11428         Value *NewLoad = 
11429           IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
11430         // Now cast the result of the load.
11431         return new BitCastInst(NewLoad, LI.getType());
11432       }
11433     }
11434   }
11435   return 0;
11436 }
11437
11438 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11439   Value *Op = LI.getOperand(0);
11440
11441   // Attempt to improve the alignment.
11442   if (TD) {
11443     unsigned KnownAlign =
11444       GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11445     if (KnownAlign >
11446         (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11447                                   LI.getAlignment()))
11448       LI.setAlignment(KnownAlign);
11449   }
11450
11451   // load (cast X) --> cast (load X) iff safe.
11452   if (isa<CastInst>(Op))
11453     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11454       return Res;
11455
11456   // None of the following transforms are legal for volatile loads.
11457   if (LI.isVolatile()) return 0;
11458   
11459   // Do really simple store-to-load forwarding and load CSE, to catch cases
11460   // where there are several consequtive memory accesses to the same location,
11461   // separated by a few arithmetic operations.
11462   BasicBlock::iterator BBI = &LI;
11463   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11464     return ReplaceInstUsesWith(LI, AvailableVal);
11465
11466   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11467     const Value *GEPI0 = GEPI->getOperand(0);
11468     // TODO: Consider a target hook for valid address spaces for this xform.
11469     if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
11470       // Insert a new store to null instruction before the load to indicate
11471       // that this code is not reachable.  We do this instead of inserting
11472       // an unreachable instruction directly because we cannot modify the
11473       // CFG.
11474       new StoreInst(UndefValue::get(LI.getType()),
11475                     Constant::getNullValue(Op->getType()), &LI);
11476       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11477     }
11478   } 
11479
11480   if (Constant *C = dyn_cast<Constant>(Op)) {
11481     // load null/undef -> undef
11482     // TODO: Consider a target hook for valid address spaces for this xform.
11483     if (isa<UndefValue>(C) ||
11484         (C->isNullValue() && LI.getPointerAddressSpace() == 0)) {
11485       // Insert a new store to null instruction before the load to indicate that
11486       // this code is not reachable.  We do this instead of inserting an
11487       // unreachable instruction directly because we cannot modify the CFG.
11488       new StoreInst(UndefValue::get(LI.getType()),
11489                     Constant::getNullValue(Op->getType()), &LI);
11490       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11491     }
11492
11493     // Instcombine load (constant global) into the value loaded.
11494     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11495       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11496         return ReplaceInstUsesWith(LI, GV->getInitializer());
11497
11498     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11499     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11500       if (CE->getOpcode() == Instruction::GetElementPtr) {
11501         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11502           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11503             if (Constant *V = 
11504                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
11505               return ReplaceInstUsesWith(LI, V);
11506         if (CE->getOperand(0)->isNullValue()) {
11507           // Insert a new store to null instruction before the load to indicate
11508           // that this code is not reachable.  We do this instead of inserting
11509           // an unreachable instruction directly because we cannot modify the
11510           // CFG.
11511           new StoreInst(UndefValue::get(LI.getType()),
11512                         Constant::getNullValue(Op->getType()), &LI);
11513           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11514         }
11515
11516       } else if (CE->isCast()) {
11517         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11518           return Res;
11519       }
11520     }
11521   }
11522     
11523   // If this load comes from anywhere in a constant global, and if the global
11524   // is all undef or zero, we know what it loads.
11525   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11526     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11527       if (GV->getInitializer()->isNullValue())
11528         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11529       else if (isa<UndefValue>(GV->getInitializer()))
11530         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11531     }
11532   }
11533
11534   if (Op->hasOneUse()) {
11535     // Change select and PHI nodes to select values instead of addresses: this
11536     // helps alias analysis out a lot, allows many others simplifications, and
11537     // exposes redundancy in the code.
11538     //
11539     // Note that we cannot do the transformation unless we know that the
11540     // introduced loads cannot trap!  Something like this is valid as long as
11541     // the condition is always false: load (select bool %C, int* null, int* %G),
11542     // but it would not be valid if we transformed it to load from null
11543     // unconditionally.
11544     //
11545     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11546       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11547       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11548           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11549         Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11550                                         SI->getOperand(1)->getName()+".val");
11551         Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11552                                         SI->getOperand(2)->getName()+".val");
11553         return SelectInst::Create(SI->getCondition(), V1, V2);
11554       }
11555
11556       // load (select (cond, null, P)) -> load P
11557       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11558         if (C->isNullValue()) {
11559           LI.setOperand(0, SI->getOperand(2));
11560           return &LI;
11561         }
11562
11563       // load (select (cond, P, null)) -> load P
11564       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11565         if (C->isNullValue()) {
11566           LI.setOperand(0, SI->getOperand(1));
11567           return &LI;
11568         }
11569     }
11570   }
11571   return 0;
11572 }
11573
11574 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11575 /// when possible.  This makes it generally easy to do alias analysis and/or
11576 /// SROA/mem2reg of the memory object.
11577 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11578   User *CI = cast<User>(SI.getOperand(1));
11579   Value *CastOp = CI->getOperand(0);
11580
11581   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11582   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11583   if (SrcTy == 0) return 0;
11584   
11585   const Type *SrcPTy = SrcTy->getElementType();
11586
11587   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11588     return 0;
11589   
11590   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11591   /// to its first element.  This allows us to handle things like:
11592   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11593   /// on 32-bit hosts.
11594   SmallVector<Value*, 4> NewGEPIndices;
11595   
11596   // If the source is an array, the code below will not succeed.  Check to
11597   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11598   // constants.
11599   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11600     // Index through pointer.
11601     Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
11602     NewGEPIndices.push_back(Zero);
11603     
11604     while (1) {
11605       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11606         if (!STy->getNumElements()) /* Struct can be empty {} */
11607           break;
11608         NewGEPIndices.push_back(Zero);
11609         SrcPTy = STy->getElementType(0);
11610       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11611         NewGEPIndices.push_back(Zero);
11612         SrcPTy = ATy->getElementType();
11613       } else {
11614         break;
11615       }
11616     }
11617     
11618     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11619   }
11620
11621   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11622     return 0;
11623   
11624   // If the pointers point into different address spaces or if they point to
11625   // values with different sizes, we can't do the transformation.
11626   if (!IC.getTargetData() ||
11627       SrcTy->getAddressSpace() != 
11628         cast<PointerType>(CI->getType())->getAddressSpace() ||
11629       IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11630       IC.getTargetData()->getTypeSizeInBits(DestPTy))
11631     return 0;
11632
11633   // Okay, we are casting from one integer or pointer type to another of
11634   // the same size.  Instead of casting the pointer before 
11635   // the store, cast the value to be stored.
11636   Value *NewCast;
11637   Value *SIOp0 = SI.getOperand(0);
11638   Instruction::CastOps opcode = Instruction::BitCast;
11639   const Type* CastSrcTy = SIOp0->getType();
11640   const Type* CastDstTy = SrcPTy;
11641   if (isa<PointerType>(CastDstTy)) {
11642     if (CastSrcTy->isInteger())
11643       opcode = Instruction::IntToPtr;
11644   } else if (isa<IntegerType>(CastDstTy)) {
11645     if (isa<PointerType>(SIOp0->getType()))
11646       opcode = Instruction::PtrToInt;
11647   }
11648   
11649   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11650   // emit a GEP to index into its first field.
11651   if (!NewGEPIndices.empty())
11652     CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11653                                            NewGEPIndices.end());
11654   
11655   NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11656                                    SIOp0->getName()+".c");
11657   return new StoreInst(NewCast, CastOp);
11658 }
11659
11660 /// equivalentAddressValues - Test if A and B will obviously have the same
11661 /// value. This includes recognizing that %t0 and %t1 will have the same
11662 /// value in code like this:
11663 ///   %t0 = getelementptr \@a, 0, 3
11664 ///   store i32 0, i32* %t0
11665 ///   %t1 = getelementptr \@a, 0, 3
11666 ///   %t2 = load i32* %t1
11667 ///
11668 static bool equivalentAddressValues(Value *A, Value *B) {
11669   // Test if the values are trivially equivalent.
11670   if (A == B) return true;
11671   
11672   // Test if the values come form identical arithmetic instructions.
11673   // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11674   // its only used to compare two uses within the same basic block, which
11675   // means that they'll always either have the same value or one of them
11676   // will have an undefined value.
11677   if (isa<BinaryOperator>(A) ||
11678       isa<CastInst>(A) ||
11679       isa<PHINode>(A) ||
11680       isa<GetElementPtrInst>(A))
11681     if (Instruction *BI = dyn_cast<Instruction>(B))
11682       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
11683         return true;
11684   
11685   // Otherwise they may not be equivalent.
11686   return false;
11687 }
11688
11689 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11690 // return the llvm.dbg.declare.
11691 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11692   if (!V->hasNUses(2))
11693     return 0;
11694   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11695        UI != E; ++UI) {
11696     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11697       return DI;
11698     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11699       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11700         return DI;
11701       }
11702   }
11703   return 0;
11704 }
11705
11706 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11707   Value *Val = SI.getOperand(0);
11708   Value *Ptr = SI.getOperand(1);
11709
11710   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11711     EraseInstFromFunction(SI);
11712     ++NumCombined;
11713     return 0;
11714   }
11715   
11716   // If the RHS is an alloca with a single use, zapify the store, making the
11717   // alloca dead.
11718   // If the RHS is an alloca with a two uses, the other one being a 
11719   // llvm.dbg.declare, zapify the store and the declare, making the
11720   // alloca dead.  We must do this to prevent declare's from affecting
11721   // codegen.
11722   if (!SI.isVolatile()) {
11723     if (Ptr->hasOneUse()) {
11724       if (isa<AllocaInst>(Ptr)) {
11725         EraseInstFromFunction(SI);
11726         ++NumCombined;
11727         return 0;
11728       }
11729       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11730         if (isa<AllocaInst>(GEP->getOperand(0))) {
11731           if (GEP->getOperand(0)->hasOneUse()) {
11732             EraseInstFromFunction(SI);
11733             ++NumCombined;
11734             return 0;
11735           }
11736           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11737             EraseInstFromFunction(*DI);
11738             EraseInstFromFunction(SI);
11739             ++NumCombined;
11740             return 0;
11741           }
11742         }
11743       }
11744     }
11745     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11746       EraseInstFromFunction(*DI);
11747       EraseInstFromFunction(SI);
11748       ++NumCombined;
11749       return 0;
11750     }
11751   }
11752
11753   // Attempt to improve the alignment.
11754   if (TD) {
11755     unsigned KnownAlign =
11756       GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11757     if (KnownAlign >
11758         (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11759                                   SI.getAlignment()))
11760       SI.setAlignment(KnownAlign);
11761   }
11762
11763   // Do really simple DSE, to catch cases where there are several consecutive
11764   // stores to the same location, separated by a few arithmetic operations. This
11765   // situation often occurs with bitfield accesses.
11766   BasicBlock::iterator BBI = &SI;
11767   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11768        --ScanInsts) {
11769     --BBI;
11770     // Don't count debug info directives, lest they affect codegen,
11771     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11772     // It is necessary for correctness to skip those that feed into a
11773     // llvm.dbg.declare, as these are not present when debugging is off.
11774     if (isa<DbgInfoIntrinsic>(BBI) ||
11775         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11776       ScanInsts++;
11777       continue;
11778     }    
11779     
11780     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11781       // Prev store isn't volatile, and stores to the same location?
11782       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11783                                                           SI.getOperand(1))) {
11784         ++NumDeadStore;
11785         ++BBI;
11786         EraseInstFromFunction(*PrevSI);
11787         continue;
11788       }
11789       break;
11790     }
11791     
11792     // If this is a load, we have to stop.  However, if the loaded value is from
11793     // the pointer we're loading and is producing the pointer we're storing,
11794     // then *this* store is dead (X = load P; store X -> P).
11795     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11796       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11797           !SI.isVolatile()) {
11798         EraseInstFromFunction(SI);
11799         ++NumCombined;
11800         return 0;
11801       }
11802       // Otherwise, this is a load from some other location.  Stores before it
11803       // may not be dead.
11804       break;
11805     }
11806     
11807     // Don't skip over loads or things that can modify memory.
11808     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11809       break;
11810   }
11811   
11812   
11813   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11814
11815   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11816   if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
11817     if (!isa<UndefValue>(Val)) {
11818       SI.setOperand(0, UndefValue::get(Val->getType()));
11819       if (Instruction *U = dyn_cast<Instruction>(Val))
11820         Worklist.Add(U);  // Dropped a use.
11821       ++NumCombined;
11822     }
11823     return 0;  // Do not modify these!
11824   }
11825
11826   // store undef, Ptr -> noop
11827   if (isa<UndefValue>(Val)) {
11828     EraseInstFromFunction(SI);
11829     ++NumCombined;
11830     return 0;
11831   }
11832
11833   // If the pointer destination is a cast, see if we can fold the cast into the
11834   // source instead.
11835   if (isa<CastInst>(Ptr))
11836     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11837       return Res;
11838   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11839     if (CE->isCast())
11840       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11841         return Res;
11842
11843   
11844   // If this store is the last instruction in the basic block (possibly
11845   // excepting debug info instructions and the pointer bitcasts that feed
11846   // into them), and if the block ends with an unconditional branch, try
11847   // to move it to the successor block.
11848   BBI = &SI; 
11849   do {
11850     ++BBI;
11851   } while (isa<DbgInfoIntrinsic>(BBI) ||
11852            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11853   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11854     if (BI->isUnconditional())
11855       if (SimplifyStoreAtEndOfBlock(SI))
11856         return 0;  // xform done!
11857   
11858   return 0;
11859 }
11860
11861 /// SimplifyStoreAtEndOfBlock - Turn things like:
11862 ///   if () { *P = v1; } else { *P = v2 }
11863 /// into a phi node with a store in the successor.
11864 ///
11865 /// Simplify things like:
11866 ///   *P = v1; if () { *P = v2; }
11867 /// into a phi node with a store in the successor.
11868 ///
11869 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11870   BasicBlock *StoreBB = SI.getParent();
11871   
11872   // Check to see if the successor block has exactly two incoming edges.  If
11873   // so, see if the other predecessor contains a store to the same location.
11874   // if so, insert a PHI node (if needed) and move the stores down.
11875   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11876   
11877   // Determine whether Dest has exactly two predecessors and, if so, compute
11878   // the other predecessor.
11879   pred_iterator PI = pred_begin(DestBB);
11880   BasicBlock *OtherBB = 0;
11881   if (*PI != StoreBB)
11882     OtherBB = *PI;
11883   ++PI;
11884   if (PI == pred_end(DestBB))
11885     return false;
11886   
11887   if (*PI != StoreBB) {
11888     if (OtherBB)
11889       return false;
11890     OtherBB = *PI;
11891   }
11892   if (++PI != pred_end(DestBB))
11893     return false;
11894
11895   // Bail out if all the relevant blocks aren't distinct (this can happen,
11896   // for example, if SI is in an infinite loop)
11897   if (StoreBB == DestBB || OtherBB == DestBB)
11898     return false;
11899
11900   // Verify that the other block ends in a branch and is not otherwise empty.
11901   BasicBlock::iterator BBI = OtherBB->getTerminator();
11902   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11903   if (!OtherBr || BBI == OtherBB->begin())
11904     return false;
11905   
11906   // If the other block ends in an unconditional branch, check for the 'if then
11907   // else' case.  there is an instruction before the branch.
11908   StoreInst *OtherStore = 0;
11909   if (OtherBr->isUnconditional()) {
11910     --BBI;
11911     // Skip over debugging info.
11912     while (isa<DbgInfoIntrinsic>(BBI) ||
11913            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11914       if (BBI==OtherBB->begin())
11915         return false;
11916       --BBI;
11917     }
11918     // If this isn't a store, or isn't a store to the same location, bail out.
11919     OtherStore = dyn_cast<StoreInst>(BBI);
11920     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11921       return false;
11922   } else {
11923     // Otherwise, the other block ended with a conditional branch. If one of the
11924     // destinations is StoreBB, then we have the if/then case.
11925     if (OtherBr->getSuccessor(0) != StoreBB && 
11926         OtherBr->getSuccessor(1) != StoreBB)
11927       return false;
11928     
11929     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11930     // if/then triangle.  See if there is a store to the same ptr as SI that
11931     // lives in OtherBB.
11932     for (;; --BBI) {
11933       // Check to see if we find the matching store.
11934       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11935         if (OtherStore->getOperand(1) != SI.getOperand(1))
11936           return false;
11937         break;
11938       }
11939       // If we find something that may be using or overwriting the stored
11940       // value, or if we run out of instructions, we can't do the xform.
11941       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11942           BBI == OtherBB->begin())
11943         return false;
11944     }
11945     
11946     // In order to eliminate the store in OtherBr, we have to
11947     // make sure nothing reads or overwrites the stored value in
11948     // StoreBB.
11949     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11950       // FIXME: This should really be AA driven.
11951       if (I->mayReadFromMemory() || I->mayWriteToMemory())
11952         return false;
11953     }
11954   }
11955   
11956   // Insert a PHI node now if we need it.
11957   Value *MergedVal = OtherStore->getOperand(0);
11958   if (MergedVal != SI.getOperand(0)) {
11959     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11960     PN->reserveOperandSpace(2);
11961     PN->addIncoming(SI.getOperand(0), SI.getParent());
11962     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11963     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11964   }
11965   
11966   // Advance to a place where it is safe to insert the new store and
11967   // insert it.
11968   BBI = DestBB->getFirstNonPHI();
11969   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11970                                     OtherStore->isVolatile()), *BBI);
11971   
11972   // Nuke the old stores.
11973   EraseInstFromFunction(SI);
11974   EraseInstFromFunction(*OtherStore);
11975   ++NumCombined;
11976   return true;
11977 }
11978
11979
11980 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11981   // Change br (not X), label True, label False to: br X, label False, True
11982   Value *X = 0;
11983   BasicBlock *TrueDest;
11984   BasicBlock *FalseDest;
11985   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11986       !isa<Constant>(X)) {
11987     // Swap Destinations and condition...
11988     BI.setCondition(X);
11989     BI.setSuccessor(0, FalseDest);
11990     BI.setSuccessor(1, TrueDest);
11991     return &BI;
11992   }
11993
11994   // Cannonicalize fcmp_one -> fcmp_oeq
11995   FCmpInst::Predicate FPred; Value *Y;
11996   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
11997                              TrueDest, FalseDest)) &&
11998       BI.getCondition()->hasOneUse())
11999     if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12000         FPred == FCmpInst::FCMP_OGE) {
12001       FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12002       Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12003       
12004       // Swap Destinations and condition.
12005       BI.setSuccessor(0, FalseDest);
12006       BI.setSuccessor(1, TrueDest);
12007       Worklist.Add(Cond);
12008       return &BI;
12009     }
12010
12011   // Cannonicalize icmp_ne -> icmp_eq
12012   ICmpInst::Predicate IPred;
12013   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12014                       TrueDest, FalseDest)) &&
12015       BI.getCondition()->hasOneUse())
12016     if (IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12017         IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12018         IPred == ICmpInst::ICMP_SGE) {
12019       ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12020       Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12021       // Swap Destinations and condition.
12022       BI.setSuccessor(0, FalseDest);
12023       BI.setSuccessor(1, TrueDest);
12024       Worklist.Add(Cond);
12025       return &BI;
12026     }
12027
12028   return 0;
12029 }
12030
12031 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12032   Value *Cond = SI.getCondition();
12033   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12034     if (I->getOpcode() == Instruction::Add)
12035       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12036         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12037         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12038           SI.setOperand(i,
12039                    ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
12040                                                 AddRHS));
12041         SI.setOperand(0, I->getOperand(0));
12042         Worklist.Add(I);
12043         return &SI;
12044       }
12045   }
12046   return 0;
12047 }
12048
12049 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12050   Value *Agg = EV.getAggregateOperand();
12051
12052   if (!EV.hasIndices())
12053     return ReplaceInstUsesWith(EV, Agg);
12054
12055   if (Constant *C = dyn_cast<Constant>(Agg)) {
12056     if (isa<UndefValue>(C))
12057       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12058       
12059     if (isa<ConstantAggregateZero>(C))
12060       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12061
12062     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12063       // Extract the element indexed by the first index out of the constant
12064       Value *V = C->getOperand(*EV.idx_begin());
12065       if (EV.getNumIndices() > 1)
12066         // Extract the remaining indices out of the constant indexed by the
12067         // first index
12068         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12069       else
12070         return ReplaceInstUsesWith(EV, V);
12071     }
12072     return 0; // Can't handle other constants
12073   } 
12074   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12075     // We're extracting from an insertvalue instruction, compare the indices
12076     const unsigned *exti, *exte, *insi, *inse;
12077     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12078          exte = EV.idx_end(), inse = IV->idx_end();
12079          exti != exte && insi != inse;
12080          ++exti, ++insi) {
12081       if (*insi != *exti)
12082         // The insert and extract both reference distinctly different elements.
12083         // This means the extract is not influenced by the insert, and we can
12084         // replace the aggregate operand of the extract with the aggregate
12085         // operand of the insert. i.e., replace
12086         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12087         // %E = extractvalue { i32, { i32 } } %I, 0
12088         // with
12089         // %E = extractvalue { i32, { i32 } } %A, 0
12090         return ExtractValueInst::Create(IV->getAggregateOperand(),
12091                                         EV.idx_begin(), EV.idx_end());
12092     }
12093     if (exti == exte && insi == inse)
12094       // Both iterators are at the end: Index lists are identical. Replace
12095       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12096       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12097       // with "i32 42"
12098       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12099     if (exti == exte) {
12100       // The extract list is a prefix of the insert list. i.e. replace
12101       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12102       // %E = extractvalue { i32, { i32 } } %I, 1
12103       // with
12104       // %X = extractvalue { i32, { i32 } } %A, 1
12105       // %E = insertvalue { i32 } %X, i32 42, 0
12106       // by switching the order of the insert and extract (though the
12107       // insertvalue should be left in, since it may have other uses).
12108       Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12109                                                  EV.idx_begin(), EV.idx_end());
12110       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12111                                      insi, inse);
12112     }
12113     if (insi == inse)
12114       // The insert list is a prefix of the extract list
12115       // We can simply remove the common indices from the extract and make it
12116       // operate on the inserted value instead of the insertvalue result.
12117       // i.e., replace
12118       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12119       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12120       // with
12121       // %E extractvalue { i32 } { i32 42 }, 0
12122       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12123                                       exti, exte);
12124   }
12125   // Can't simplify extracts from other values. Note that nested extracts are
12126   // already simplified implicitely by the above (extract ( extract (insert) )
12127   // will be translated into extract ( insert ( extract ) ) first and then just
12128   // the value inserted, if appropriate).
12129   return 0;
12130 }
12131
12132 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12133 /// is to leave as a vector operation.
12134 static bool CheapToScalarize(Value *V, bool isConstant) {
12135   if (isa<ConstantAggregateZero>(V)) 
12136     return true;
12137   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12138     if (isConstant) return true;
12139     // If all elts are the same, we can extract.
12140     Constant *Op0 = C->getOperand(0);
12141     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12142       if (C->getOperand(i) != Op0)
12143         return false;
12144     return true;
12145   }
12146   Instruction *I = dyn_cast<Instruction>(V);
12147   if (!I) return false;
12148   
12149   // Insert element gets simplified to the inserted element or is deleted if
12150   // this is constant idx extract element and its a constant idx insertelt.
12151   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12152       isa<ConstantInt>(I->getOperand(2)))
12153     return true;
12154   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12155     return true;
12156   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12157     if (BO->hasOneUse() &&
12158         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12159          CheapToScalarize(BO->getOperand(1), isConstant)))
12160       return true;
12161   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12162     if (CI->hasOneUse() &&
12163         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12164          CheapToScalarize(CI->getOperand(1), isConstant)))
12165       return true;
12166   
12167   return false;
12168 }
12169
12170 /// Read and decode a shufflevector mask.
12171 ///
12172 /// It turns undef elements into values that are larger than the number of
12173 /// elements in the input.
12174 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12175   unsigned NElts = SVI->getType()->getNumElements();
12176   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12177     return std::vector<unsigned>(NElts, 0);
12178   if (isa<UndefValue>(SVI->getOperand(2)))
12179     return std::vector<unsigned>(NElts, 2*NElts);
12180
12181   std::vector<unsigned> Result;
12182   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12183   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12184     if (isa<UndefValue>(*i))
12185       Result.push_back(NElts*2);  // undef -> 8
12186     else
12187       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12188   return Result;
12189 }
12190
12191 /// FindScalarElement - Given a vector and an element number, see if the scalar
12192 /// value is already around as a register, for example if it were inserted then
12193 /// extracted from the vector.
12194 static Value *FindScalarElement(Value *V, unsigned EltNo,
12195                                 LLVMContext *Context) {
12196   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12197   const VectorType *PTy = cast<VectorType>(V->getType());
12198   unsigned Width = PTy->getNumElements();
12199   if (EltNo >= Width)  // Out of range access.
12200     return UndefValue::get(PTy->getElementType());
12201   
12202   if (isa<UndefValue>(V))
12203     return UndefValue::get(PTy->getElementType());
12204   else if (isa<ConstantAggregateZero>(V))
12205     return Constant::getNullValue(PTy->getElementType());
12206   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12207     return CP->getOperand(EltNo);
12208   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12209     // If this is an insert to a variable element, we don't know what it is.
12210     if (!isa<ConstantInt>(III->getOperand(2))) 
12211       return 0;
12212     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12213     
12214     // If this is an insert to the element we are looking for, return the
12215     // inserted value.
12216     if (EltNo == IIElt) 
12217       return III->getOperand(1);
12218     
12219     // Otherwise, the insertelement doesn't modify the value, recurse on its
12220     // vector input.
12221     return FindScalarElement(III->getOperand(0), EltNo, Context);
12222   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12223     unsigned LHSWidth =
12224       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12225     unsigned InEl = getShuffleMask(SVI)[EltNo];
12226     if (InEl < LHSWidth)
12227       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12228     else if (InEl < LHSWidth*2)
12229       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12230     else
12231       return UndefValue::get(PTy->getElementType());
12232   }
12233   
12234   // Otherwise, we don't know.
12235   return 0;
12236 }
12237
12238 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12239   // If vector val is undef, replace extract with scalar undef.
12240   if (isa<UndefValue>(EI.getOperand(0)))
12241     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12242
12243   // If vector val is constant 0, replace extract with scalar 0.
12244   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12245     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12246   
12247   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12248     // If vector val is constant with all elements the same, replace EI with
12249     // that element. When the elements are not identical, we cannot replace yet
12250     // (we do that below, but only when the index is constant).
12251     Constant *op0 = C->getOperand(0);
12252     for (unsigned i = 1; i != C->getNumOperands(); ++i)
12253       if (C->getOperand(i) != op0) {
12254         op0 = 0; 
12255         break;
12256       }
12257     if (op0)
12258       return ReplaceInstUsesWith(EI, op0);
12259   }
12260   
12261   // If extracting a specified index from the vector, see if we can recursively
12262   // find a previously computed scalar that was inserted into the vector.
12263   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12264     unsigned IndexVal = IdxC->getZExtValue();
12265     unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
12266       
12267     // If this is extracting an invalid index, turn this into undef, to avoid
12268     // crashing the code below.
12269     if (IndexVal >= VectorWidth)
12270       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12271     
12272     // This instruction only demands the single element from the input vector.
12273     // If the input vector has a single use, simplify it based on this use
12274     // property.
12275     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12276       APInt UndefElts(VectorWidth, 0);
12277       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12278       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12279                                                 DemandedMask, UndefElts)) {
12280         EI.setOperand(0, V);
12281         return &EI;
12282       }
12283     }
12284     
12285     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12286       return ReplaceInstUsesWith(EI, Elt);
12287     
12288     // If the this extractelement is directly using a bitcast from a vector of
12289     // the same number of elements, see if we can find the source element from
12290     // it.  In this case, we will end up needing to bitcast the scalars.
12291     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12292       if (const VectorType *VT = 
12293               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12294         if (VT->getNumElements() == VectorWidth)
12295           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12296                                              IndexVal, Context))
12297             return new BitCastInst(Elt, EI.getType());
12298     }
12299   }
12300   
12301   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12302     // Push extractelement into predecessor operation if legal and
12303     // profitable to do so
12304     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12305       if (I->hasOneUse() &&
12306           CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12307         Value *newEI0 =
12308           Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12309                                         EI.getName()+".lhs");
12310         Value *newEI1 =
12311           Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12312                                         EI.getName()+".rhs");
12313         return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12314       }
12315     } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12316       // Extracting the inserted element?
12317       if (IE->getOperand(2) == EI.getOperand(1))
12318         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12319       // If the inserted and extracted elements are constants, they must not
12320       // be the same value, extract from the pre-inserted value instead.
12321       if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
12322         Worklist.AddValue(EI.getOperand(0));
12323         EI.setOperand(0, IE->getOperand(0));
12324         return &EI;
12325       }
12326     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12327       // If this is extracting an element from a shufflevector, figure out where
12328       // it came from and extract from the appropriate input element instead.
12329       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12330         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12331         Value *Src;
12332         unsigned LHSWidth =
12333           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12334
12335         if (SrcIdx < LHSWidth)
12336           Src = SVI->getOperand(0);
12337         else if (SrcIdx < LHSWidth*2) {
12338           SrcIdx -= LHSWidth;
12339           Src = SVI->getOperand(1);
12340         } else {
12341           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12342         }
12343         return ExtractElementInst::Create(Src,
12344                          ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12345                                           false));
12346       }
12347     }
12348     // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12349   }
12350   return 0;
12351 }
12352
12353 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12354 /// elements from either LHS or RHS, return the shuffle mask and true. 
12355 /// Otherwise, return false.
12356 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12357                                          std::vector<Constant*> &Mask,
12358                                          LLVMContext *Context) {
12359   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12360          "Invalid CollectSingleShuffleElements");
12361   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12362
12363   if (isa<UndefValue>(V)) {
12364     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12365     return true;
12366   } else if (V == LHS) {
12367     for (unsigned i = 0; i != NumElts; ++i)
12368       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12369     return true;
12370   } else if (V == RHS) {
12371     for (unsigned i = 0; i != NumElts; ++i)
12372       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
12373     return true;
12374   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12375     // If this is an insert of an extract from some other vector, include it.
12376     Value *VecOp    = IEI->getOperand(0);
12377     Value *ScalarOp = IEI->getOperand(1);
12378     Value *IdxOp    = IEI->getOperand(2);
12379     
12380     if (!isa<ConstantInt>(IdxOp))
12381       return false;
12382     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12383     
12384     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12385       // Okay, we can handle this if the vector we are insertinting into is
12386       // transitively ok.
12387       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12388         // If so, update the mask to reflect the inserted undef.
12389         Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
12390         return true;
12391       }      
12392     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12393       if (isa<ConstantInt>(EI->getOperand(1)) &&
12394           EI->getOperand(0)->getType() == V->getType()) {
12395         unsigned ExtractedIdx =
12396           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12397         
12398         // This must be extracting from either LHS or RHS.
12399         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12400           // Okay, we can handle this if the vector we are insertinting into is
12401           // transitively ok.
12402           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12403             // If so, update the mask to reflect the inserted value.
12404             if (EI->getOperand(0) == LHS) {
12405               Mask[InsertedIdx % NumElts] = 
12406                  ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12407             } else {
12408               assert(EI->getOperand(0) == RHS);
12409               Mask[InsertedIdx % NumElts] = 
12410                 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
12411               
12412             }
12413             return true;
12414           }
12415         }
12416       }
12417     }
12418   }
12419   // TODO: Handle shufflevector here!
12420   
12421   return false;
12422 }
12423
12424 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12425 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12426 /// that computes V and the LHS value of the shuffle.
12427 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12428                                      Value *&RHS, LLVMContext *Context) {
12429   assert(isa<VectorType>(V->getType()) && 
12430          (RHS == 0 || V->getType() == RHS->getType()) &&
12431          "Invalid shuffle!");
12432   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12433
12434   if (isa<UndefValue>(V)) {
12435     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12436     return V;
12437   } else if (isa<ConstantAggregateZero>(V)) {
12438     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
12439     return V;
12440   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12441     // If this is an insert of an extract from some other vector, include it.
12442     Value *VecOp    = IEI->getOperand(0);
12443     Value *ScalarOp = IEI->getOperand(1);
12444     Value *IdxOp    = IEI->getOperand(2);
12445     
12446     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12447       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12448           EI->getOperand(0)->getType() == V->getType()) {
12449         unsigned ExtractedIdx =
12450           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12451         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12452         
12453         // Either the extracted from or inserted into vector must be RHSVec,
12454         // otherwise we'd end up with a shuffle of three inputs.
12455         if (EI->getOperand(0) == RHS || RHS == 0) {
12456           RHS = EI->getOperand(0);
12457           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12458           Mask[InsertedIdx % NumElts] = 
12459             ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
12460           return V;
12461         }
12462         
12463         if (VecOp == RHS) {
12464           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12465                                             RHS, Context);
12466           // Everything but the extracted element is replaced with the RHS.
12467           for (unsigned i = 0; i != NumElts; ++i) {
12468             if (i != InsertedIdx)
12469               Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
12470           }
12471           return V;
12472         }
12473         
12474         // If this insertelement is a chain that comes from exactly these two
12475         // vectors, return the vector and the effective shuffle.
12476         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12477                                          Context))
12478           return EI->getOperand(0);
12479         
12480       }
12481     }
12482   }
12483   // TODO: Handle shufflevector here!
12484   
12485   // Otherwise, can't do anything fancy.  Return an identity vector.
12486   for (unsigned i = 0; i != NumElts; ++i)
12487     Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12488   return V;
12489 }
12490
12491 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12492   Value *VecOp    = IE.getOperand(0);
12493   Value *ScalarOp = IE.getOperand(1);
12494   Value *IdxOp    = IE.getOperand(2);
12495   
12496   // Inserting an undef or into an undefined place, remove this.
12497   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12498     ReplaceInstUsesWith(IE, VecOp);
12499   
12500   // If the inserted element was extracted from some other vector, and if the 
12501   // indexes are constant, try to turn this into a shufflevector operation.
12502   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12503     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12504         EI->getOperand(0)->getType() == IE.getType()) {
12505       unsigned NumVectorElts = IE.getType()->getNumElements();
12506       unsigned ExtractedIdx =
12507         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12508       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12509       
12510       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12511         return ReplaceInstUsesWith(IE, VecOp);
12512       
12513       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12514         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12515       
12516       // If we are extracting a value from a vector, then inserting it right
12517       // back into the same place, just use the input vector.
12518       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12519         return ReplaceInstUsesWith(IE, VecOp);      
12520       
12521       // If this insertelement isn't used by some other insertelement, turn it
12522       // (and any insertelements it points to), into one big shuffle.
12523       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12524         std::vector<Constant*> Mask;
12525         Value *RHS = 0;
12526         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12527         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12528         // We now have a shuffle of LHS, RHS, Mask.
12529         return new ShuffleVectorInst(LHS, RHS,
12530                                      ConstantVector::get(Mask));
12531       }
12532     }
12533   }
12534
12535   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12536   APInt UndefElts(VWidth, 0);
12537   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12538   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12539     return &IE;
12540
12541   return 0;
12542 }
12543
12544
12545 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12546   Value *LHS = SVI.getOperand(0);
12547   Value *RHS = SVI.getOperand(1);
12548   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12549
12550   bool MadeChange = false;
12551
12552   // Undefined shuffle mask -> undefined value.
12553   if (isa<UndefValue>(SVI.getOperand(2)))
12554     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12555
12556   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12557
12558   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12559     return 0;
12560
12561   APInt UndefElts(VWidth, 0);
12562   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12563   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12564     LHS = SVI.getOperand(0);
12565     RHS = SVI.getOperand(1);
12566     MadeChange = true;
12567   }
12568   
12569   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12570   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12571   if (LHS == RHS || isa<UndefValue>(LHS)) {
12572     if (isa<UndefValue>(LHS) && LHS == RHS) {
12573       // shuffle(undef,undef,mask) -> undef.
12574       return ReplaceInstUsesWith(SVI, LHS);
12575     }
12576     
12577     // Remap any references to RHS to use LHS.
12578     std::vector<Constant*> Elts;
12579     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12580       if (Mask[i] >= 2*e)
12581         Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12582       else {
12583         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12584             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12585           Mask[i] = 2*e;     // Turn into undef.
12586           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12587         } else {
12588           Mask[i] = Mask[i] % e;  // Force to LHS.
12589           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
12590         }
12591       }
12592     }
12593     SVI.setOperand(0, SVI.getOperand(1));
12594     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12595     SVI.setOperand(2, ConstantVector::get(Elts));
12596     LHS = SVI.getOperand(0);
12597     RHS = SVI.getOperand(1);
12598     MadeChange = true;
12599   }
12600   
12601   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12602   bool isLHSID = true, isRHSID = true;
12603     
12604   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12605     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12606     // Is this an identity shuffle of the LHS value?
12607     isLHSID &= (Mask[i] == i);
12608       
12609     // Is this an identity shuffle of the RHS value?
12610     isRHSID &= (Mask[i]-e == i);
12611   }
12612
12613   // Eliminate identity shuffles.
12614   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12615   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12616   
12617   // If the LHS is a shufflevector itself, see if we can combine it with this
12618   // one without producing an unusual shuffle.  Here we are really conservative:
12619   // we are absolutely afraid of producing a shuffle mask not in the input
12620   // program, because the code gen may not be smart enough to turn a merged
12621   // shuffle into two specific shuffles: it may produce worse code.  As such,
12622   // we only merge two shuffles if the result is one of the two input shuffle
12623   // masks.  In this case, merging the shuffles just removes one instruction,
12624   // which we know is safe.  This is good for things like turning:
12625   // (splat(splat)) -> splat.
12626   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12627     if (isa<UndefValue>(RHS)) {
12628       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12629
12630       std::vector<unsigned> NewMask;
12631       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12632         if (Mask[i] >= 2*e)
12633           NewMask.push_back(2*e);
12634         else
12635           NewMask.push_back(LHSMask[Mask[i]]);
12636       
12637       // If the result mask is equal to the src shuffle or this shuffle mask, do
12638       // the replacement.
12639       if (NewMask == LHSMask || NewMask == Mask) {
12640         unsigned LHSInNElts =
12641           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12642         std::vector<Constant*> Elts;
12643         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12644           if (NewMask[i] >= LHSInNElts*2) {
12645             Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12646           } else {
12647             Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
12648           }
12649         }
12650         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12651                                      LHSSVI->getOperand(1),
12652                                      ConstantVector::get(Elts));
12653       }
12654     }
12655   }
12656
12657   return MadeChange ? &SVI : 0;
12658 }
12659
12660
12661
12662
12663 /// TryToSinkInstruction - Try to move the specified instruction from its
12664 /// current block into the beginning of DestBlock, which can only happen if it's
12665 /// safe to move the instruction past all of the instructions between it and the
12666 /// end of its block.
12667 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12668   assert(I->hasOneUse() && "Invariants didn't hold!");
12669
12670   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12671   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12672     return false;
12673
12674   // Do not sink alloca instructions out of the entry block.
12675   if (isa<AllocaInst>(I) && I->getParent() ==
12676         &DestBlock->getParent()->getEntryBlock())
12677     return false;
12678
12679   // We can only sink load instructions if there is nothing between the load and
12680   // the end of block that could change the value.
12681   if (I->mayReadFromMemory()) {
12682     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12683          Scan != E; ++Scan)
12684       if (Scan->mayWriteToMemory())
12685         return false;
12686   }
12687
12688   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12689
12690   CopyPrecedingStopPoint(I, InsertPos);
12691   I->moveBefore(InsertPos);
12692   ++NumSunkInst;
12693   return true;
12694 }
12695
12696
12697 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12698 /// all reachable code to the worklist.
12699 ///
12700 /// This has a couple of tricks to make the code faster and more powerful.  In
12701 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12702 /// them to the worklist (this significantly speeds up instcombine on code where
12703 /// many instructions are dead or constant).  Additionally, if we find a branch
12704 /// whose condition is a known constant, we only visit the reachable successors.
12705 ///
12706 static bool AddReachableCodeToWorklist(BasicBlock *BB, 
12707                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12708                                        InstCombiner &IC,
12709                                        const TargetData *TD) {
12710   bool MadeIRChange = false;
12711   SmallVector<BasicBlock*, 256> Worklist;
12712   Worklist.push_back(BB);
12713   
12714   std::vector<Instruction*> InstrsForInstCombineWorklist;
12715   InstrsForInstCombineWorklist.reserve(128);
12716
12717   SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
12718   
12719   while (!Worklist.empty()) {
12720     BB = Worklist.back();
12721     Worklist.pop_back();
12722     
12723     // We have now visited this block!  If we've already been here, ignore it.
12724     if (!Visited.insert(BB)) continue;
12725
12726     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12727       Instruction *Inst = BBI++;
12728       
12729       // DCE instruction if trivially dead.
12730       if (isInstructionTriviallyDead(Inst)) {
12731         ++NumDeadInst;
12732         DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
12733         Inst->eraseFromParent();
12734         continue;
12735       }
12736       
12737       // ConstantProp instruction if trivially constant.
12738       if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
12739         if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12740           DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12741                        << *Inst << '\n');
12742           Inst->replaceAllUsesWith(C);
12743           ++NumConstProp;
12744           Inst->eraseFromParent();
12745           continue;
12746         }
12747       
12748       
12749       
12750       if (TD) {
12751         // See if we can constant fold its operands.
12752         for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
12753              i != e; ++i) {
12754           ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
12755           if (CE == 0) continue;
12756           
12757           // If we already folded this constant, don't try again.
12758           if (!FoldedConstants.insert(CE))
12759             continue;
12760           
12761           Constant *NewC =
12762             ConstantFoldConstantExpression(CE, BB->getContext(), TD);
12763           if (NewC && NewC != CE) {
12764             *i = NewC;
12765             MadeIRChange = true;
12766           }
12767         }
12768       }
12769       
12770
12771       InstrsForInstCombineWorklist.push_back(Inst);
12772     }
12773
12774     // Recursively visit successors.  If this is a branch or switch on a
12775     // constant, only visit the reachable successor.
12776     TerminatorInst *TI = BB->getTerminator();
12777     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12778       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12779         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12780         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12781         Worklist.push_back(ReachableBB);
12782         continue;
12783       }
12784     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12785       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12786         // See if this is an explicit destination.
12787         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12788           if (SI->getCaseValue(i) == Cond) {
12789             BasicBlock *ReachableBB = SI->getSuccessor(i);
12790             Worklist.push_back(ReachableBB);
12791             continue;
12792           }
12793         
12794         // Otherwise it is the default destination.
12795         Worklist.push_back(SI->getSuccessor(0));
12796         continue;
12797       }
12798     }
12799     
12800     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12801       Worklist.push_back(TI->getSuccessor(i));
12802   }
12803   
12804   // Once we've found all of the instructions to add to instcombine's worklist,
12805   // add them in reverse order.  This way instcombine will visit from the top
12806   // of the function down.  This jives well with the way that it adds all uses
12807   // of instructions to the worklist after doing a transformation, thus avoiding
12808   // some N^2 behavior in pathological cases.
12809   IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
12810                               InstrsForInstCombineWorklist.size());
12811   
12812   return MadeIRChange;
12813 }
12814
12815 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12816   MadeIRChange = false;
12817   
12818   DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12819         << F.getNameStr() << "\n");
12820
12821   {
12822     // Do a depth-first traversal of the function, populate the worklist with
12823     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12824     // track of which blocks we visit.
12825     SmallPtrSet<BasicBlock*, 64> Visited;
12826     MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12827
12828     // Do a quick scan over the function.  If we find any blocks that are
12829     // unreachable, remove any instructions inside of them.  This prevents
12830     // the instcombine code from having to deal with some bad special cases.
12831     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12832       if (!Visited.count(BB)) {
12833         Instruction *Term = BB->getTerminator();
12834         while (Term != BB->begin()) {   // Remove instrs bottom-up
12835           BasicBlock::iterator I = Term; --I;
12836
12837           DEBUG(errs() << "IC: DCE: " << *I << '\n');
12838           // A debug intrinsic shouldn't force another iteration if we weren't
12839           // going to do one without it.
12840           if (!isa<DbgInfoIntrinsic>(I)) {
12841             ++NumDeadInst;
12842             MadeIRChange = true;
12843           }
12844
12845           // If I is not void type then replaceAllUsesWith undef.
12846           // This allows ValueHandlers and custom metadata to adjust itself.
12847           if (!I->getType()->isVoidTy())
12848             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12849           I->eraseFromParent();
12850         }
12851       }
12852   }
12853
12854   while (!Worklist.isEmpty()) {
12855     Instruction *I = Worklist.RemoveOne();
12856     if (I == 0) continue;  // skip null values.
12857
12858     // Check to see if we can DCE the instruction.
12859     if (isInstructionTriviallyDead(I)) {
12860       DEBUG(errs() << "IC: DCE: " << *I << '\n');
12861       EraseInstFromFunction(*I);
12862       ++NumDeadInst;
12863       MadeIRChange = true;
12864       continue;
12865     }
12866
12867     // Instruction isn't dead, see if we can constant propagate it.
12868     if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
12869       if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12870         DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
12871
12872         // Add operands to the worklist.
12873         ReplaceInstUsesWith(*I, C);
12874         ++NumConstProp;
12875         EraseInstFromFunction(*I);
12876         MadeIRChange = true;
12877         continue;
12878       }
12879
12880     // See if we can trivially sink this instruction to a successor basic block.
12881     if (I->hasOneUse()) {
12882       BasicBlock *BB = I->getParent();
12883       Instruction *UserInst = cast<Instruction>(I->use_back());
12884       BasicBlock *UserParent;
12885       
12886       // Get the block the use occurs in.
12887       if (PHINode *PN = dyn_cast<PHINode>(UserInst))
12888         UserParent = PN->getIncomingBlock(I->use_begin().getUse());
12889       else
12890         UserParent = UserInst->getParent();
12891       
12892       if (UserParent != BB) {
12893         bool UserIsSuccessor = false;
12894         // See if the user is one of our successors.
12895         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12896           if (*SI == UserParent) {
12897             UserIsSuccessor = true;
12898             break;
12899           }
12900
12901         // If the user is one of our immediate successors, and if that successor
12902         // only has us as a predecessors (we'd have to split the critical edge
12903         // otherwise), we can keep going.
12904         if (UserIsSuccessor && UserParent->getSinglePredecessor())
12905           // Okay, the CFG is simple enough, try to sink this instruction.
12906           MadeIRChange |= TryToSinkInstruction(I, UserParent);
12907       }
12908     }
12909
12910     // Now that we have an instruction, try combining it to simplify it.
12911     Builder->SetInsertPoint(I->getParent(), I);
12912     
12913 #ifndef NDEBUG
12914     std::string OrigI;
12915 #endif
12916     DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
12917     DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
12918
12919     if (Instruction *Result = visit(*I)) {
12920       ++NumCombined;
12921       // Should we replace the old instruction with a new one?
12922       if (Result != I) {
12923         DEBUG(errs() << "IC: Old = " << *I << '\n'
12924                      << "    New = " << *Result << '\n');
12925
12926         // Everything uses the new instruction now.
12927         I->replaceAllUsesWith(Result);
12928
12929         // Push the new instruction and any users onto the worklist.
12930         Worklist.Add(Result);
12931         Worklist.AddUsersToWorkList(*Result);
12932
12933         // Move the name to the new instruction first.
12934         Result->takeName(I);
12935
12936         // Insert the new instruction into the basic block...
12937         BasicBlock *InstParent = I->getParent();
12938         BasicBlock::iterator InsertPos = I;
12939
12940         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
12941           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12942             ++InsertPos;
12943
12944         InstParent->getInstList().insert(InsertPos, Result);
12945
12946         EraseInstFromFunction(*I);
12947       } else {
12948 #ifndef NDEBUG
12949         DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12950                      << "    New = " << *I << '\n');
12951 #endif
12952
12953         // If the instruction was modified, it's possible that it is now dead.
12954         // if so, remove it.
12955         if (isInstructionTriviallyDead(I)) {
12956           EraseInstFromFunction(*I);
12957         } else {
12958           Worklist.Add(I);
12959           Worklist.AddUsersToWorkList(*I);
12960         }
12961       }
12962       MadeIRChange = true;
12963     }
12964   }
12965
12966   Worklist.Zap();
12967   return MadeIRChange;
12968 }
12969
12970
12971 bool InstCombiner::runOnFunction(Function &F) {
12972   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12973   Context = &F.getContext();
12974   TD = getAnalysisIfAvailable<TargetData>();
12975
12976   
12977   /// Builder - This is an IRBuilder that automatically inserts new
12978   /// instructions into the worklist when they are created.
12979   IRBuilder<true, TargetFolder, InstCombineIRInserter> 
12980     TheBuilder(F.getContext(), TargetFolder(TD, F.getContext()),
12981                InstCombineIRInserter(Worklist));
12982   Builder = &TheBuilder;
12983   
12984   bool EverMadeChange = false;
12985
12986   // Iterate while there is work to do.
12987   unsigned Iteration = 0;
12988   while (DoOneIteration(F, Iteration++))
12989     EverMadeChange = true;
12990   
12991   Builder = 0;
12992   return EverMadeChange;
12993 }
12994
12995 FunctionPass *llvm::createInstructionCombiningPass() {
12996   return new InstCombiner();
12997 }