Make LSR's OptimizeShadowIV ignore induction variables with negative
[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 *visitAllocaInst(AllocaInst &AI);
288     Instruction *visitFreeInst(FreeInst &FI);
289     Instruction *visitFree(Instruction &FI);
290     Instruction *visitLoadInst(LoadInst &LI);
291     Instruction *visitStoreInst(StoreInst &SI);
292     Instruction *visitBranchInst(BranchInst &BI);
293     Instruction *visitSwitchInst(SwitchInst &SI);
294     Instruction *visitInsertElementInst(InsertElementInst &IE);
295     Instruction *visitExtractElementInst(ExtractElementInst &EI);
296     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
297     Instruction *visitExtractValueInst(ExtractValueInst &EV);
298
299     // visitInstruction - Specify what to return for unhandled instructions...
300     Instruction *visitInstruction(Instruction &I) { return 0; }
301
302   private:
303     Instruction *visitCallSite(CallSite CS);
304     bool transformConstExprCastCall(CallSite CS);
305     Instruction *transformCallThroughTrampoline(CallSite CS);
306     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
307                                    bool DoXform = true);
308     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
309     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
310
311
312   public:
313     // InsertNewInstBefore - insert an instruction New before instruction Old
314     // in the program.  Add the new instruction to the worklist.
315     //
316     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
317       assert(New && New->getParent() == 0 &&
318              "New instruction already inserted into a basic block!");
319       BasicBlock *BB = Old.getParent();
320       BB->getInstList().insert(&Old, New);  // Insert inst
321       Worklist.Add(New);
322       return New;
323     }
324         
325     // ReplaceInstUsesWith - This method is to be used when an instruction is
326     // found to be dead, replacable with another preexisting expression.  Here
327     // we add all uses of I to the worklist, replace all uses of I with the new
328     // value, then return I, so that the inst combiner will know that I was
329     // modified.
330     //
331     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
332       Worklist.AddUsersToWorkList(I);   // Add all modified instrs to worklist.
333       
334       // If we are replacing the instruction with itself, this must be in a
335       // segment of unreachable code, so just clobber the instruction.
336       if (&I == V) 
337         V = UndefValue::get(I.getType());
338         
339       I.replaceAllUsesWith(V);
340       return &I;
341     }
342
343     // EraseInstFromFunction - When dealing with an instruction that has side
344     // effects or produces a void value, we can't rely on DCE to delete the
345     // instruction.  Instead, visit methods should return the value returned by
346     // this function.
347     Instruction *EraseInstFromFunction(Instruction &I) {
348       DEBUG(errs() << "IC: ERASE " << I << '\n');
349
350       assert(I.use_empty() && "Cannot erase instruction that is used!");
351       // Make sure that we reprocess all operands now that we reduced their
352       // use counts.
353       if (I.getNumOperands() < 8) {
354         for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
355           if (Instruction *Op = dyn_cast<Instruction>(*i))
356             Worklist.Add(Op);
357       }
358       Worklist.Remove(&I);
359       I.eraseFromParent();
360       MadeIRChange = true;
361       return 0;  // Don't do anything with FI
362     }
363         
364     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
365                            APInt &KnownOne, unsigned Depth = 0) const {
366       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
367     }
368     
369     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
370                            unsigned Depth = 0) const {
371       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
372     }
373     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
374       return llvm::ComputeNumSignBits(Op, TD, Depth);
375     }
376
377   private:
378
379     /// SimplifyCommutative - This performs a few simplifications for 
380     /// commutative operators.
381     bool SimplifyCommutative(BinaryOperator &I);
382
383     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
384     /// most-complex to least-complex order.
385     bool SimplifyCompare(CmpInst &I);
386
387     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
388     /// based on the demanded bits.
389     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
390                                    APInt& KnownZero, APInt& KnownOne,
391                                    unsigned Depth);
392     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
393                               APInt& KnownZero, APInt& KnownOne,
394                               unsigned Depth=0);
395         
396     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
397     /// SimplifyDemandedBits knows about.  See if the instruction has any
398     /// properties that allow us to simplify its operands.
399     bool SimplifyDemandedInstructionBits(Instruction &Inst);
400         
401     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
402                                       APInt& UndefElts, unsigned Depth = 0);
403       
404     // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
405     // which has a PHI node as operand #0, see if we can fold the instruction
406     // into the PHI (which is only possible if all operands to the PHI are
407     // constants).
408     //
409     // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
410     // that would normally be unprofitable because they strongly encourage jump
411     // threading.
412     Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
413
414     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
415     // operator and they all are only used by the PHI, PHI together their
416     // inputs, and do the operation once, to the result of the PHI.
417     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
418     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
419     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
420
421     
422     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
423                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
424     
425     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
426                               bool isSub, Instruction &I);
427     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
428                                  bool isSigned, bool Inside, Instruction &IB);
429     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
430     Instruction *MatchBSwap(BinaryOperator &I);
431     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
432     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
433     Instruction *SimplifyMemSet(MemSetInst *MI);
434
435
436     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
437
438     bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
439                                     unsigned CastOpc, int &NumCastsRemoved);
440     unsigned GetOrEnforceKnownAlignment(Value *V,
441                                         unsigned PrefAlign = 0);
442
443   };
444 } // end anonymous namespace
445
446 char InstCombiner::ID = 0;
447 static RegisterPass<InstCombiner>
448 X("instcombine", "Combine redundant instructions");
449
450 // getComplexity:  Assign a complexity or rank value to LLVM Values...
451 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
452 static unsigned getComplexity(Value *V) {
453   if (isa<Instruction>(V)) {
454     if (BinaryOperator::isNeg(V) ||
455         BinaryOperator::isFNeg(V) ||
456         BinaryOperator::isNot(V))
457       return 3;
458     return 4;
459   }
460   if (isa<Argument>(V)) return 3;
461   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
462 }
463
464 // isOnlyUse - Return true if this instruction will be deleted if we stop using
465 // it.
466 static bool isOnlyUse(Value *V) {
467   return V->hasOneUse() || isa<Constant>(V);
468 }
469
470 // getPromotedType - Return the specified type promoted as it would be to pass
471 // though a va_arg area...
472 static const Type *getPromotedType(const Type *Ty) {
473   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
474     if (ITy->getBitWidth() < 32)
475       return Type::getInt32Ty(Ty->getContext());
476   }
477   return Ty;
478 }
479
480 /// getBitCastOperand - If the specified operand is a CastInst, a constant
481 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
482 /// operand value, otherwise return null.
483 static Value *getBitCastOperand(Value *V) {
484   if (Operator *O = dyn_cast<Operator>(V)) {
485     if (O->getOpcode() == Instruction::BitCast)
486       return O->getOperand(0);
487     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
488       if (GEP->hasAllZeroIndices())
489         return GEP->getPointerOperand();
490   }
491   return 0;
492 }
493
494 /// This function is a wrapper around CastInst::isEliminableCastPair. It
495 /// simply extracts arguments and returns what that function returns.
496 static Instruction::CastOps 
497 isEliminableCastPair(
498   const CastInst *CI, ///< The first cast instruction
499   unsigned opcode,       ///< The opcode of the second cast instruction
500   const Type *DstTy,     ///< The target type for the second cast instruction
501   TargetData *TD         ///< The target data for pointer size
502 ) {
503
504   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
505   const Type *MidTy = CI->getType();                  // B from above
506
507   // Get the opcodes of the two Cast instructions
508   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
509   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
510
511   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
512                                                 DstTy,
513                                   TD ? TD->getIntPtrType(CI->getContext()) : 0);
514   
515   // We don't want to form an inttoptr or ptrtoint that converts to an integer
516   // type that differs from the pointer size.
517   if ((Res == Instruction::IntToPtr &&
518           (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
519       (Res == Instruction::PtrToInt &&
520           (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
521     Res = 0;
522   
523   return Instruction::CastOps(Res);
524 }
525
526 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
527 /// in any code being generated.  It does not require codegen if V is simple
528 /// enough or if the cast can be folded into other casts.
529 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
530                               const Type *Ty, TargetData *TD) {
531   if (V->getType() == Ty || isa<Constant>(V)) return false;
532   
533   // If this is another cast that can be eliminated, it isn't codegen either.
534   if (const CastInst *CI = dyn_cast<CastInst>(V))
535     if (isEliminableCastPair(CI, opcode, Ty, TD))
536       return false;
537   return true;
538 }
539
540 // SimplifyCommutative - This performs a few simplifications for commutative
541 // operators:
542 //
543 //  1. Order operands such that they are listed from right (least complex) to
544 //     left (most complex).  This puts constants before unary operators before
545 //     binary operators.
546 //
547 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
548 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
549 //
550 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
551   bool Changed = false;
552   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
553     Changed = !I.swapOperands();
554
555   if (!I.isAssociative()) return Changed;
556   Instruction::BinaryOps Opcode = I.getOpcode();
557   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
558     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
559       if (isa<Constant>(I.getOperand(1))) {
560         Constant *Folded = ConstantExpr::get(I.getOpcode(),
561                                              cast<Constant>(I.getOperand(1)),
562                                              cast<Constant>(Op->getOperand(1)));
563         I.setOperand(0, Op->getOperand(0));
564         I.setOperand(1, Folded);
565         return true;
566       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
567         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
568             isOnlyUse(Op) && isOnlyUse(Op1)) {
569           Constant *C1 = cast<Constant>(Op->getOperand(1));
570           Constant *C2 = cast<Constant>(Op1->getOperand(1));
571
572           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
573           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
574           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
575                                                     Op1->getOperand(0),
576                                                     Op1->getName(), &I);
577           Worklist.Add(New);
578           I.setOperand(0, New);
579           I.setOperand(1, Folded);
580           return true;
581         }
582     }
583   return Changed;
584 }
585
586 /// SimplifyCompare - For a CmpInst this function just orders the operands
587 /// so that theyare listed from right (least complex) to left (most complex).
588 /// This puts constants before unary operators before binary operators.
589 bool InstCombiner::SimplifyCompare(CmpInst &I) {
590   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
591     return false;
592   I.swapOperands();
593   // Compare instructions are not associative so there's nothing else we can do.
594   return true;
595 }
596
597 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
598 // if the LHS is a constant zero (which is the 'negate' form).
599 //
600 static inline Value *dyn_castNegVal(Value *V) {
601   if (BinaryOperator::isNeg(V))
602     return BinaryOperator::getNegArgument(V);
603
604   // Constants can be considered to be negated values if they can be folded.
605   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
606     return ConstantExpr::getNeg(C);
607
608   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
609     if (C->getType()->getElementType()->isInteger())
610       return ConstantExpr::getNeg(C);
611
612   return 0;
613 }
614
615 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
616 // instruction if the LHS is a constant negative zero (which is the 'negate'
617 // form).
618 //
619 static inline Value *dyn_castFNegVal(Value *V) {
620   if (BinaryOperator::isFNeg(V))
621     return BinaryOperator::getFNegArgument(V);
622
623   // Constants can be considered to be negated values if they can be folded.
624   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
625     return ConstantExpr::getFNeg(C);
626
627   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
628     if (C->getType()->getElementType()->isFloatingPoint())
629       return ConstantExpr::getFNeg(C);
630
631   return 0;
632 }
633
634 static inline Value *dyn_castNotVal(Value *V) {
635   if (BinaryOperator::isNot(V))
636     return BinaryOperator::getNotArgument(V);
637
638   // Constants can be considered to be not'ed values...
639   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
640     return ConstantInt::get(C->getType(), ~C->getValue());
641   return 0;
642 }
643
644 // dyn_castFoldableMul - If this value is a multiply that can be folded into
645 // other computations (because it has a constant operand), return the
646 // non-constant operand of the multiply, and set CST to point to the multiplier.
647 // Otherwise, return null.
648 //
649 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
650   if (V->hasOneUse() && V->getType()->isInteger())
651     if (Instruction *I = dyn_cast<Instruction>(V)) {
652       if (I->getOpcode() == Instruction::Mul)
653         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
654           return I->getOperand(0);
655       if (I->getOpcode() == Instruction::Shl)
656         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
657           // The multiplier is really 1 << CST.
658           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
659           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
660           CST = ConstantInt::get(V->getType()->getContext(),
661                                  APInt(BitWidth, 1).shl(CSTVal));
662           return I->getOperand(0);
663         }
664     }
665   return 0;
666 }
667
668 /// AddOne - Add one to a ConstantInt
669 static Constant *AddOne(Constant *C) {
670   return ConstantExpr::getAdd(C, 
671     ConstantInt::get(C->getType(), 1));
672 }
673 /// SubOne - Subtract one from a ConstantInt
674 static Constant *SubOne(ConstantInt *C) {
675   return ConstantExpr::getSub(C, 
676     ConstantInt::get(C->getType(), 1));
677 }
678 /// MultiplyOverflows - True if the multiply can not be expressed in an int
679 /// this size.
680 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
681   uint32_t W = C1->getBitWidth();
682   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
683   if (sign) {
684     LHSExt.sext(W * 2);
685     RHSExt.sext(W * 2);
686   } else {
687     LHSExt.zext(W * 2);
688     RHSExt.zext(W * 2);
689   }
690
691   APInt MulExt = LHSExt * RHSExt;
692
693   if (sign) {
694     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
695     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
696     return MulExt.slt(Min) || MulExt.sgt(Max);
697   } else 
698     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
699 }
700
701
702 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
703 /// specified instruction is a constant integer.  If so, check to see if there
704 /// are any bits set in the constant that are not demanded.  If so, shrink the
705 /// constant and return true.
706 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
707                                    APInt Demanded) {
708   assert(I && "No instruction?");
709   assert(OpNo < I->getNumOperands() && "Operand index too large");
710
711   // If the operand is not a constant integer, nothing to do.
712   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
713   if (!OpC) return false;
714
715   // If there are no bits set that aren't demanded, nothing to do.
716   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
717   if ((~Demanded & OpC->getValue()) == 0)
718     return false;
719
720   // This instruction is producing bits that are not demanded. Shrink the RHS.
721   Demanded &= OpC->getValue();
722   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
723   return true;
724 }
725
726 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
727 // set of known zero and one bits, compute the maximum and minimum values that
728 // could have the specified known zero and known one bits, returning them in
729 // min/max.
730 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
731                                                    const APInt& KnownOne,
732                                                    APInt& Min, APInt& Max) {
733   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
734          KnownZero.getBitWidth() == Min.getBitWidth() &&
735          KnownZero.getBitWidth() == Max.getBitWidth() &&
736          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
737   APInt UnknownBits = ~(KnownZero|KnownOne);
738
739   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
740   // bit if it is unknown.
741   Min = KnownOne;
742   Max = KnownOne|UnknownBits;
743   
744   if (UnknownBits.isNegative()) { // Sign bit is unknown
745     Min.set(Min.getBitWidth()-1);
746     Max.clear(Max.getBitWidth()-1);
747   }
748 }
749
750 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
751 // a set of known zero and one bits, compute the maximum and minimum values that
752 // could have the specified known zero and known one bits, returning them in
753 // min/max.
754 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
755                                                      const APInt &KnownOne,
756                                                      APInt &Min, APInt &Max) {
757   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
758          KnownZero.getBitWidth() == Min.getBitWidth() &&
759          KnownZero.getBitWidth() == Max.getBitWidth() &&
760          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
761   APInt UnknownBits = ~(KnownZero|KnownOne);
762   
763   // The minimum value is when the unknown bits are all zeros.
764   Min = KnownOne;
765   // The maximum value is when the unknown bits are all ones.
766   Max = KnownOne|UnknownBits;
767 }
768
769 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
770 /// SimplifyDemandedBits knows about.  See if the instruction has any
771 /// properties that allow us to simplify its operands.
772 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
773   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
774   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
775   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
776   
777   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
778                                      KnownZero, KnownOne, 0);
779   if (V == 0) return false;
780   if (V == &Inst) return true;
781   ReplaceInstUsesWith(Inst, V);
782   return true;
783 }
784
785 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
786 /// specified instruction operand if possible, updating it in place.  It returns
787 /// true if it made any change and false otherwise.
788 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
789                                         APInt &KnownZero, APInt &KnownOne,
790                                         unsigned Depth) {
791   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
792                                           KnownZero, KnownOne, Depth);
793   if (NewVal == 0) return false;
794   U = NewVal;
795   return true;
796 }
797
798
799 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
800 /// value based on the demanded bits.  When this function is called, it is known
801 /// that only the bits set in DemandedMask of the result of V are ever used
802 /// downstream. Consequently, depending on the mask and V, it may be possible
803 /// to replace V with a constant or one of its operands. In such cases, this
804 /// function does the replacement and returns true. In all other cases, it
805 /// returns false after analyzing the expression and setting KnownOne and known
806 /// to be one in the expression.  KnownZero contains all the bits that are known
807 /// to be zero in the expression. These are provided to potentially allow the
808 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
809 /// the expression. KnownOne and KnownZero always follow the invariant that 
810 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
811 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
812 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
813 /// and KnownOne must all be the same.
814 ///
815 /// This returns null if it did not change anything and it permits no
816 /// simplification.  This returns V itself if it did some simplification of V's
817 /// operands based on the information about what bits are demanded. This returns
818 /// some other non-null value if it found out that V is equal to another value
819 /// in the context where the specified bits are demanded, but not for all users.
820 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
821                                              APInt &KnownZero, APInt &KnownOne,
822                                              unsigned Depth) {
823   assert(V != 0 && "Null pointer of Value???");
824   assert(Depth <= 6 && "Limit Search Depth");
825   uint32_t BitWidth = DemandedMask.getBitWidth();
826   const Type *VTy = V->getType();
827   assert((TD || !isa<PointerType>(VTy)) &&
828          "SimplifyDemandedBits needs to know bit widths!");
829   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
830          (!VTy->isIntOrIntVector() ||
831           VTy->getScalarSizeInBits() == BitWidth) &&
832          KnownZero.getBitWidth() == BitWidth &&
833          KnownOne.getBitWidth() == BitWidth &&
834          "Value *V, DemandedMask, KnownZero and KnownOne "
835          "must have same BitWidth");
836   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
837     // We know all of the bits for a constant!
838     KnownOne = CI->getValue() & DemandedMask;
839     KnownZero = ~KnownOne & DemandedMask;
840     return 0;
841   }
842   if (isa<ConstantPointerNull>(V)) {
843     // We know all of the bits for a constant!
844     KnownOne.clear();
845     KnownZero = DemandedMask;
846     return 0;
847   }
848
849   KnownZero.clear();
850   KnownOne.clear();
851   if (DemandedMask == 0) {   // Not demanding any bits from V.
852     if (isa<UndefValue>(V))
853       return 0;
854     return UndefValue::get(VTy);
855   }
856   
857   if (Depth == 6)        // Limit search depth.
858     return 0;
859   
860   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
861   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
862
863   Instruction *I = dyn_cast<Instruction>(V);
864   if (!I) {
865     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
866     return 0;        // Only analyze instructions.
867   }
868
869   // If there are multiple uses of this value and we aren't at the root, then
870   // we can't do any simplifications of the operands, because DemandedMask
871   // only reflects the bits demanded by *one* of the users.
872   if (Depth != 0 && !I->hasOneUse()) {
873     // Despite the fact that we can't simplify this instruction in all User's
874     // context, we can at least compute the knownzero/knownone bits, and we can
875     // do simplifications that apply to *just* the one user if we know that
876     // this instruction has a simpler value in that context.
877     if (I->getOpcode() == Instruction::And) {
878       // If either the LHS or the RHS are Zero, the result is zero.
879       ComputeMaskedBits(I->getOperand(1), DemandedMask,
880                         RHSKnownZero, RHSKnownOne, Depth+1);
881       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
882                         LHSKnownZero, LHSKnownOne, Depth+1);
883       
884       // If all of the demanded bits are known 1 on one side, return the other.
885       // These bits cannot contribute to the result of the 'and' in this
886       // context.
887       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
888           (DemandedMask & ~LHSKnownZero))
889         return I->getOperand(0);
890       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
891           (DemandedMask & ~RHSKnownZero))
892         return I->getOperand(1);
893       
894       // If all of the demanded bits in the inputs are known zeros, return zero.
895       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
896         return Constant::getNullValue(VTy);
897       
898     } else if (I->getOpcode() == Instruction::Or) {
899       // We can simplify (X|Y) -> X or Y in the user's context if we know that
900       // only bits from X or Y are demanded.
901       
902       // If either the LHS or the RHS are One, the result is One.
903       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
904                         RHSKnownZero, RHSKnownOne, Depth+1);
905       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
906                         LHSKnownZero, LHSKnownOne, Depth+1);
907       
908       // If all of the demanded bits are known zero on one side, return the
909       // other.  These bits cannot contribute to the result of the 'or' in this
910       // context.
911       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
912           (DemandedMask & ~LHSKnownOne))
913         return I->getOperand(0);
914       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
915           (DemandedMask & ~RHSKnownOne))
916         return I->getOperand(1);
917       
918       // If all of the potentially set bits on one side are known to be set on
919       // the other side, just use the 'other' side.
920       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
921           (DemandedMask & (~RHSKnownZero)))
922         return I->getOperand(0);
923       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
924           (DemandedMask & (~LHSKnownZero)))
925         return I->getOperand(1);
926     }
927     
928     // Compute the KnownZero/KnownOne bits to simplify things downstream.
929     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
930     return 0;
931   }
932   
933   // If this is the root being simplified, allow it to have multiple uses,
934   // just set the DemandedMask to all bits so that we can try to simplify the
935   // operands.  This allows visitTruncInst (for example) to simplify the
936   // operand of a trunc without duplicating all the logic below.
937   if (Depth == 0 && !V->hasOneUse())
938     DemandedMask = APInt::getAllOnesValue(BitWidth);
939   
940   switch (I->getOpcode()) {
941   default:
942     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
943     break;
944   case Instruction::And:
945     // If either the LHS or the RHS are Zero, the result is zero.
946     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
947                              RHSKnownZero, RHSKnownOne, Depth+1) ||
948         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
949                              LHSKnownZero, LHSKnownOne, Depth+1))
950       return I;
951     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
952     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
953
954     // If all of the demanded bits are known 1 on one side, return the other.
955     // These bits cannot contribute to the result of the 'and'.
956     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
957         (DemandedMask & ~LHSKnownZero))
958       return I->getOperand(0);
959     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
960         (DemandedMask & ~RHSKnownZero))
961       return I->getOperand(1);
962     
963     // If all of the demanded bits in the inputs are known zeros, return zero.
964     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
965       return Constant::getNullValue(VTy);
966       
967     // If the RHS is a constant, see if we can simplify it.
968     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
969       return I;
970       
971     // Output known-1 bits are only known if set in both the LHS & RHS.
972     RHSKnownOne &= LHSKnownOne;
973     // Output known-0 are known to be clear if zero in either the LHS | RHS.
974     RHSKnownZero |= LHSKnownZero;
975     break;
976   case Instruction::Or:
977     // If either the LHS or the RHS are One, the result is One.
978     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
979                              RHSKnownZero, RHSKnownOne, Depth+1) ||
980         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
981                              LHSKnownZero, LHSKnownOne, Depth+1))
982       return I;
983     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
984     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
985     
986     // If all of the demanded bits are known zero on one side, return the other.
987     // These bits cannot contribute to the result of the 'or'.
988     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
989         (DemandedMask & ~LHSKnownOne))
990       return I->getOperand(0);
991     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
992         (DemandedMask & ~RHSKnownOne))
993       return I->getOperand(1);
994
995     // If all of the potentially set bits on one side are known to be set on
996     // the other side, just use the 'other' side.
997     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
998         (DemandedMask & (~RHSKnownZero)))
999       return I->getOperand(0);
1000     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
1001         (DemandedMask & (~LHSKnownZero)))
1002       return I->getOperand(1);
1003         
1004     // If the RHS is a constant, see if we can simplify it.
1005     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1006       return I;
1007           
1008     // Output known-0 bits are only known if clear in both the LHS & RHS.
1009     RHSKnownZero &= LHSKnownZero;
1010     // Output known-1 are known to be set if set in either the LHS | RHS.
1011     RHSKnownOne |= LHSKnownOne;
1012     break;
1013   case Instruction::Xor: {
1014     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1015                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1016         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1017                              LHSKnownZero, LHSKnownOne, Depth+1))
1018       return I;
1019     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1020     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1021     
1022     // If all of the demanded bits are known zero on one side, return the other.
1023     // These bits cannot contribute to the result of the 'xor'.
1024     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1025       return I->getOperand(0);
1026     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1027       return I->getOperand(1);
1028     
1029     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1030     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1031                          (RHSKnownOne & LHSKnownOne);
1032     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1033     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1034                         (RHSKnownOne & LHSKnownZero);
1035     
1036     // If all of the demanded bits are known to be zero on one side or the
1037     // other, turn this into an *inclusive* or.
1038     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1039     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1040       Instruction *Or = 
1041         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1042                                  I->getName());
1043       return InsertNewInstBefore(Or, *I);
1044     }
1045     
1046     // If all of the demanded bits on one side are known, and all of the set
1047     // bits on that side are also known to be set on the other side, turn this
1048     // into an AND, as we know the bits will be cleared.
1049     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1050     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1051       // all known
1052       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1053         Constant *AndC = Constant::getIntegerValue(VTy,
1054                                                    ~RHSKnownOne & DemandedMask);
1055         Instruction *And = 
1056           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1057         return InsertNewInstBefore(And, *I);
1058       }
1059     }
1060     
1061     // If the RHS is a constant, see if we can simplify it.
1062     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1063     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1064       return I;
1065     
1066     // If our LHS is an 'and' and if it has one use, and if any of the bits we
1067     // are flipping are known to be set, then the xor is just resetting those
1068     // bits to zero.  We can just knock out bits from the 'and' and the 'xor',
1069     // simplifying both of them.
1070     if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1071       if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1072           isa<ConstantInt>(I->getOperand(1)) &&
1073           isa<ConstantInt>(LHSInst->getOperand(1)) &&
1074           (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1075         ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1076         ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1077         APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1078         
1079         Constant *AndC =
1080           ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1081         Instruction *NewAnd = 
1082           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1083         InsertNewInstBefore(NewAnd, *I);
1084         
1085         Constant *XorC =
1086           ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1087         Instruction *NewXor =
1088           BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1089         return InsertNewInstBefore(NewXor, *I);
1090       }
1091           
1092           
1093     RHSKnownZero = KnownZeroOut;
1094     RHSKnownOne  = KnownOneOut;
1095     break;
1096   }
1097   case Instruction::Select:
1098     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1099                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1100         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1101                              LHSKnownZero, LHSKnownOne, Depth+1))
1102       return I;
1103     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1104     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1105     
1106     // If the operands are constants, see if we can simplify them.
1107     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1108         ShrinkDemandedConstant(I, 2, DemandedMask))
1109       return I;
1110     
1111     // Only known if known in both the LHS and RHS.
1112     RHSKnownOne &= LHSKnownOne;
1113     RHSKnownZero &= LHSKnownZero;
1114     break;
1115   case Instruction::Trunc: {
1116     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1117     DemandedMask.zext(truncBf);
1118     RHSKnownZero.zext(truncBf);
1119     RHSKnownOne.zext(truncBf);
1120     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1121                              RHSKnownZero, RHSKnownOne, Depth+1))
1122       return I;
1123     DemandedMask.trunc(BitWidth);
1124     RHSKnownZero.trunc(BitWidth);
1125     RHSKnownOne.trunc(BitWidth);
1126     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1127     break;
1128   }
1129   case Instruction::BitCast:
1130     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1131       return false;  // vector->int or fp->int?
1132
1133     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1134       if (const VectorType *SrcVTy =
1135             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1136         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1137           // Don't touch a bitcast between vectors of different element counts.
1138           return false;
1139       } else
1140         // Don't touch a scalar-to-vector bitcast.
1141         return false;
1142     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1143       // Don't touch a vector-to-scalar bitcast.
1144       return false;
1145
1146     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1147                              RHSKnownZero, RHSKnownOne, Depth+1))
1148       return I;
1149     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1150     break;
1151   case Instruction::ZExt: {
1152     // Compute the bits in the result that are not present in the input.
1153     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1154     
1155     DemandedMask.trunc(SrcBitWidth);
1156     RHSKnownZero.trunc(SrcBitWidth);
1157     RHSKnownOne.trunc(SrcBitWidth);
1158     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1159                              RHSKnownZero, RHSKnownOne, Depth+1))
1160       return I;
1161     DemandedMask.zext(BitWidth);
1162     RHSKnownZero.zext(BitWidth);
1163     RHSKnownOne.zext(BitWidth);
1164     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1165     // The top bits are known to be zero.
1166     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1167     break;
1168   }
1169   case Instruction::SExt: {
1170     // Compute the bits in the result that are not present in the input.
1171     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1172     
1173     APInt InputDemandedBits = DemandedMask & 
1174                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1175
1176     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1177     // If any of the sign extended bits are demanded, we know that the sign
1178     // bit is demanded.
1179     if ((NewBits & DemandedMask) != 0)
1180       InputDemandedBits.set(SrcBitWidth-1);
1181       
1182     InputDemandedBits.trunc(SrcBitWidth);
1183     RHSKnownZero.trunc(SrcBitWidth);
1184     RHSKnownOne.trunc(SrcBitWidth);
1185     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1186                              RHSKnownZero, RHSKnownOne, Depth+1))
1187       return I;
1188     InputDemandedBits.zext(BitWidth);
1189     RHSKnownZero.zext(BitWidth);
1190     RHSKnownOne.zext(BitWidth);
1191     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1192       
1193     // If the sign bit of the input is known set or clear, then we know the
1194     // top bits of the result.
1195
1196     // If the input sign bit is known zero, or if the NewBits are not demanded
1197     // convert this into a zero extension.
1198     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1199       // Convert to ZExt cast
1200       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1201       return InsertNewInstBefore(NewCast, *I);
1202     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1203       RHSKnownOne |= NewBits;
1204     }
1205     break;
1206   }
1207   case Instruction::Add: {
1208     // Figure out what the input bits are.  If the top bits of the and result
1209     // are not demanded, then the add doesn't demand them from its input
1210     // either.
1211     unsigned NLZ = DemandedMask.countLeadingZeros();
1212       
1213     // If there is a constant on the RHS, there are a variety of xformations
1214     // we can do.
1215     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1216       // If null, this should be simplified elsewhere.  Some of the xforms here
1217       // won't work if the RHS is zero.
1218       if (RHS->isZero())
1219         break;
1220       
1221       // If the top bit of the output is demanded, demand everything from the
1222       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1223       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1224
1225       // Find information about known zero/one bits in the input.
1226       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1227                                LHSKnownZero, LHSKnownOne, Depth+1))
1228         return I;
1229
1230       // If the RHS of the add has bits set that can't affect the input, reduce
1231       // the constant.
1232       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1233         return I;
1234       
1235       // Avoid excess work.
1236       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1237         break;
1238       
1239       // Turn it into OR if input bits are zero.
1240       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1241         Instruction *Or =
1242           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1243                                    I->getName());
1244         return InsertNewInstBefore(Or, *I);
1245       }
1246       
1247       // We can say something about the output known-zero and known-one bits,
1248       // depending on potential carries from the input constant and the
1249       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1250       // bits set and the RHS constant is 0x01001, then we know we have a known
1251       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1252       
1253       // To compute this, we first compute the potential carry bits.  These are
1254       // the bits which may be modified.  I'm not aware of a better way to do
1255       // this scan.
1256       const APInt &RHSVal = RHS->getValue();
1257       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1258       
1259       // Now that we know which bits have carries, compute the known-1/0 sets.
1260       
1261       // Bits are known one if they are known zero in one operand and one in the
1262       // other, and there is no input carry.
1263       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1264                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1265       
1266       // Bits are known zero if they are known zero in both operands and there
1267       // is no input carry.
1268       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1269     } else {
1270       // If the high-bits of this ADD are not demanded, then it does not demand
1271       // the high bits of its LHS or RHS.
1272       if (DemandedMask[BitWidth-1] == 0) {
1273         // Right fill the mask of bits for this ADD to demand the most
1274         // significant bit and all those below it.
1275         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1276         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1277                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1278             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1279                                  LHSKnownZero, LHSKnownOne, Depth+1))
1280           return I;
1281       }
1282     }
1283     break;
1284   }
1285   case Instruction::Sub:
1286     // If the high-bits of this SUB are not demanded, then it does not demand
1287     // the high bits of its LHS or RHS.
1288     if (DemandedMask[BitWidth-1] == 0) {
1289       // Right fill the mask of bits for this SUB to demand the most
1290       // significant bit and all those below it.
1291       uint32_t NLZ = DemandedMask.countLeadingZeros();
1292       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1293       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1294                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1295           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1296                                LHSKnownZero, LHSKnownOne, Depth+1))
1297         return I;
1298     }
1299     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1300     // the known zeros and ones.
1301     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1302     break;
1303   case Instruction::Shl:
1304     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1305       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1306       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1307       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1308                                RHSKnownZero, RHSKnownOne, Depth+1))
1309         return I;
1310       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1311       RHSKnownZero <<= ShiftAmt;
1312       RHSKnownOne  <<= ShiftAmt;
1313       // low bits known zero.
1314       if (ShiftAmt)
1315         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1316     }
1317     break;
1318   case Instruction::LShr:
1319     // For a logical shift right
1320     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1321       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1322       
1323       // Unsigned shift right.
1324       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1325       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1326                                RHSKnownZero, RHSKnownOne, Depth+1))
1327         return I;
1328       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1329       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1330       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1331       if (ShiftAmt) {
1332         // Compute the new bits that are at the top now.
1333         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1334         RHSKnownZero |= HighBits;  // high bits known zero.
1335       }
1336     }
1337     break;
1338   case Instruction::AShr:
1339     // If this is an arithmetic shift right and only the low-bit is set, we can
1340     // always convert this into a logical shr, even if the shift amount is
1341     // variable.  The low bit of the shift cannot be an input sign bit unless
1342     // the shift amount is >= the size of the datatype, which is undefined.
1343     if (DemandedMask == 1) {
1344       // Perform the logical shift right.
1345       Instruction *NewVal = BinaryOperator::CreateLShr(
1346                         I->getOperand(0), I->getOperand(1), I->getName());
1347       return InsertNewInstBefore(NewVal, *I);
1348     }    
1349
1350     // If the sign bit is the only bit demanded by this ashr, then there is no
1351     // need to do it, the shift doesn't change the high bit.
1352     if (DemandedMask.isSignBit())
1353       return I->getOperand(0);
1354     
1355     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1356       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1357       
1358       // Signed shift right.
1359       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1360       // If any of the "high bits" are demanded, we should set the sign bit as
1361       // demanded.
1362       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1363         DemandedMaskIn.set(BitWidth-1);
1364       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1365                                RHSKnownZero, RHSKnownOne, Depth+1))
1366         return I;
1367       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1368       // Compute the new bits that are at the top now.
1369       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1370       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1371       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1372         
1373       // Handle the sign bits.
1374       APInt SignBit(APInt::getSignBit(BitWidth));
1375       // Adjust to where it is now in the mask.
1376       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1377         
1378       // If the input sign bit is known to be zero, or if none of the top bits
1379       // are demanded, turn this into an unsigned shift right.
1380       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1381           (HighBits & ~DemandedMask) == HighBits) {
1382         // Perform the logical shift right.
1383         Instruction *NewVal = BinaryOperator::CreateLShr(
1384                           I->getOperand(0), SA, I->getName());
1385         return InsertNewInstBefore(NewVal, *I);
1386       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1387         RHSKnownOne |= HighBits;
1388       }
1389     }
1390     break;
1391   case Instruction::SRem:
1392     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1393       APInt RA = Rem->getValue().abs();
1394       if (RA.isPowerOf2()) {
1395         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1396           return I->getOperand(0);
1397
1398         APInt LowBits = RA - 1;
1399         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1400         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1401                                  LHSKnownZero, LHSKnownOne, Depth+1))
1402           return I;
1403
1404         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1405           LHSKnownZero |= ~LowBits;
1406
1407         KnownZero |= LHSKnownZero & DemandedMask;
1408
1409         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1410       }
1411     }
1412     break;
1413   case Instruction::URem: {
1414     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1415     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1416     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1417                              KnownZero2, KnownOne2, Depth+1) ||
1418         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1419                              KnownZero2, KnownOne2, Depth+1))
1420       return I;
1421
1422     unsigned Leaders = KnownZero2.countLeadingOnes();
1423     Leaders = std::max(Leaders,
1424                        KnownZero2.countLeadingOnes());
1425     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1426     break;
1427   }
1428   case Instruction::Call:
1429     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1430       switch (II->getIntrinsicID()) {
1431       default: break;
1432       case Intrinsic::bswap: {
1433         // If the only bits demanded come from one byte of the bswap result,
1434         // just shift the input byte into position to eliminate the bswap.
1435         unsigned NLZ = DemandedMask.countLeadingZeros();
1436         unsigned NTZ = DemandedMask.countTrailingZeros();
1437           
1438         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1439         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1440         // have 14 leading zeros, round to 8.
1441         NLZ &= ~7;
1442         NTZ &= ~7;
1443         // If we need exactly one byte, we can do this transformation.
1444         if (BitWidth-NLZ-NTZ == 8) {
1445           unsigned ResultBit = NTZ;
1446           unsigned InputBit = BitWidth-NTZ-8;
1447           
1448           // Replace this with either a left or right shift to get the byte into
1449           // the right place.
1450           Instruction *NewVal;
1451           if (InputBit > ResultBit)
1452             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1453                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1454           else
1455             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1456                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1457           NewVal->takeName(I);
1458           return InsertNewInstBefore(NewVal, *I);
1459         }
1460           
1461         // TODO: Could compute known zero/one bits based on the input.
1462         break;
1463       }
1464       }
1465     }
1466     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1467     break;
1468   }
1469   
1470   // If the client is only demanding bits that we know, return the known
1471   // constant.
1472   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1473     return Constant::getIntegerValue(VTy, RHSKnownOne);
1474   return false;
1475 }
1476
1477
1478 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1479 /// any number of elements. DemandedElts contains the set of elements that are
1480 /// actually used by the caller.  This method analyzes which elements of the
1481 /// operand are undef and returns that information in UndefElts.
1482 ///
1483 /// If the information about demanded elements can be used to simplify the
1484 /// operation, the operation is simplified, then the resultant value is
1485 /// returned.  This returns null if no change was made.
1486 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1487                                                 APInt& UndefElts,
1488                                                 unsigned Depth) {
1489   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1490   APInt EltMask(APInt::getAllOnesValue(VWidth));
1491   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1492
1493   if (isa<UndefValue>(V)) {
1494     // If the entire vector is undefined, just return this info.
1495     UndefElts = EltMask;
1496     return 0;
1497   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1498     UndefElts = EltMask;
1499     return UndefValue::get(V->getType());
1500   }
1501
1502   UndefElts = 0;
1503   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1504     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1505     Constant *Undef = UndefValue::get(EltTy);
1506
1507     std::vector<Constant*> Elts;
1508     for (unsigned i = 0; i != VWidth; ++i)
1509       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1510         Elts.push_back(Undef);
1511         UndefElts.set(i);
1512       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1513         Elts.push_back(Undef);
1514         UndefElts.set(i);
1515       } else {                               // Otherwise, defined.
1516         Elts.push_back(CP->getOperand(i));
1517       }
1518
1519     // If we changed the constant, return it.
1520     Constant *NewCP = ConstantVector::get(Elts);
1521     return NewCP != CP ? NewCP : 0;
1522   } else if (isa<ConstantAggregateZero>(V)) {
1523     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1524     // set to undef.
1525     
1526     // Check if this is identity. If so, return 0 since we are not simplifying
1527     // anything.
1528     if (DemandedElts == ((1ULL << VWidth) -1))
1529       return 0;
1530     
1531     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1532     Constant *Zero = Constant::getNullValue(EltTy);
1533     Constant *Undef = UndefValue::get(EltTy);
1534     std::vector<Constant*> Elts;
1535     for (unsigned i = 0; i != VWidth; ++i) {
1536       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1537       Elts.push_back(Elt);
1538     }
1539     UndefElts = DemandedElts ^ EltMask;
1540     return ConstantVector::get(Elts);
1541   }
1542   
1543   // Limit search depth.
1544   if (Depth == 10)
1545     return 0;
1546
1547   // If multiple users are using the root value, procede with
1548   // simplification conservatively assuming that all elements
1549   // are needed.
1550   if (!V->hasOneUse()) {
1551     // Quit if we find multiple users of a non-root value though.
1552     // They'll be handled when it's their turn to be visited by
1553     // the main instcombine process.
1554     if (Depth != 0)
1555       // TODO: Just compute the UndefElts information recursively.
1556       return 0;
1557
1558     // Conservatively assume that all elements are needed.
1559     DemandedElts = EltMask;
1560   }
1561   
1562   Instruction *I = dyn_cast<Instruction>(V);
1563   if (!I) return 0;        // Only analyze instructions.
1564   
1565   bool MadeChange = false;
1566   APInt UndefElts2(VWidth, 0);
1567   Value *TmpV;
1568   switch (I->getOpcode()) {
1569   default: break;
1570     
1571   case Instruction::InsertElement: {
1572     // If this is a variable index, we don't know which element it overwrites.
1573     // demand exactly the same input as we produce.
1574     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1575     if (Idx == 0) {
1576       // Note that we can't propagate undef elt info, because we don't know
1577       // which elt is getting updated.
1578       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1579                                         UndefElts2, Depth+1);
1580       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1581       break;
1582     }
1583     
1584     // If this is inserting an element that isn't demanded, remove this
1585     // insertelement.
1586     unsigned IdxNo = Idx->getZExtValue();
1587     if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1588       Worklist.Add(I);
1589       return I->getOperand(0);
1590     }
1591     
1592     // Otherwise, the element inserted overwrites whatever was there, so the
1593     // input demanded set is simpler than the output set.
1594     APInt DemandedElts2 = DemandedElts;
1595     DemandedElts2.clear(IdxNo);
1596     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1597                                       UndefElts, Depth+1);
1598     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1599
1600     // The inserted element is defined.
1601     UndefElts.clear(IdxNo);
1602     break;
1603   }
1604   case Instruction::ShuffleVector: {
1605     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1606     uint64_t LHSVWidth =
1607       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1608     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1609     for (unsigned i = 0; i < VWidth; i++) {
1610       if (DemandedElts[i]) {
1611         unsigned MaskVal = Shuffle->getMaskValue(i);
1612         if (MaskVal != -1u) {
1613           assert(MaskVal < LHSVWidth * 2 &&
1614                  "shufflevector mask index out of range!");
1615           if (MaskVal < LHSVWidth)
1616             LeftDemanded.set(MaskVal);
1617           else
1618             RightDemanded.set(MaskVal - LHSVWidth);
1619         }
1620       }
1621     }
1622
1623     APInt UndefElts4(LHSVWidth, 0);
1624     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1625                                       UndefElts4, Depth+1);
1626     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1627
1628     APInt UndefElts3(LHSVWidth, 0);
1629     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1630                                       UndefElts3, Depth+1);
1631     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1632
1633     bool NewUndefElts = false;
1634     for (unsigned i = 0; i < VWidth; i++) {
1635       unsigned MaskVal = Shuffle->getMaskValue(i);
1636       if (MaskVal == -1u) {
1637         UndefElts.set(i);
1638       } else if (MaskVal < LHSVWidth) {
1639         if (UndefElts4[MaskVal]) {
1640           NewUndefElts = true;
1641           UndefElts.set(i);
1642         }
1643       } else {
1644         if (UndefElts3[MaskVal - LHSVWidth]) {
1645           NewUndefElts = true;
1646           UndefElts.set(i);
1647         }
1648       }
1649     }
1650
1651     if (NewUndefElts) {
1652       // Add additional discovered undefs.
1653       std::vector<Constant*> Elts;
1654       for (unsigned i = 0; i < VWidth; ++i) {
1655         if (UndefElts[i])
1656           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
1657         else
1658           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
1659                                           Shuffle->getMaskValue(i)));
1660       }
1661       I->setOperand(2, ConstantVector::get(Elts));
1662       MadeChange = true;
1663     }
1664     break;
1665   }
1666   case Instruction::BitCast: {
1667     // Vector->vector casts only.
1668     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1669     if (!VTy) break;
1670     unsigned InVWidth = VTy->getNumElements();
1671     APInt InputDemandedElts(InVWidth, 0);
1672     unsigned Ratio;
1673
1674     if (VWidth == InVWidth) {
1675       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1676       // elements as are demanded of us.
1677       Ratio = 1;
1678       InputDemandedElts = DemandedElts;
1679     } else if (VWidth > InVWidth) {
1680       // Untested so far.
1681       break;
1682       
1683       // If there are more elements in the result than there are in the source,
1684       // then an input element is live if any of the corresponding output
1685       // elements are live.
1686       Ratio = VWidth/InVWidth;
1687       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1688         if (DemandedElts[OutIdx])
1689           InputDemandedElts.set(OutIdx/Ratio);
1690       }
1691     } else {
1692       // Untested so far.
1693       break;
1694       
1695       // If there are more elements in the source than there are in the result,
1696       // then an input element is live if the corresponding output element is
1697       // live.
1698       Ratio = InVWidth/VWidth;
1699       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1700         if (DemandedElts[InIdx/Ratio])
1701           InputDemandedElts.set(InIdx);
1702     }
1703     
1704     // div/rem demand all inputs, because they don't want divide by zero.
1705     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1706                                       UndefElts2, Depth+1);
1707     if (TmpV) {
1708       I->setOperand(0, TmpV);
1709       MadeChange = true;
1710     }
1711     
1712     UndefElts = UndefElts2;
1713     if (VWidth > InVWidth) {
1714       llvm_unreachable("Unimp");
1715       // If there are more elements in the result than there are in the source,
1716       // then an output element is undef if the corresponding input element is
1717       // undef.
1718       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1719         if (UndefElts2[OutIdx/Ratio])
1720           UndefElts.set(OutIdx);
1721     } else if (VWidth < InVWidth) {
1722       llvm_unreachable("Unimp");
1723       // If there are more elements in the source than there are in the result,
1724       // then a result element is undef if all of the corresponding input
1725       // elements are undef.
1726       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1727       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1728         if (!UndefElts2[InIdx])            // Not undef?
1729           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1730     }
1731     break;
1732   }
1733   case Instruction::And:
1734   case Instruction::Or:
1735   case Instruction::Xor:
1736   case Instruction::Add:
1737   case Instruction::Sub:
1738   case Instruction::Mul:
1739     // div/rem demand all inputs, because they don't want divide by zero.
1740     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1741                                       UndefElts, Depth+1);
1742     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1743     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1744                                       UndefElts2, Depth+1);
1745     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1746       
1747     // Output elements are undefined if both are undefined.  Consider things
1748     // like undef&0.  The result is known zero, not undef.
1749     UndefElts &= UndefElts2;
1750     break;
1751     
1752   case Instruction::Call: {
1753     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1754     if (!II) break;
1755     switch (II->getIntrinsicID()) {
1756     default: break;
1757       
1758     // Binary vector operations that work column-wise.  A dest element is a
1759     // function of the corresponding input elements from the two inputs.
1760     case Intrinsic::x86_sse_sub_ss:
1761     case Intrinsic::x86_sse_mul_ss:
1762     case Intrinsic::x86_sse_min_ss:
1763     case Intrinsic::x86_sse_max_ss:
1764     case Intrinsic::x86_sse2_sub_sd:
1765     case Intrinsic::x86_sse2_mul_sd:
1766     case Intrinsic::x86_sse2_min_sd:
1767     case Intrinsic::x86_sse2_max_sd:
1768       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1769                                         UndefElts, Depth+1);
1770       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1771       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1772                                         UndefElts2, Depth+1);
1773       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1774
1775       // If only the low elt is demanded and this is a scalarizable intrinsic,
1776       // scalarize it now.
1777       if (DemandedElts == 1) {
1778         switch (II->getIntrinsicID()) {
1779         default: break;
1780         case Intrinsic::x86_sse_sub_ss:
1781         case Intrinsic::x86_sse_mul_ss:
1782         case Intrinsic::x86_sse2_sub_sd:
1783         case Intrinsic::x86_sse2_mul_sd:
1784           // TODO: Lower MIN/MAX/ABS/etc
1785           Value *LHS = II->getOperand(1);
1786           Value *RHS = II->getOperand(2);
1787           // Extract the element as scalars.
1788           LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS, 
1789             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1790           RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1791             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1792           
1793           switch (II->getIntrinsicID()) {
1794           default: llvm_unreachable("Case stmts out of sync!");
1795           case Intrinsic::x86_sse_sub_ss:
1796           case Intrinsic::x86_sse2_sub_sd:
1797             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1798                                                         II->getName()), *II);
1799             break;
1800           case Intrinsic::x86_sse_mul_ss:
1801           case Intrinsic::x86_sse2_mul_sd:
1802             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1803                                                          II->getName()), *II);
1804             break;
1805           }
1806           
1807           Instruction *New =
1808             InsertElementInst::Create(
1809               UndefValue::get(II->getType()), TmpV,
1810               ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
1811           InsertNewInstBefore(New, *II);
1812           return New;
1813         }            
1814       }
1815         
1816       // Output elements are undefined if both are undefined.  Consider things
1817       // like undef&0.  The result is known zero, not undef.
1818       UndefElts &= UndefElts2;
1819       break;
1820     }
1821     break;
1822   }
1823   }
1824   return MadeChange ? I : 0;
1825 }
1826
1827
1828 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1829 /// function is designed to check a chain of associative operators for a
1830 /// potential to apply a certain optimization.  Since the optimization may be
1831 /// applicable if the expression was reassociated, this checks the chain, then
1832 /// reassociates the expression as necessary to expose the optimization
1833 /// opportunity.  This makes use of a special Functor, which must define
1834 /// 'shouldApply' and 'apply' methods.
1835 ///
1836 template<typename Functor>
1837 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1838   unsigned Opcode = Root.getOpcode();
1839   Value *LHS = Root.getOperand(0);
1840
1841   // Quick check, see if the immediate LHS matches...
1842   if (F.shouldApply(LHS))
1843     return F.apply(Root);
1844
1845   // Otherwise, if the LHS is not of the same opcode as the root, return.
1846   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1847   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1848     // Should we apply this transform to the RHS?
1849     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1850
1851     // If not to the RHS, check to see if we should apply to the LHS...
1852     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1853       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1854       ShouldApply = true;
1855     }
1856
1857     // If the functor wants to apply the optimization to the RHS of LHSI,
1858     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1859     if (ShouldApply) {
1860       // Now all of the instructions are in the current basic block, go ahead
1861       // and perform the reassociation.
1862       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1863
1864       // First move the selected RHS to the LHS of the root...
1865       Root.setOperand(0, LHSI->getOperand(1));
1866
1867       // Make what used to be the LHS of the root be the user of the root...
1868       Value *ExtraOperand = TmpLHSI->getOperand(1);
1869       if (&Root == TmpLHSI) {
1870         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1871         return 0;
1872       }
1873       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1874       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1875       BasicBlock::iterator ARI = &Root; ++ARI;
1876       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1877       ARI = Root;
1878
1879       // Now propagate the ExtraOperand down the chain of instructions until we
1880       // get to LHSI.
1881       while (TmpLHSI != LHSI) {
1882         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1883         // Move the instruction to immediately before the chain we are
1884         // constructing to avoid breaking dominance properties.
1885         NextLHSI->moveBefore(ARI);
1886         ARI = NextLHSI;
1887
1888         Value *NextOp = NextLHSI->getOperand(1);
1889         NextLHSI->setOperand(1, ExtraOperand);
1890         TmpLHSI = NextLHSI;
1891         ExtraOperand = NextOp;
1892       }
1893
1894       // Now that the instructions are reassociated, have the functor perform
1895       // the transformation...
1896       return F.apply(Root);
1897     }
1898
1899     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1900   }
1901   return 0;
1902 }
1903
1904 namespace {
1905
1906 // AddRHS - Implements: X + X --> X << 1
1907 struct AddRHS {
1908   Value *RHS;
1909   explicit AddRHS(Value *rhs) : RHS(rhs) {}
1910   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1911   Instruction *apply(BinaryOperator &Add) const {
1912     return BinaryOperator::CreateShl(Add.getOperand(0),
1913                                      ConstantInt::get(Add.getType(), 1));
1914   }
1915 };
1916
1917 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1918 //                 iff C1&C2 == 0
1919 struct AddMaskingAnd {
1920   Constant *C2;
1921   explicit AddMaskingAnd(Constant *c) : C2(c) {}
1922   bool shouldApply(Value *LHS) const {
1923     ConstantInt *C1;
1924     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1925            ConstantExpr::getAnd(C1, C2)->isNullValue();
1926   }
1927   Instruction *apply(BinaryOperator &Add) const {
1928     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1929   }
1930 };
1931
1932 }
1933
1934 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1935                                              InstCombiner *IC) {
1936   if (CastInst *CI = dyn_cast<CastInst>(&I))
1937     return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
1938
1939   // Figure out if the constant is the left or the right argument.
1940   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1941   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1942
1943   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1944     if (ConstIsRHS)
1945       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1946     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1947   }
1948
1949   Value *Op0 = SO, *Op1 = ConstOperand;
1950   if (!ConstIsRHS)
1951     std::swap(Op0, Op1);
1952   
1953   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1954     return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1955                                     SO->getName()+".op");
1956   if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1957     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1958                                    SO->getName()+".cmp");
1959   if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1960     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1961                                    SO->getName()+".cmp");
1962   llvm_unreachable("Unknown binary instruction type!");
1963 }
1964
1965 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1966 // constant as the other operand, try to fold the binary operator into the
1967 // select arguments.  This also works for Cast instructions, which obviously do
1968 // not have a second operand.
1969 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1970                                      InstCombiner *IC) {
1971   // Don't modify shared select instructions
1972   if (!SI->hasOneUse()) return 0;
1973   Value *TV = SI->getOperand(1);
1974   Value *FV = SI->getOperand(2);
1975
1976   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1977     // Bool selects with constant operands can be folded to logical ops.
1978     if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
1979
1980     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1981     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1982
1983     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1984                               SelectFalseVal);
1985   }
1986   return 0;
1987 }
1988
1989
1990 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
1991 /// has a PHI node as operand #0, see if we can fold the instruction into the
1992 /// PHI (which is only possible if all operands to the PHI are constants).
1993 ///
1994 /// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
1995 /// that would normally be unprofitable because they strongly encourage jump
1996 /// threading.
1997 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
1998                                          bool AllowAggressive) {
1999   AllowAggressive = false;
2000   PHINode *PN = cast<PHINode>(I.getOperand(0));
2001   unsigned NumPHIValues = PN->getNumIncomingValues();
2002   if (NumPHIValues == 0 ||
2003       // We normally only transform phis with a single use, unless we're trying
2004       // hard to make jump threading happen.
2005       (!PN->hasOneUse() && !AllowAggressive))
2006     return 0;
2007   
2008   
2009   // Check to see if all of the operands of the PHI are simple constants
2010   // (constantint/constantfp/undef).  If there is one non-constant value,
2011   // remember the BB it is in.  If there is more than one or if *it* is a PHI,
2012   // bail out.  We don't do arbitrary constant expressions here because moving
2013   // their computation can be expensive without a cost model.
2014   BasicBlock *NonConstBB = 0;
2015   for (unsigned i = 0; i != NumPHIValues; ++i)
2016     if (!isa<Constant>(PN->getIncomingValue(i)) ||
2017         isa<ConstantExpr>(PN->getIncomingValue(i))) {
2018       if (NonConstBB) return 0;  // More than one non-const value.
2019       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
2020       NonConstBB = PN->getIncomingBlock(i);
2021       
2022       // If the incoming non-constant value is in I's block, we have an infinite
2023       // loop.
2024       if (NonConstBB == I.getParent())
2025         return 0;
2026     }
2027   
2028   // If there is exactly one non-constant value, we can insert a copy of the
2029   // operation in that block.  However, if this is a critical edge, we would be
2030   // inserting the computation one some other paths (e.g. inside a loop).  Only
2031   // do this if the pred block is unconditionally branching into the phi block.
2032   if (NonConstBB != 0 && !AllowAggressive) {
2033     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2034     if (!BI || !BI->isUnconditional()) return 0;
2035   }
2036
2037   // Okay, we can do the transformation: create the new PHI node.
2038   PHINode *NewPN = PHINode::Create(I.getType(), "");
2039   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2040   InsertNewInstBefore(NewPN, *PN);
2041   NewPN->takeName(PN);
2042
2043   // Next, add all of the operands to the PHI.
2044   if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2045     // We only currently try to fold the condition of a select when it is a phi,
2046     // not the true/false values.
2047     Value *TrueV = SI->getTrueValue();
2048     Value *FalseV = SI->getFalseValue();
2049     BasicBlock *PhiTransBB = PN->getParent();
2050     for (unsigned i = 0; i != NumPHIValues; ++i) {
2051       BasicBlock *ThisBB = PN->getIncomingBlock(i);
2052       Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2053       Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
2054       Value *InV = 0;
2055       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2056         InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
2057       } else {
2058         assert(PN->getIncomingBlock(i) == NonConstBB);
2059         InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2060                                  FalseVInPred,
2061                                  "phitmp", NonConstBB->getTerminator());
2062         Worklist.Add(cast<Instruction>(InV));
2063       }
2064       NewPN->addIncoming(InV, ThisBB);
2065     }
2066   } else if (I.getNumOperands() == 2) {
2067     Constant *C = cast<Constant>(I.getOperand(1));
2068     for (unsigned i = 0; i != NumPHIValues; ++i) {
2069       Value *InV = 0;
2070       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2071         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2072           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2073         else
2074           InV = ConstantExpr::get(I.getOpcode(), InC, C);
2075       } else {
2076         assert(PN->getIncomingBlock(i) == NonConstBB);
2077         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
2078           InV = BinaryOperator::Create(BO->getOpcode(),
2079                                        PN->getIncomingValue(i), C, "phitmp",
2080                                        NonConstBB->getTerminator());
2081         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2082           InV = CmpInst::Create(CI->getOpcode(),
2083                                 CI->getPredicate(),
2084                                 PN->getIncomingValue(i), C, "phitmp",
2085                                 NonConstBB->getTerminator());
2086         else
2087           llvm_unreachable("Unknown binop!");
2088         
2089         Worklist.Add(cast<Instruction>(InV));
2090       }
2091       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2092     }
2093   } else { 
2094     CastInst *CI = cast<CastInst>(&I);
2095     const Type *RetTy = CI->getType();
2096     for (unsigned i = 0; i != NumPHIValues; ++i) {
2097       Value *InV;
2098       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2099         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2100       } else {
2101         assert(PN->getIncomingBlock(i) == NonConstBB);
2102         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2103                                I.getType(), "phitmp", 
2104                                NonConstBB->getTerminator());
2105         Worklist.Add(cast<Instruction>(InV));
2106       }
2107       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2108     }
2109   }
2110   return ReplaceInstUsesWith(I, NewPN);
2111 }
2112
2113
2114 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2115 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2116 /// This basically requires proving that the add in the original type would not
2117 /// overflow to change the sign bit or have a carry out.
2118 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2119   // There are different heuristics we can use for this.  Here are some simple
2120   // ones.
2121   
2122   // Add has the property that adding any two 2's complement numbers can only 
2123   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2124   // have at least two sign bits, we know that the addition of the two values will
2125   // sign extend fine.
2126   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2127     return true;
2128   
2129   
2130   // If one of the operands only has one non-zero bit, and if the other operand
2131   // has a known-zero bit in a more significant place than it (not including the
2132   // sign bit) the ripple may go up to and fill the zero, but won't change the
2133   // sign.  For example, (X & ~4) + 1.
2134   
2135   // TODO: Implement.
2136   
2137   return false;
2138 }
2139
2140
2141 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2142   bool Changed = SimplifyCommutative(I);
2143   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2144
2145   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2146     // X + undef -> undef
2147     if (isa<UndefValue>(RHS))
2148       return ReplaceInstUsesWith(I, RHS);
2149
2150     // X + 0 --> X
2151     if (RHSC->isNullValue())
2152       return ReplaceInstUsesWith(I, LHS);
2153
2154     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2155       // X + (signbit) --> X ^ signbit
2156       const APInt& Val = CI->getValue();
2157       uint32_t BitWidth = Val.getBitWidth();
2158       if (Val == APInt::getSignBit(BitWidth))
2159         return BinaryOperator::CreateXor(LHS, RHS);
2160       
2161       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2162       // (X & 254)+1 -> (X&254)|1
2163       if (SimplifyDemandedInstructionBits(I))
2164         return &I;
2165
2166       // zext(bool) + C -> bool ? C + 1 : C
2167       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2168         if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2169           return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
2170     }
2171
2172     if (isa<PHINode>(LHS))
2173       if (Instruction *NV = FoldOpIntoPhi(I))
2174         return NV;
2175     
2176     ConstantInt *XorRHS = 0;
2177     Value *XorLHS = 0;
2178     if (isa<ConstantInt>(RHSC) &&
2179         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2180       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2181       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2182       
2183       uint32_t Size = TySizeBits / 2;
2184       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2185       APInt CFF80Val(-C0080Val);
2186       do {
2187         if (TySizeBits > Size) {
2188           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2189           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2190           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2191               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2192             // This is a sign extend if the top bits are known zero.
2193             if (!MaskedValueIsZero(XorLHS, 
2194                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2195               Size = 0;  // Not a sign ext, but can't be any others either.
2196             break;
2197           }
2198         }
2199         Size >>= 1;
2200         C0080Val = APIntOps::lshr(C0080Val, Size);
2201         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2202       } while (Size >= 1);
2203       
2204       // FIXME: This shouldn't be necessary. When the backends can handle types
2205       // with funny bit widths then this switch statement should be removed. It
2206       // is just here to get the size of the "middle" type back up to something
2207       // that the back ends can handle.
2208       const Type *MiddleType = 0;
2209       switch (Size) {
2210         default: break;
2211         case 32: MiddleType = Type::getInt32Ty(*Context); break;
2212         case 16: MiddleType = Type::getInt16Ty(*Context); break;
2213         case  8: MiddleType = Type::getInt8Ty(*Context); break;
2214       }
2215       if (MiddleType) {
2216         Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
2217         return new SExtInst(NewTrunc, I.getType(), I.getName());
2218       }
2219     }
2220   }
2221
2222   if (I.getType() == Type::getInt1Ty(*Context))
2223     return BinaryOperator::CreateXor(LHS, RHS);
2224
2225   // X + X --> X << 1
2226   if (I.getType()->isInteger()) {
2227     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
2228       return Result;
2229
2230     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2231       if (RHSI->getOpcode() == Instruction::Sub)
2232         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2233           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2234     }
2235     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2236       if (LHSI->getOpcode() == Instruction::Sub)
2237         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2238           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2239     }
2240   }
2241
2242   // -A + B  -->  B - A
2243   // -A + -B  -->  -(A + B)
2244   if (Value *LHSV = dyn_castNegVal(LHS)) {
2245     if (LHS->getType()->isIntOrIntVector()) {
2246       if (Value *RHSV = dyn_castNegVal(RHS)) {
2247         Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
2248         return BinaryOperator::CreateNeg(NewAdd);
2249       }
2250     }
2251     
2252     return BinaryOperator::CreateSub(RHS, LHSV);
2253   }
2254
2255   // A + -B  -->  A - B
2256   if (!isa<Constant>(RHS))
2257     if (Value *V = dyn_castNegVal(RHS))
2258       return BinaryOperator::CreateSub(LHS, V);
2259
2260
2261   ConstantInt *C2;
2262   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2263     if (X == RHS)   // X*C + X --> X * (C+1)
2264       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2265
2266     // X*C1 + X*C2 --> X * (C1+C2)
2267     ConstantInt *C1;
2268     if (X == dyn_castFoldableMul(RHS, C1))
2269       return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2270   }
2271
2272   // X + X*C --> X * (C+1)
2273   if (dyn_castFoldableMul(RHS, C2) == LHS)
2274     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2275
2276   // X + ~X --> -1   since   ~X = -X-1
2277   if (dyn_castNotVal(LHS) == RHS ||
2278       dyn_castNotVal(RHS) == LHS)
2279     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2280   
2281
2282   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2283   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2284     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2285       return R;
2286   
2287   // A+B --> A|B iff A and B have no bits set in common.
2288   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2289     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2290     APInt LHSKnownOne(IT->getBitWidth(), 0);
2291     APInt LHSKnownZero(IT->getBitWidth(), 0);
2292     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2293     if (LHSKnownZero != 0) {
2294       APInt RHSKnownOne(IT->getBitWidth(), 0);
2295       APInt RHSKnownZero(IT->getBitWidth(), 0);
2296       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2297       
2298       // No bits in common -> bitwise or.
2299       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2300         return BinaryOperator::CreateOr(LHS, RHS);
2301     }
2302   }
2303
2304   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2305   if (I.getType()->isIntOrIntVector()) {
2306     Value *W, *X, *Y, *Z;
2307     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2308         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2309       if (W != Y) {
2310         if (W == Z) {
2311           std::swap(Y, Z);
2312         } else if (Y == X) {
2313           std::swap(W, X);
2314         } else if (X == Z) {
2315           std::swap(Y, Z);
2316           std::swap(W, X);
2317         }
2318       }
2319
2320       if (W == Y) {
2321         Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
2322         return BinaryOperator::CreateMul(W, NewAdd);
2323       }
2324     }
2325   }
2326
2327   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2328     Value *X = 0;
2329     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2330       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2331
2332     // (X & FF00) + xx00  -> (X+xx00) & FF00
2333     if (LHS->hasOneUse() &&
2334         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2335       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2336       if (Anded == CRHS) {
2337         // See if all bits from the first bit set in the Add RHS up are included
2338         // in the mask.  First, get the rightmost bit.
2339         const APInt& AddRHSV = CRHS->getValue();
2340
2341         // Form a mask of all bits from the lowest bit added through the top.
2342         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2343
2344         // See if the and mask includes all of these bits.
2345         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2346
2347         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2348           // Okay, the xform is safe.  Insert the new add pronto.
2349           Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
2350           return BinaryOperator::CreateAnd(NewAdd, C2);
2351         }
2352       }
2353     }
2354
2355     // Try to fold constant add into select arguments.
2356     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2357       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2358         return R;
2359   }
2360
2361   // add (select X 0 (sub n A)) A  -->  select X A n
2362   {
2363     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2364     Value *A = RHS;
2365     if (!SI) {
2366       SI = dyn_cast<SelectInst>(RHS);
2367       A = LHS;
2368     }
2369     if (SI && SI->hasOneUse()) {
2370       Value *TV = SI->getTrueValue();
2371       Value *FV = SI->getFalseValue();
2372       Value *N;
2373
2374       // Can we fold the add into the argument of the select?
2375       // We check both true and false select arguments for a matching subtract.
2376       if (match(FV, m_Zero()) &&
2377           match(TV, m_Sub(m_Value(N), m_Specific(A))))
2378         // Fold the add into the true select value.
2379         return SelectInst::Create(SI->getCondition(), N, A);
2380       if (match(TV, m_Zero()) &&
2381           match(FV, m_Sub(m_Value(N), m_Specific(A))))
2382         // Fold the add into the false select value.
2383         return SelectInst::Create(SI->getCondition(), A, N);
2384     }
2385   }
2386
2387   // Check for (add (sext x), y), see if we can merge this into an
2388   // integer add followed by a sext.
2389   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2390     // (add (sext x), cst) --> (sext (add x, cst'))
2391     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2392       Constant *CI = 
2393         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2394       if (LHSConv->hasOneUse() &&
2395           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2396           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2397         // Insert the new, smaller add.
2398         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0), 
2399                                            CI, "addconv");
2400         return new SExtInst(NewAdd, I.getType());
2401       }
2402     }
2403     
2404     // (add (sext x), (sext y)) --> (sext (add int x, y))
2405     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2406       // Only do this if x/y have the same type, if at last one of them has a
2407       // single use (so we don't increase the number of sexts), and if the
2408       // integer add will not overflow.
2409       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2410           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2411           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2412                                    RHSConv->getOperand(0))) {
2413         // Insert the new integer add.
2414         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0), 
2415                                            RHSConv->getOperand(0), "addconv");
2416         return new SExtInst(NewAdd, I.getType());
2417       }
2418     }
2419   }
2420
2421   return Changed ? &I : 0;
2422 }
2423
2424 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2425   bool Changed = SimplifyCommutative(I);
2426   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2427
2428   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2429     // X + 0 --> X
2430     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2431       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2432                               (I.getType())->getValueAPF()))
2433         return ReplaceInstUsesWith(I, LHS);
2434     }
2435
2436     if (isa<PHINode>(LHS))
2437       if (Instruction *NV = FoldOpIntoPhi(I))
2438         return NV;
2439   }
2440
2441   // -A + B  -->  B - A
2442   // -A + -B  -->  -(A + B)
2443   if (Value *LHSV = dyn_castFNegVal(LHS))
2444     return BinaryOperator::CreateFSub(RHS, LHSV);
2445
2446   // A + -B  -->  A - B
2447   if (!isa<Constant>(RHS))
2448     if (Value *V = dyn_castFNegVal(RHS))
2449       return BinaryOperator::CreateFSub(LHS, V);
2450
2451   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2452   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2453     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2454       return ReplaceInstUsesWith(I, LHS);
2455
2456   // Check for (add double (sitofp x), y), see if we can merge this into an
2457   // integer add followed by a promotion.
2458   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2459     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2460     // ... if the constant fits in the integer value.  This is useful for things
2461     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2462     // requires a constant pool load, and generally allows the add to be better
2463     // instcombined.
2464     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2465       Constant *CI = 
2466       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2467       if (LHSConv->hasOneUse() &&
2468           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2469           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2470         // Insert the new integer add.
2471         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2472                                            CI, "addconv");
2473         return new SIToFPInst(NewAdd, I.getType());
2474       }
2475     }
2476     
2477     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2478     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2479       // Only do this if x/y have the same type, if at last one of them has a
2480       // single use (so we don't increase the number of int->fp conversions),
2481       // and if the integer add will not overflow.
2482       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2483           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2484           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2485                                    RHSConv->getOperand(0))) {
2486         // Insert the new integer add.
2487         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0), 
2488                                            RHSConv->getOperand(0), "addconv");
2489         return new SIToFPInst(NewAdd, I.getType());
2490       }
2491     }
2492   }
2493   
2494   return Changed ? &I : 0;
2495 }
2496
2497 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2498   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2499
2500   if (Op0 == Op1)                        // sub X, X  -> 0
2501     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2502
2503   // If this is a 'B = x-(-A)', change to B = x+A...
2504   if (Value *V = dyn_castNegVal(Op1))
2505     return BinaryOperator::CreateAdd(Op0, V);
2506
2507   if (isa<UndefValue>(Op0))
2508     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2509   if (isa<UndefValue>(Op1))
2510     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2511
2512   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2513     // Replace (-1 - A) with (~A)...
2514     if (C->isAllOnesValue())
2515       return BinaryOperator::CreateNot(Op1);
2516
2517     // C - ~X == X + (1+C)
2518     Value *X = 0;
2519     if (match(Op1, m_Not(m_Value(X))))
2520       return BinaryOperator::CreateAdd(X, AddOne(C));
2521
2522     // -(X >>u 31) -> (X >>s 31)
2523     // -(X >>s 31) -> (X >>u 31)
2524     if (C->isZero()) {
2525       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2526         if (SI->getOpcode() == Instruction::LShr) {
2527           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2528             // Check to see if we are shifting out everything but the sign bit.
2529             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2530                 SI->getType()->getPrimitiveSizeInBits()-1) {
2531               // Ok, the transformation is safe.  Insert AShr.
2532               return BinaryOperator::Create(Instruction::AShr, 
2533                                           SI->getOperand(0), CU, SI->getName());
2534             }
2535           }
2536         }
2537         else if (SI->getOpcode() == Instruction::AShr) {
2538           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2539             // Check to see if we are shifting out everything but the sign bit.
2540             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2541                 SI->getType()->getPrimitiveSizeInBits()-1) {
2542               // Ok, the transformation is safe.  Insert LShr. 
2543               return BinaryOperator::CreateLShr(
2544                                           SI->getOperand(0), CU, SI->getName());
2545             }
2546           }
2547         }
2548       }
2549     }
2550
2551     // Try to fold constant sub into select arguments.
2552     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2553       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2554         return R;
2555
2556     // C - zext(bool) -> bool ? C - 1 : C
2557     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2558       if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2559         return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
2560   }
2561
2562   if (I.getType() == Type::getInt1Ty(*Context))
2563     return BinaryOperator::CreateXor(Op0, Op1);
2564
2565   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2566     if (Op1I->getOpcode() == Instruction::Add) {
2567       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2568         return BinaryOperator::CreateNeg(Op1I->getOperand(1),
2569                                          I.getName());
2570       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2571         return BinaryOperator::CreateNeg(Op1I->getOperand(0),
2572                                          I.getName());
2573       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2574         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2575           // C1-(X+C2) --> (C1-C2)-X
2576           return BinaryOperator::CreateSub(
2577             ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
2578       }
2579     }
2580
2581     if (Op1I->hasOneUse()) {
2582       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2583       // is not used by anyone else...
2584       //
2585       if (Op1I->getOpcode() == Instruction::Sub) {
2586         // Swap the two operands of the subexpr...
2587         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2588         Op1I->setOperand(0, IIOp1);
2589         Op1I->setOperand(1, IIOp0);
2590
2591         // Create the new top level add instruction...
2592         return BinaryOperator::CreateAdd(Op0, Op1);
2593       }
2594
2595       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2596       //
2597       if (Op1I->getOpcode() == Instruction::And &&
2598           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2599         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2600
2601         Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
2602         return BinaryOperator::CreateAnd(Op0, NewNot);
2603       }
2604
2605       // 0 - (X sdiv C)  -> (X sdiv -C)
2606       if (Op1I->getOpcode() == Instruction::SDiv)
2607         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2608           if (CSI->isZero())
2609             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2610               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2611                                           ConstantExpr::getNeg(DivRHS));
2612
2613       // X - X*C --> X * (1-C)
2614       ConstantInt *C2 = 0;
2615       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2616         Constant *CP1 = 
2617           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2618                                              C2);
2619         return BinaryOperator::CreateMul(Op0, CP1);
2620       }
2621     }
2622   }
2623
2624   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2625     if (Op0I->getOpcode() == Instruction::Add) {
2626       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2627         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2628       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2629         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2630     } else if (Op0I->getOpcode() == Instruction::Sub) {
2631       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2632         return BinaryOperator::CreateNeg(Op0I->getOperand(1),
2633                                          I.getName());
2634     }
2635   }
2636
2637   ConstantInt *C1;
2638   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2639     if (X == Op1)  // X*C - X --> X * (C-1)
2640       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2641
2642     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2643     if (X == dyn_castFoldableMul(Op1, C2))
2644       return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2645   }
2646   return 0;
2647 }
2648
2649 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2650   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2651
2652   // If this is a 'B = x-(-A)', change to B = x+A...
2653   if (Value *V = dyn_castFNegVal(Op1))
2654     return BinaryOperator::CreateFAdd(Op0, V);
2655
2656   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2657     if (Op1I->getOpcode() == Instruction::FAdd) {
2658       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2659         return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
2660                                           I.getName());
2661       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2662         return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
2663                                           I.getName());
2664     }
2665   }
2666
2667   return 0;
2668 }
2669
2670 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2671 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2672 /// TrueIfSigned if the result of the comparison is true when the input value is
2673 /// signed.
2674 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2675                            bool &TrueIfSigned) {
2676   switch (pred) {
2677   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2678     TrueIfSigned = true;
2679     return RHS->isZero();
2680   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2681     TrueIfSigned = true;
2682     return RHS->isAllOnesValue();
2683   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2684     TrueIfSigned = false;
2685     return RHS->isAllOnesValue();
2686   case ICmpInst::ICMP_UGT:
2687     // True if LHS u> RHS and RHS == high-bit-mask - 1
2688     TrueIfSigned = true;
2689     return RHS->getValue() ==
2690       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2691   case ICmpInst::ICMP_UGE: 
2692     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2693     TrueIfSigned = true;
2694     return RHS->getValue().isSignBit();
2695   default:
2696     return false;
2697   }
2698 }
2699
2700 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2701   bool Changed = SimplifyCommutative(I);
2702   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2703
2704   if (isa<UndefValue>(Op1))              // undef * X -> 0
2705     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2706
2707   // Simplify mul instructions with a constant RHS.
2708   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2709     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
2710
2711       // ((X << C1)*C2) == (X * (C2 << C1))
2712       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2713         if (SI->getOpcode() == Instruction::Shl)
2714           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2715             return BinaryOperator::CreateMul(SI->getOperand(0),
2716                                         ConstantExpr::getShl(CI, ShOp));
2717
2718       if (CI->isZero())
2719         return ReplaceInstUsesWith(I, Op1C);  // X * 0  == 0
2720       if (CI->equalsInt(1))                  // X * 1  == X
2721         return ReplaceInstUsesWith(I, Op0);
2722       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2723         return BinaryOperator::CreateNeg(Op0, I.getName());
2724
2725       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2726       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2727         return BinaryOperator::CreateShl(Op0,
2728                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2729       }
2730     } else if (isa<VectorType>(Op1C->getType())) {
2731       if (Op1C->isNullValue())
2732         return ReplaceInstUsesWith(I, Op1C);
2733
2734       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
2735         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2736           return BinaryOperator::CreateNeg(Op0, I.getName());
2737
2738         // As above, vector X*splat(1.0) -> X in all defined cases.
2739         if (Constant *Splat = Op1V->getSplatValue()) {
2740           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2741             if (CI->equalsInt(1))
2742               return ReplaceInstUsesWith(I, Op0);
2743         }
2744       }
2745     }
2746     
2747     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2748       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2749           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
2750         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2751         Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
2752         Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
2753         return BinaryOperator::CreateAdd(Add, C1C2);
2754         
2755       }
2756
2757     // Try to fold constant mul into select arguments.
2758     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2759       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2760         return R;
2761
2762     if (isa<PHINode>(Op0))
2763       if (Instruction *NV = FoldOpIntoPhi(I))
2764         return NV;
2765   }
2766
2767   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2768     if (Value *Op1v = dyn_castNegVal(Op1))
2769       return BinaryOperator::CreateMul(Op0v, Op1v);
2770
2771   // (X / Y) *  Y = X - (X % Y)
2772   // (X / Y) * -Y = (X % Y) - X
2773   {
2774     Value *Op1C = Op1;
2775     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2776     if (!BO ||
2777         (BO->getOpcode() != Instruction::UDiv && 
2778          BO->getOpcode() != Instruction::SDiv)) {
2779       Op1C = Op0;
2780       BO = dyn_cast<BinaryOperator>(Op1);
2781     }
2782     Value *Neg = dyn_castNegVal(Op1C);
2783     if (BO && BO->hasOneUse() &&
2784         (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
2785         (BO->getOpcode() == Instruction::UDiv ||
2786          BO->getOpcode() == Instruction::SDiv)) {
2787       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2788
2789       // If the division is exact, X % Y is zero.
2790       if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2791         if (SDiv->isExact()) {
2792           if (Op1BO == Op1C)
2793             return ReplaceInstUsesWith(I, Op0BO);
2794           return BinaryOperator::CreateNeg(Op0BO);
2795         }
2796
2797       Value *Rem;
2798       if (BO->getOpcode() == Instruction::UDiv)
2799         Rem = Builder->CreateURem(Op0BO, Op1BO);
2800       else
2801         Rem = Builder->CreateSRem(Op0BO, Op1BO);
2802       Rem->takeName(BO);
2803
2804       if (Op1BO == Op1C)
2805         return BinaryOperator::CreateSub(Op0BO, Rem);
2806       return BinaryOperator::CreateSub(Rem, Op0BO);
2807     }
2808   }
2809
2810   /// i1 mul -> i1 and.
2811   if (I.getType() == Type::getInt1Ty(*Context))
2812     return BinaryOperator::CreateAnd(Op0, Op1);
2813
2814   // X*(1 << Y) --> X << Y
2815   // (1 << Y)*X --> X << Y
2816   {
2817     Value *Y;
2818     if (match(Op0, m_Shl(m_One(), m_Value(Y))))
2819       return BinaryOperator::CreateShl(Op1, Y);
2820     if (match(Op1, m_Shl(m_One(), m_Value(Y))))
2821       return BinaryOperator::CreateShl(Op0, Y);
2822   }
2823   
2824   // If one of the operands of the multiply is a cast from a boolean value, then
2825   // we know the bool is either zero or one, so this is a 'masking' multiply.
2826   //   X * Y (where Y is 0 or 1) -> X & (0-Y)
2827   if (!isa<VectorType>(I.getType())) {
2828     // -2 is "-1 << 1" so it is all bits set except the low one.
2829     APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
2830     
2831     Value *BoolCast = 0, *OtherOp = 0;
2832     if (MaskedValueIsZero(Op0, Negative2))
2833       BoolCast = Op0, OtherOp = Op1;
2834     else if (MaskedValueIsZero(Op1, Negative2))
2835       BoolCast = Op1, OtherOp = Op0;
2836
2837     if (BoolCast) {
2838       Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
2839                                     BoolCast, "tmp");
2840       return BinaryOperator::CreateAnd(V, OtherOp);
2841     }
2842   }
2843
2844   return Changed ? &I : 0;
2845 }
2846
2847 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2848   bool Changed = SimplifyCommutative(I);
2849   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2850
2851   // Simplify mul instructions with a constant RHS...
2852   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2853     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
2854       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2855       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2856       if (Op1F->isExactlyValue(1.0))
2857         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2858     } else if (isa<VectorType>(Op1C->getType())) {
2859       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
2860         // As above, vector X*splat(1.0) -> X in all defined cases.
2861         if (Constant *Splat = Op1V->getSplatValue()) {
2862           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2863             if (F->isExactlyValue(1.0))
2864               return ReplaceInstUsesWith(I, Op0);
2865         }
2866       }
2867     }
2868
2869     // Try to fold constant mul into select arguments.
2870     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2871       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2872         return R;
2873
2874     if (isa<PHINode>(Op0))
2875       if (Instruction *NV = FoldOpIntoPhi(I))
2876         return NV;
2877   }
2878
2879   if (Value *Op0v = dyn_castFNegVal(Op0))     // -X * -Y = X*Y
2880     if (Value *Op1v = dyn_castFNegVal(Op1))
2881       return BinaryOperator::CreateFMul(Op0v, Op1v);
2882
2883   return Changed ? &I : 0;
2884 }
2885
2886 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2887 /// instruction.
2888 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2889   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2890   
2891   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2892   int NonNullOperand = -1;
2893   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2894     if (ST->isNullValue())
2895       NonNullOperand = 2;
2896   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2897   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2898     if (ST->isNullValue())
2899       NonNullOperand = 1;
2900   
2901   if (NonNullOperand == -1)
2902     return false;
2903   
2904   Value *SelectCond = SI->getOperand(0);
2905   
2906   // Change the div/rem to use 'Y' instead of the select.
2907   I.setOperand(1, SI->getOperand(NonNullOperand));
2908   
2909   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2910   // problem.  However, the select, or the condition of the select may have
2911   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2912   // propagate the known value for the select into other uses of it, and
2913   // propagate a known value of the condition into its other users.
2914   
2915   // If the select and condition only have a single use, don't bother with this,
2916   // early exit.
2917   if (SI->use_empty() && SelectCond->hasOneUse())
2918     return true;
2919   
2920   // Scan the current block backward, looking for other uses of SI.
2921   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2922   
2923   while (BBI != BBFront) {
2924     --BBI;
2925     // If we found a call to a function, we can't assume it will return, so
2926     // information from below it cannot be propagated above it.
2927     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2928       break;
2929     
2930     // Replace uses of the select or its condition with the known values.
2931     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2932          I != E; ++I) {
2933       if (*I == SI) {
2934         *I = SI->getOperand(NonNullOperand);
2935         Worklist.Add(BBI);
2936       } else if (*I == SelectCond) {
2937         *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2938                                    ConstantInt::getFalse(*Context);
2939         Worklist.Add(BBI);
2940       }
2941     }
2942     
2943     // If we past the instruction, quit looking for it.
2944     if (&*BBI == SI)
2945       SI = 0;
2946     if (&*BBI == SelectCond)
2947       SelectCond = 0;
2948     
2949     // If we ran out of things to eliminate, break out of the loop.
2950     if (SelectCond == 0 && SI == 0)
2951       break;
2952     
2953   }
2954   return true;
2955 }
2956
2957
2958 /// This function implements the transforms on div instructions that work
2959 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2960 /// used by the visitors to those instructions.
2961 /// @brief Transforms common to all three div instructions
2962 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2963   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2964
2965   // undef / X -> 0        for integer.
2966   // undef / X -> undef    for FP (the undef could be a snan).
2967   if (isa<UndefValue>(Op0)) {
2968     if (Op0->getType()->isFPOrFPVector())
2969       return ReplaceInstUsesWith(I, Op0);
2970     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2971   }
2972
2973   // X / undef -> undef
2974   if (isa<UndefValue>(Op1))
2975     return ReplaceInstUsesWith(I, Op1);
2976
2977   return 0;
2978 }
2979
2980 /// This function implements the transforms common to both integer division
2981 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2982 /// division instructions.
2983 /// @brief Common integer divide transforms
2984 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2985   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2986
2987   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2988   if (Op0 == Op1) {
2989     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2990       Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
2991       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2992       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2993     }
2994
2995     Constant *CI = ConstantInt::get(I.getType(), 1);
2996     return ReplaceInstUsesWith(I, CI);
2997   }
2998   
2999   if (Instruction *Common = commonDivTransforms(I))
3000     return Common;
3001   
3002   // Handle cases involving: [su]div X, (select Cond, Y, Z)
3003   // This does not apply for fdiv.
3004   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3005     return &I;
3006
3007   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3008     // div X, 1 == X
3009     if (RHS->equalsInt(1))
3010       return ReplaceInstUsesWith(I, Op0);
3011
3012     // (X / C1) / C2  -> X / (C1*C2)
3013     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3014       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3015         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3016           if (MultiplyOverflows(RHS, LHSRHS,
3017                                 I.getOpcode()==Instruction::SDiv))
3018             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3019           else 
3020             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
3021                                       ConstantExpr::getMul(RHS, LHSRHS));
3022         }
3023
3024     if (!RHS->isZero()) { // avoid X udiv 0
3025       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3026         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3027           return R;
3028       if (isa<PHINode>(Op0))
3029         if (Instruction *NV = FoldOpIntoPhi(I))
3030           return NV;
3031     }
3032   }
3033
3034   // 0 / X == 0, we don't need to preserve faults!
3035   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3036     if (LHS->equalsInt(0))
3037       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3038
3039   // It can't be division by zero, hence it must be division by one.
3040   if (I.getType() == Type::getInt1Ty(*Context))
3041     return ReplaceInstUsesWith(I, Op0);
3042
3043   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3044     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3045       // div X, 1 == X
3046       if (X->isOne())
3047         return ReplaceInstUsesWith(I, Op0);
3048   }
3049
3050   return 0;
3051 }
3052
3053 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3054   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3055
3056   // Handle the integer div common cases
3057   if (Instruction *Common = commonIDivTransforms(I))
3058     return Common;
3059
3060   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3061     // X udiv C^2 -> X >> C
3062     // Check to see if this is an unsigned division with an exact power of 2,
3063     // if so, convert to a right shift.
3064     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3065       return BinaryOperator::CreateLShr(Op0, 
3066             ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3067
3068     // X udiv C, where C >= signbit
3069     if (C->getValue().isNegative()) {
3070       Value *IC = Builder->CreateICmpULT( Op0, C);
3071       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3072                                 ConstantInt::get(I.getType(), 1));
3073     }
3074   }
3075
3076   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3077   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3078     if (RHSI->getOpcode() == Instruction::Shl &&
3079         isa<ConstantInt>(RHSI->getOperand(0))) {
3080       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3081       if (C1.isPowerOf2()) {
3082         Value *N = RHSI->getOperand(1);
3083         const Type *NTy = N->getType();
3084         if (uint32_t C2 = C1.logBase2())
3085           N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
3086         return BinaryOperator::CreateLShr(Op0, N);
3087       }
3088     }
3089   }
3090   
3091   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3092   // where C1&C2 are powers of two.
3093   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3094     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3095       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3096         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3097         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3098           // Compute the shift amounts
3099           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3100           // Construct the "on true" case of the select
3101           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3102           Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
3103   
3104           // Construct the "on false" case of the select
3105           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3106           Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
3107
3108           // construct the select instruction and return it.
3109           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3110         }
3111       }
3112   return 0;
3113 }
3114
3115 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3116   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3117
3118   // Handle the integer div common cases
3119   if (Instruction *Common = commonIDivTransforms(I))
3120     return Common;
3121
3122   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3123     // sdiv X, -1 == -X
3124     if (RHS->isAllOnesValue())
3125       return BinaryOperator::CreateNeg(Op0);
3126
3127     // sdiv X, C  -->  ashr X, log2(C)
3128     if (cast<SDivOperator>(&I)->isExact() &&
3129         RHS->getValue().isNonNegative() &&
3130         RHS->getValue().isPowerOf2()) {
3131       Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3132                                             RHS->getValue().exactLogBase2());
3133       return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3134     }
3135
3136     // -X/C  -->  X/-C  provided the negation doesn't overflow.
3137     if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3138       if (isa<Constant>(Sub->getOperand(0)) &&
3139           cast<Constant>(Sub->getOperand(0))->isNullValue() &&
3140           Sub->hasNoSignedWrap())
3141         return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3142                                           ConstantExpr::getNeg(RHS));
3143   }
3144
3145   // If the sign bits of both operands are zero (i.e. we can prove they are
3146   // unsigned inputs), turn this into a udiv.
3147   if (I.getType()->isInteger()) {
3148     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3149     if (MaskedValueIsZero(Op0, Mask)) {
3150       if (MaskedValueIsZero(Op1, Mask)) {
3151         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3152         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3153       }
3154       ConstantInt *ShiftedInt;
3155       if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
3156           ShiftedInt->getValue().isPowerOf2()) {
3157         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3158         // Safe because the only negative value (1 << Y) can take on is
3159         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3160         // the sign bit set.
3161         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3162       }
3163     }
3164   }
3165   
3166   return 0;
3167 }
3168
3169 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3170   return commonDivTransforms(I);
3171 }
3172
3173 /// This function implements the transforms on rem instructions that work
3174 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3175 /// is used by the visitors to those instructions.
3176 /// @brief Transforms common to all three rem instructions
3177 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3178   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3179
3180   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3181     if (I.getType()->isFPOrFPVector())
3182       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3183     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3184   }
3185   if (isa<UndefValue>(Op1))
3186     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3187
3188   // Handle cases involving: rem X, (select Cond, Y, Z)
3189   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3190     return &I;
3191
3192   return 0;
3193 }
3194
3195 /// This function implements the transforms common to both integer remainder
3196 /// instructions (urem and srem). It is called by the visitors to those integer
3197 /// remainder instructions.
3198 /// @brief Common integer remainder transforms
3199 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3200   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3201
3202   if (Instruction *common = commonRemTransforms(I))
3203     return common;
3204
3205   // 0 % X == 0 for integer, we don't need to preserve faults!
3206   if (Constant *LHS = dyn_cast<Constant>(Op0))
3207     if (LHS->isNullValue())
3208       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3209
3210   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3211     // X % 0 == undef, we don't need to preserve faults!
3212     if (RHS->equalsInt(0))
3213       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3214     
3215     if (RHS->equalsInt(1))  // X % 1 == 0
3216       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3217
3218     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3219       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3220         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3221           return R;
3222       } else if (isa<PHINode>(Op0I)) {
3223         if (Instruction *NV = FoldOpIntoPhi(I))
3224           return NV;
3225       }
3226
3227       // See if we can fold away this rem instruction.
3228       if (SimplifyDemandedInstructionBits(I))
3229         return &I;
3230     }
3231   }
3232
3233   return 0;
3234 }
3235
3236 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3237   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3238
3239   if (Instruction *common = commonIRemTransforms(I))
3240     return common;
3241   
3242   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3243     // X urem C^2 -> X and C
3244     // Check to see if this is an unsigned remainder with an exact power of 2,
3245     // if so, convert to a bitwise and.
3246     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3247       if (C->getValue().isPowerOf2())
3248         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3249   }
3250
3251   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3252     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3253     if (RHSI->getOpcode() == Instruction::Shl &&
3254         isa<ConstantInt>(RHSI->getOperand(0))) {
3255       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3256         Constant *N1 = Constant::getAllOnesValue(I.getType());
3257         Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
3258         return BinaryOperator::CreateAnd(Op0, Add);
3259       }
3260     }
3261   }
3262
3263   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3264   // where C1&C2 are powers of two.
3265   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3266     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3267       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3268         // STO == 0 and SFO == 0 handled above.
3269         if ((STO->getValue().isPowerOf2()) && 
3270             (SFO->getValue().isPowerOf2())) {
3271           Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3272                                               SI->getName()+".t");
3273           Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3274                                                SI->getName()+".f");
3275           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3276         }
3277       }
3278   }
3279   
3280   return 0;
3281 }
3282
3283 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3284   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3285
3286   // Handle the integer rem common cases
3287   if (Instruction *Common = commonIRemTransforms(I))
3288     return Common;
3289   
3290   if (Value *RHSNeg = dyn_castNegVal(Op1))
3291     if (!isa<Constant>(RHSNeg) ||
3292         (isa<ConstantInt>(RHSNeg) &&
3293          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3294       // X % -Y -> X % Y
3295       Worklist.AddValue(I.getOperand(1));
3296       I.setOperand(1, RHSNeg);
3297       return &I;
3298     }
3299
3300   // If the sign bits of both operands are zero (i.e. we can prove they are
3301   // unsigned inputs), turn this into a urem.
3302   if (I.getType()->isInteger()) {
3303     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3304     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3305       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3306       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3307     }
3308   }
3309
3310   // If it's a constant vector, flip any negative values positive.
3311   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3312     unsigned VWidth = RHSV->getNumOperands();
3313
3314     bool hasNegative = false;
3315     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3316       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3317         if (RHS->getValue().isNegative())
3318           hasNegative = true;
3319
3320     if (hasNegative) {
3321       std::vector<Constant *> Elts(VWidth);
3322       for (unsigned i = 0; i != VWidth; ++i) {
3323         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3324           if (RHS->getValue().isNegative())
3325             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3326           else
3327             Elts[i] = RHS;
3328         }
3329       }
3330
3331       Constant *NewRHSV = ConstantVector::get(Elts);
3332       if (NewRHSV != RHSV) {
3333         Worklist.AddValue(I.getOperand(1));
3334         I.setOperand(1, NewRHSV);
3335         return &I;
3336       }
3337     }
3338   }
3339
3340   return 0;
3341 }
3342
3343 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3344   return commonRemTransforms(I);
3345 }
3346
3347 // isOneBitSet - Return true if there is exactly one bit set in the specified
3348 // constant.
3349 static bool isOneBitSet(const ConstantInt *CI) {
3350   return CI->getValue().isPowerOf2();
3351 }
3352
3353 // isHighOnes - Return true if the constant is of the form 1+0+.
3354 // This is the same as lowones(~X).
3355 static bool isHighOnes(const ConstantInt *CI) {
3356   return (~CI->getValue() + 1).isPowerOf2();
3357 }
3358
3359 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3360 /// are carefully arranged to allow folding of expressions such as:
3361 ///
3362 ///      (A < B) | (A > B) --> (A != B)
3363 ///
3364 /// Note that this is only valid if the first and second predicates have the
3365 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3366 ///
3367 /// Three bits are used to represent the condition, as follows:
3368 ///   0  A > B
3369 ///   1  A == B
3370 ///   2  A < B
3371 ///
3372 /// <=>  Value  Definition
3373 /// 000     0   Always false
3374 /// 001     1   A >  B
3375 /// 010     2   A == B
3376 /// 011     3   A >= B
3377 /// 100     4   A <  B
3378 /// 101     5   A != B
3379 /// 110     6   A <= B
3380 /// 111     7   Always true
3381 ///  
3382 static unsigned getICmpCode(const ICmpInst *ICI) {
3383   switch (ICI->getPredicate()) {
3384     // False -> 0
3385   case ICmpInst::ICMP_UGT: return 1;  // 001
3386   case ICmpInst::ICMP_SGT: return 1;  // 001
3387   case ICmpInst::ICMP_EQ:  return 2;  // 010
3388   case ICmpInst::ICMP_UGE: return 3;  // 011
3389   case ICmpInst::ICMP_SGE: return 3;  // 011
3390   case ICmpInst::ICMP_ULT: return 4;  // 100
3391   case ICmpInst::ICMP_SLT: return 4;  // 100
3392   case ICmpInst::ICMP_NE:  return 5;  // 101
3393   case ICmpInst::ICMP_ULE: return 6;  // 110
3394   case ICmpInst::ICMP_SLE: return 6;  // 110
3395     // True -> 7
3396   default:
3397     llvm_unreachable("Invalid ICmp predicate!");
3398     return 0;
3399   }
3400 }
3401
3402 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3403 /// predicate into a three bit mask. It also returns whether it is an ordered
3404 /// predicate by reference.
3405 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3406   isOrdered = false;
3407   switch (CC) {
3408   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3409   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3410   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3411   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3412   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3413   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3414   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3415   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3416   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3417   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3418   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3419   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3420   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3421   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3422     // True -> 7
3423   default:
3424     // Not expecting FCMP_FALSE and FCMP_TRUE;
3425     llvm_unreachable("Unexpected FCmp predicate!");
3426     return 0;
3427   }
3428 }
3429
3430 /// getICmpValue - This is the complement of getICmpCode, which turns an
3431 /// opcode and two operands into either a constant true or false, or a brand 
3432 /// new ICmp instruction. The sign is passed in to determine which kind
3433 /// of predicate to use in the new icmp instruction.
3434 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3435                            LLVMContext *Context) {
3436   switch (code) {
3437   default: llvm_unreachable("Illegal ICmp code!");
3438   case  0: return ConstantInt::getFalse(*Context);
3439   case  1: 
3440     if (sign)
3441       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3442     else
3443       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3444   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3445   case  3: 
3446     if (sign)
3447       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3448     else
3449       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3450   case  4: 
3451     if (sign)
3452       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3453     else
3454       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3455   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3456   case  6: 
3457     if (sign)
3458       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3459     else
3460       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3461   case  7: return ConstantInt::getTrue(*Context);
3462   }
3463 }
3464
3465 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3466 /// opcode and two operands into either a FCmp instruction. isordered is passed
3467 /// in to determine which kind of predicate to use in the new fcmp instruction.
3468 static Value *getFCmpValue(bool isordered, unsigned code,
3469                            Value *LHS, Value *RHS, LLVMContext *Context) {
3470   switch (code) {
3471   default: llvm_unreachable("Illegal FCmp code!");
3472   case  0:
3473     if (isordered)
3474       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3475     else
3476       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3477   case  1: 
3478     if (isordered)
3479       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3480     else
3481       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3482   case  2: 
3483     if (isordered)
3484       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3485     else
3486       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3487   case  3: 
3488     if (isordered)
3489       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3490     else
3491       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3492   case  4: 
3493     if (isordered)
3494       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3495     else
3496       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3497   case  5: 
3498     if (isordered)
3499       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3500     else
3501       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3502   case  6: 
3503     if (isordered)
3504       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3505     else
3506       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3507   case  7: return ConstantInt::getTrue(*Context);
3508   }
3509 }
3510
3511 /// PredicatesFoldable - Return true if both predicates match sign or if at
3512 /// least one of them is an equality comparison (which is signless).
3513 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3514   return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3515          (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3516          (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
3517 }
3518
3519 namespace { 
3520 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3521 struct FoldICmpLogical {
3522   InstCombiner &IC;
3523   Value *LHS, *RHS;
3524   ICmpInst::Predicate pred;
3525   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3526     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3527       pred(ICI->getPredicate()) {}
3528   bool shouldApply(Value *V) const {
3529     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3530       if (PredicatesFoldable(pred, ICI->getPredicate()))
3531         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3532                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3533     return false;
3534   }
3535   Instruction *apply(Instruction &Log) const {
3536     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3537     if (ICI->getOperand(0) != LHS) {
3538       assert(ICI->getOperand(1) == LHS);
3539       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3540     }
3541
3542     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3543     unsigned LHSCode = getICmpCode(ICI);
3544     unsigned RHSCode = getICmpCode(RHSICI);
3545     unsigned Code;
3546     switch (Log.getOpcode()) {
3547     case Instruction::And: Code = LHSCode & RHSCode; break;
3548     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3549     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3550     default: llvm_unreachable("Illegal logical opcode!"); return 0;
3551     }
3552
3553     bool isSigned = RHSICI->isSigned() || ICI->isSigned();
3554     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3555     if (Instruction *I = dyn_cast<Instruction>(RV))
3556       return I;
3557     // Otherwise, it's a constant boolean value...
3558     return IC.ReplaceInstUsesWith(Log, RV);
3559   }
3560 };
3561 } // end anonymous namespace
3562
3563 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3564 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3565 // guaranteed to be a binary operator.
3566 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3567                                     ConstantInt *OpRHS,
3568                                     ConstantInt *AndRHS,
3569                                     BinaryOperator &TheAnd) {
3570   Value *X = Op->getOperand(0);
3571   Constant *Together = 0;
3572   if (!Op->isShift())
3573     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3574
3575   switch (Op->getOpcode()) {
3576   case Instruction::Xor:
3577     if (Op->hasOneUse()) {
3578       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3579       Value *And = Builder->CreateAnd(X, AndRHS);
3580       And->takeName(Op);
3581       return BinaryOperator::CreateXor(And, Together);
3582     }
3583     break;
3584   case Instruction::Or:
3585     if (Together == AndRHS) // (X | C) & C --> C
3586       return ReplaceInstUsesWith(TheAnd, AndRHS);
3587
3588     if (Op->hasOneUse() && Together != OpRHS) {
3589       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3590       Value *Or = Builder->CreateOr(X, Together);
3591       Or->takeName(Op);
3592       return BinaryOperator::CreateAnd(Or, AndRHS);
3593     }
3594     break;
3595   case Instruction::Add:
3596     if (Op->hasOneUse()) {
3597       // Adding a one to a single bit bit-field should be turned into an XOR
3598       // of the bit.  First thing to check is to see if this AND is with a
3599       // single bit constant.
3600       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3601
3602       // If there is only one bit set...
3603       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3604         // Ok, at this point, we know that we are masking the result of the
3605         // ADD down to exactly one bit.  If the constant we are adding has
3606         // no bits set below this bit, then we can eliminate the ADD.
3607         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3608
3609         // Check to see if any bits below the one bit set in AndRHSV are set.
3610         if ((AddRHS & (AndRHSV-1)) == 0) {
3611           // If not, the only thing that can effect the output of the AND is
3612           // the bit specified by AndRHSV.  If that bit is set, the effect of
3613           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3614           // no effect.
3615           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3616             TheAnd.setOperand(0, X);
3617             return &TheAnd;
3618           } else {
3619             // Pull the XOR out of the AND.
3620             Value *NewAnd = Builder->CreateAnd(X, AndRHS);
3621             NewAnd->takeName(Op);
3622             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3623           }
3624         }
3625       }
3626     }
3627     break;
3628
3629   case Instruction::Shl: {
3630     // We know that the AND will not produce any of the bits shifted in, so if
3631     // the anded constant includes them, clear them now!
3632     //
3633     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3634     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3635     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3636     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3637
3638     if (CI->getValue() == ShlMask) { 
3639     // Masking out bits that the shift already masks
3640       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3641     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3642       TheAnd.setOperand(1, CI);
3643       return &TheAnd;
3644     }
3645     break;
3646   }
3647   case Instruction::LShr:
3648   {
3649     // We know that the AND will not produce any of the bits shifted in, so if
3650     // the anded constant includes them, clear them now!  This only applies to
3651     // unsigned shifts, because a signed shr may bring in set bits!
3652     //
3653     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3654     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3655     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3656     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3657
3658     if (CI->getValue() == ShrMask) {   
3659     // Masking out bits that the shift already masks.
3660       return ReplaceInstUsesWith(TheAnd, Op);
3661     } else if (CI != AndRHS) {
3662       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3663       return &TheAnd;
3664     }
3665     break;
3666   }
3667   case Instruction::AShr:
3668     // Signed shr.
3669     // See if this is shifting in some sign extension, then masking it out
3670     // with an and.
3671     if (Op->hasOneUse()) {
3672       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3673       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3674       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3675       Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3676       if (C == AndRHS) {          // Masking out bits shifted in.
3677         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3678         // Make the argument unsigned.
3679         Value *ShVal = Op->getOperand(0);
3680         ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
3681         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3682       }
3683     }
3684     break;
3685   }
3686   return 0;
3687 }
3688
3689
3690 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3691 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3692 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3693 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3694 /// insert new instructions.
3695 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3696                                            bool isSigned, bool Inside, 
3697                                            Instruction &IB) {
3698   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3699             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3700          "Lo is not <= Hi in range emission code!");
3701     
3702   if (Inside) {
3703     if (Lo == Hi)  // Trivially false.
3704       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3705
3706     // V >= Min && V < Hi --> V < Hi
3707     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3708       ICmpInst::Predicate pred = (isSigned ? 
3709         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3710       return new ICmpInst(pred, V, Hi);
3711     }
3712
3713     // Emit V-Lo <u Hi-Lo
3714     Constant *NegLo = ConstantExpr::getNeg(Lo);
3715     Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3716     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3717     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3718   }
3719
3720   if (Lo == Hi)  // Trivially true.
3721     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3722
3723   // V < Min || V >= Hi -> V > Hi-1
3724   Hi = SubOne(cast<ConstantInt>(Hi));
3725   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3726     ICmpInst::Predicate pred = (isSigned ? 
3727         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3728     return new ICmpInst(pred, V, Hi);
3729   }
3730
3731   // Emit V-Lo >u Hi-1-Lo
3732   // Note that Hi has already had one subtracted from it, above.
3733   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3734   Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3735   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3736   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3737 }
3738
3739 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3740 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3741 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3742 // not, since all 1s are not contiguous.
3743 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3744   const APInt& V = Val->getValue();
3745   uint32_t BitWidth = Val->getType()->getBitWidth();
3746   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3747
3748   // look for the first zero bit after the run of ones
3749   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3750   // look for the first non-zero bit
3751   ME = V.getActiveBits(); 
3752   return true;
3753 }
3754
3755 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3756 /// where isSub determines whether the operator is a sub.  If we can fold one of
3757 /// the following xforms:
3758 /// 
3759 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3760 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3761 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3762 ///
3763 /// return (A +/- B).
3764 ///
3765 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3766                                         ConstantInt *Mask, bool isSub,
3767                                         Instruction &I) {
3768   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3769   if (!LHSI || LHSI->getNumOperands() != 2 ||
3770       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3771
3772   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3773
3774   switch (LHSI->getOpcode()) {
3775   default: return 0;
3776   case Instruction::And:
3777     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3778       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3779       if ((Mask->getValue().countLeadingZeros() + 
3780            Mask->getValue().countPopulation()) == 
3781           Mask->getValue().getBitWidth())
3782         break;
3783
3784       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3785       // part, we don't need any explicit masks to take them out of A.  If that
3786       // is all N is, ignore it.
3787       uint32_t MB = 0, ME = 0;
3788       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3789         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3790         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3791         if (MaskedValueIsZero(RHS, Mask))
3792           break;
3793       }
3794     }
3795     return 0;
3796   case Instruction::Or:
3797   case Instruction::Xor:
3798     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3799     if ((Mask->getValue().countLeadingZeros() + 
3800          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3801         && ConstantExpr::getAnd(N, Mask)->isNullValue())
3802       break;
3803     return 0;
3804   }
3805   
3806   if (isSub)
3807     return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3808   return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
3809 }
3810
3811 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3812 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3813                                           ICmpInst *LHS, ICmpInst *RHS) {
3814   Value *Val, *Val2;
3815   ConstantInt *LHSCst, *RHSCst;
3816   ICmpInst::Predicate LHSCC, RHSCC;
3817   
3818   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3819   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3820                          m_ConstantInt(LHSCst))) ||
3821       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3822                          m_ConstantInt(RHSCst))))
3823     return 0;
3824   
3825   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3826   // where C is a power of 2
3827   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3828       LHSCst->getValue().isPowerOf2()) {
3829     Value *NewOr = Builder->CreateOr(Val, Val2);
3830     return new ICmpInst(LHSCC, NewOr, LHSCst);
3831   }
3832   
3833   // From here on, we only handle:
3834   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3835   if (Val != Val2) return 0;
3836   
3837   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3838   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3839       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3840       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3841       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3842     return 0;
3843   
3844   // We can't fold (ugt x, C) & (sgt x, C2).
3845   if (!PredicatesFoldable(LHSCC, RHSCC))
3846     return 0;
3847     
3848   // Ensure that the larger constant is on the RHS.
3849   bool ShouldSwap;
3850   if (CmpInst::isSigned(LHSCC) ||
3851       (ICmpInst::isEquality(LHSCC) && 
3852        CmpInst::isSigned(RHSCC)))
3853     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3854   else
3855     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3856     
3857   if (ShouldSwap) {
3858     std::swap(LHS, RHS);
3859     std::swap(LHSCst, RHSCst);
3860     std::swap(LHSCC, RHSCC);
3861   }
3862
3863   // At this point, we know we have have two icmp instructions
3864   // comparing a value against two constants and and'ing the result
3865   // together.  Because of the above check, we know that we only have
3866   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3867   // (from the FoldICmpLogical check above), that the two constants 
3868   // are not equal and that the larger constant is on the RHS
3869   assert(LHSCst != RHSCst && "Compares not folded above?");
3870
3871   switch (LHSCC) {
3872   default: llvm_unreachable("Unknown integer condition code!");
3873   case ICmpInst::ICMP_EQ:
3874     switch (RHSCC) {
3875     default: llvm_unreachable("Unknown integer condition code!");
3876     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3877     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3878     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3879       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3880     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3881     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3882     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3883       return ReplaceInstUsesWith(I, LHS);
3884     }
3885   case ICmpInst::ICMP_NE:
3886     switch (RHSCC) {
3887     default: llvm_unreachable("Unknown integer condition code!");
3888     case ICmpInst::ICMP_ULT:
3889       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3890         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3891       break;                        // (X != 13 & X u< 15) -> no change
3892     case ICmpInst::ICMP_SLT:
3893       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3894         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3895       break;                        // (X != 13 & X s< 15) -> no change
3896     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3897     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3898     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3899       return ReplaceInstUsesWith(I, RHS);
3900     case ICmpInst::ICMP_NE:
3901       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3902         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3903         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
3904         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3905                             ConstantInt::get(Add->getType(), 1));
3906       }
3907       break;                        // (X != 13 & X != 15) -> no change
3908     }
3909     break;
3910   case ICmpInst::ICMP_ULT:
3911     switch (RHSCC) {
3912     default: llvm_unreachable("Unknown integer condition code!");
3913     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3914     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3915       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3916     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3917       break;
3918     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3919     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3920       return ReplaceInstUsesWith(I, LHS);
3921     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3922       break;
3923     }
3924     break;
3925   case ICmpInst::ICMP_SLT:
3926     switch (RHSCC) {
3927     default: llvm_unreachable("Unknown integer condition code!");
3928     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3929     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3930       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3931     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3932       break;
3933     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3934     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3935       return ReplaceInstUsesWith(I, LHS);
3936     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3937       break;
3938     }
3939     break;
3940   case ICmpInst::ICMP_UGT:
3941     switch (RHSCC) {
3942     default: llvm_unreachable("Unknown integer condition code!");
3943     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3944     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3945       return ReplaceInstUsesWith(I, RHS);
3946     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3947       break;
3948     case ICmpInst::ICMP_NE:
3949       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3950         return new ICmpInst(LHSCC, Val, RHSCst);
3951       break;                        // (X u> 13 & X != 15) -> no change
3952     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3953       return InsertRangeTest(Val, AddOne(LHSCst),
3954                              RHSCst, false, true, I);
3955     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3956       break;
3957     }
3958     break;
3959   case ICmpInst::ICMP_SGT:
3960     switch (RHSCC) {
3961     default: llvm_unreachable("Unknown integer condition code!");
3962     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3963     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3964       return ReplaceInstUsesWith(I, RHS);
3965     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3966       break;
3967     case ICmpInst::ICMP_NE:
3968       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3969         return new ICmpInst(LHSCC, Val, RHSCst);
3970       break;                        // (X s> 13 & X != 15) -> no change
3971     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3972       return InsertRangeTest(Val, AddOne(LHSCst),
3973                              RHSCst, true, true, I);
3974     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3975       break;
3976     }
3977     break;
3978   }
3979  
3980   return 0;
3981 }
3982
3983 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3984                                           FCmpInst *RHS) {
3985   
3986   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3987       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3988     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3989     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3990       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3991         // If either of the constants are nans, then the whole thing returns
3992         // false.
3993         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3994           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3995         return new FCmpInst(FCmpInst::FCMP_ORD,
3996                             LHS->getOperand(0), RHS->getOperand(0));
3997       }
3998     
3999     // Handle vector zeros.  This occurs because the canonical form of
4000     // "fcmp ord x,x" is "fcmp ord x, 0".
4001     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4002         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4003       return new FCmpInst(FCmpInst::FCMP_ORD,
4004                           LHS->getOperand(0), RHS->getOperand(0));
4005     return 0;
4006   }
4007   
4008   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4009   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4010   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4011   
4012   
4013   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4014     // Swap RHS operands to match LHS.
4015     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4016     std::swap(Op1LHS, Op1RHS);
4017   }
4018   
4019   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4020     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4021     if (Op0CC == Op1CC)
4022       return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4023     
4024     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
4025       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4026     if (Op0CC == FCmpInst::FCMP_TRUE)
4027       return ReplaceInstUsesWith(I, RHS);
4028     if (Op1CC == FCmpInst::FCMP_TRUE)
4029       return ReplaceInstUsesWith(I, LHS);
4030     
4031     bool Op0Ordered;
4032     bool Op1Ordered;
4033     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4034     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4035     if (Op1Pred == 0) {
4036       std::swap(LHS, RHS);
4037       std::swap(Op0Pred, Op1Pred);
4038       std::swap(Op0Ordered, Op1Ordered);
4039     }
4040     if (Op0Pred == 0) {
4041       // uno && ueq -> uno && (uno || eq) -> ueq
4042       // ord && olt -> ord && (ord && lt) -> olt
4043       if (Op0Ordered == Op1Ordered)
4044         return ReplaceInstUsesWith(I, RHS);
4045       
4046       // uno && oeq -> uno && (ord && eq) -> false
4047       // uno && ord -> false
4048       if (!Op0Ordered)
4049         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4050       // ord && ueq -> ord && (uno || eq) -> oeq
4051       return cast<Instruction>(getFCmpValue(true, Op1Pred,
4052                                             Op0LHS, Op0RHS, Context));
4053     }
4054   }
4055
4056   return 0;
4057 }
4058
4059
4060 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4061   bool Changed = SimplifyCommutative(I);
4062   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4063
4064   if (isa<UndefValue>(Op1))                         // X & undef -> 0
4065     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4066
4067   // and X, X = X
4068   if (Op0 == Op1)
4069     return ReplaceInstUsesWith(I, Op1);
4070
4071   // See if we can simplify any instructions used by the instruction whose sole 
4072   // purpose is to compute bits we don't care about.
4073   if (SimplifyDemandedInstructionBits(I))
4074     return &I;
4075   if (isa<VectorType>(I.getType())) {
4076     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4077       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
4078         return ReplaceInstUsesWith(I, I.getOperand(0));
4079     } else if (isa<ConstantAggregateZero>(Op1)) {
4080       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
4081     }
4082   }
4083
4084   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4085     const APInt &AndRHSMask = AndRHS->getValue();
4086     APInt NotAndRHS(~AndRHSMask);
4087
4088     // Optimize a variety of ((val OP C1) & C2) combinations...
4089     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4090       Value *Op0LHS = Op0I->getOperand(0);
4091       Value *Op0RHS = Op0I->getOperand(1);
4092       switch (Op0I->getOpcode()) {
4093       default: break;
4094       case Instruction::Xor:
4095       case Instruction::Or:
4096         // If the mask is only needed on one incoming arm, push it up.
4097         if (!Op0I->hasOneUse()) break;
4098           
4099         if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4100           // Not masking anything out for the LHS, move to RHS.
4101           Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4102                                              Op0RHS->getName()+".masked");
4103           return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4104         }
4105         if (!isa<Constant>(Op0RHS) &&
4106             MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4107           // Not masking anything out for the RHS, move to LHS.
4108           Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4109                                              Op0LHS->getName()+".masked");
4110           return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
4111         }
4112
4113         break;
4114       case Instruction::Add:
4115         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4116         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4117         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4118         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4119           return BinaryOperator::CreateAnd(V, AndRHS);
4120         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4121           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4122         break;
4123
4124       case Instruction::Sub:
4125         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4126         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4127         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4128         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4129           return BinaryOperator::CreateAnd(V, AndRHS);
4130
4131         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4132         // has 1's for all bits that the subtraction with A might affect.
4133         if (Op0I->hasOneUse()) {
4134           uint32_t BitWidth = AndRHSMask.getBitWidth();
4135           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4136           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4137
4138           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4139           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4140               MaskedValueIsZero(Op0LHS, Mask)) {
4141             Value *NewNeg = Builder->CreateNeg(Op0RHS);
4142             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4143           }
4144         }
4145         break;
4146
4147       case Instruction::Shl:
4148       case Instruction::LShr:
4149         // (1 << x) & 1 --> zext(x == 0)
4150         // (1 >> x) & 1 --> zext(x == 0)
4151         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4152           Value *NewICmp =
4153             Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
4154           return new ZExtInst(NewICmp, I.getType());
4155         }
4156         break;
4157       }
4158
4159       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4160         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4161           return Res;
4162     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4163       // If this is an integer truncation or change from signed-to-unsigned, and
4164       // if the source is an and/or with immediate, transform it.  This
4165       // frequently occurs for bitfield accesses.
4166       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4167         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4168             CastOp->getNumOperands() == 2)
4169           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4170             if (CastOp->getOpcode() == Instruction::And) {
4171               // Change: and (cast (and X, C1) to T), C2
4172               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4173               // This will fold the two constants together, which may allow 
4174               // other simplifications.
4175               Value *NewCast = Builder->CreateTruncOrBitCast(
4176                 CastOp->getOperand(0), I.getType(), 
4177                 CastOp->getName()+".shrunk");
4178               // trunc_or_bitcast(C1)&C2
4179               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4180               C3 = ConstantExpr::getAnd(C3, AndRHS);
4181               return BinaryOperator::CreateAnd(NewCast, C3);
4182             } else if (CastOp->getOpcode() == Instruction::Or) {
4183               // Change: and (cast (or X, C1) to T), C2
4184               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4185               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4186               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
4187                 // trunc(C1)&C2
4188                 return ReplaceInstUsesWith(I, AndRHS);
4189             }
4190           }
4191       }
4192     }
4193
4194     // Try to fold constant and into select arguments.
4195     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4196       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4197         return R;
4198     if (isa<PHINode>(Op0))
4199       if (Instruction *NV = FoldOpIntoPhi(I))
4200         return NV;
4201   }
4202
4203   Value *Op0NotVal = dyn_castNotVal(Op0);
4204   Value *Op1NotVal = dyn_castNotVal(Op1);
4205
4206   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4207     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4208
4209   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4210   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4211     Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4212                                   I.getName()+".demorgan");
4213     return BinaryOperator::CreateNot(Or);
4214   }
4215   
4216   {
4217     Value *A = 0, *B = 0, *C = 0, *D = 0;
4218     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4219       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4220         return ReplaceInstUsesWith(I, Op1);
4221     
4222       // (A|B) & ~(A&B) -> A^B
4223       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4224         if ((A == C && B == D) || (A == D && B == C))
4225           return BinaryOperator::CreateXor(A, B);
4226       }
4227     }
4228     
4229     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4230       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4231         return ReplaceInstUsesWith(I, Op0);
4232
4233       // ~(A&B) & (A|B) -> A^B
4234       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4235         if ((A == C && B == D) || (A == D && B == C))
4236           return BinaryOperator::CreateXor(A, B);
4237       }
4238     }
4239     
4240     if (Op0->hasOneUse() &&
4241         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4242       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4243         I.swapOperands();     // Simplify below
4244         std::swap(Op0, Op1);
4245       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4246         cast<BinaryOperator>(Op0)->swapOperands();
4247         I.swapOperands();     // Simplify below
4248         std::swap(Op0, Op1);
4249       }
4250     }
4251
4252     if (Op1->hasOneUse() &&
4253         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4254       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4255         cast<BinaryOperator>(Op1)->swapOperands();
4256         std::swap(A, B);
4257       }
4258       if (A == Op0)                                // A&(A^B) -> A & ~B
4259         return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
4260     }
4261
4262     // (A&((~A)|B)) -> A&B
4263     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4264         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4265       return BinaryOperator::CreateAnd(A, Op1);
4266     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4267         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4268       return BinaryOperator::CreateAnd(A, Op0);
4269   }
4270   
4271   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4272     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4273     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4274       return R;
4275
4276     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4277       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4278         return Res;
4279   }
4280
4281   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4282   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4283     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4284       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4285         const Type *SrcTy = Op0C->getOperand(0)->getType();
4286         if (SrcTy == Op1C->getOperand(0)->getType() &&
4287             SrcTy->isIntOrIntVector() &&
4288             // Only do this if the casts both really cause code to be generated.
4289             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4290                               I.getType(), TD) &&
4291             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4292                               I.getType(), TD)) {
4293           Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4294                                             Op1C->getOperand(0), I.getName());
4295           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4296         }
4297       }
4298     
4299   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4300   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4301     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4302       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4303           SI0->getOperand(1) == SI1->getOperand(1) &&
4304           (SI0->hasOneUse() || SI1->hasOneUse())) {
4305         Value *NewOp =
4306           Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4307                              SI0->getName());
4308         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4309                                       SI1->getOperand(1));
4310       }
4311   }
4312
4313   // If and'ing two fcmp, try combine them into one.
4314   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4315     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4316       if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4317         return Res;
4318   }
4319
4320   return Changed ? &I : 0;
4321 }
4322
4323 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4324 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4325 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4326 /// the expression came from the corresponding "byte swapped" byte in some other
4327 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4328 /// we know that the expression deposits the low byte of %X into the high byte
4329 /// of the bswap result and that all other bytes are zero.  This expression is
4330 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4331 /// match.
4332 ///
4333 /// This function returns true if the match was unsuccessful and false if so.
4334 /// On entry to the function the "OverallLeftShift" is a signed integer value
4335 /// indicating the number of bytes that the subexpression is later shifted.  For
4336 /// example, if the expression is later right shifted by 16 bits, the
4337 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4338 /// byte of ByteValues is actually being set.
4339 ///
4340 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4341 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4342 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4343 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4344 /// always in the local (OverallLeftShift) coordinate space.
4345 ///
4346 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4347                               SmallVector<Value*, 8> &ByteValues) {
4348   if (Instruction *I = dyn_cast<Instruction>(V)) {
4349     // If this is an or instruction, it may be an inner node of the bswap.
4350     if (I->getOpcode() == Instruction::Or) {
4351       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4352                                ByteValues) ||
4353              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4354                                ByteValues);
4355     }
4356   
4357     // If this is a logical shift by a constant multiple of 8, recurse with
4358     // OverallLeftShift and ByteMask adjusted.
4359     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4360       unsigned ShAmt = 
4361         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4362       // Ensure the shift amount is defined and of a byte value.
4363       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4364         return true;
4365
4366       unsigned ByteShift = ShAmt >> 3;
4367       if (I->getOpcode() == Instruction::Shl) {
4368         // X << 2 -> collect(X, +2)
4369         OverallLeftShift += ByteShift;
4370         ByteMask >>= ByteShift;
4371       } else {
4372         // X >>u 2 -> collect(X, -2)
4373         OverallLeftShift -= ByteShift;
4374         ByteMask <<= ByteShift;
4375         ByteMask &= (~0U >> (32-ByteValues.size()));
4376       }
4377
4378       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4379       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4380
4381       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4382                                ByteValues);
4383     }
4384
4385     // If this is a logical 'and' with a mask that clears bytes, clear the
4386     // corresponding bytes in ByteMask.
4387     if (I->getOpcode() == Instruction::And &&
4388         isa<ConstantInt>(I->getOperand(1))) {
4389       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4390       unsigned NumBytes = ByteValues.size();
4391       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4392       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4393       
4394       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4395         // If this byte is masked out by a later operation, we don't care what
4396         // the and mask is.
4397         if ((ByteMask & (1 << i)) == 0)
4398           continue;
4399         
4400         // If the AndMask is all zeros for this byte, clear the bit.
4401         APInt MaskB = AndMask & Byte;
4402         if (MaskB == 0) {
4403           ByteMask &= ~(1U << i);
4404           continue;
4405         }
4406         
4407         // If the AndMask is not all ones for this byte, it's not a bytezap.
4408         if (MaskB != Byte)
4409           return true;
4410
4411         // Otherwise, this byte is kept.
4412       }
4413
4414       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4415                                ByteValues);
4416     }
4417   }
4418   
4419   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4420   // the input value to the bswap.  Some observations: 1) if more than one byte
4421   // is demanded from this input, then it could not be successfully assembled
4422   // into a byteswap.  At least one of the two bytes would not be aligned with
4423   // their ultimate destination.
4424   if (!isPowerOf2_32(ByteMask)) return true;
4425   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4426   
4427   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4428   // is demanded, it needs to go into byte 0 of the result.  This means that the
4429   // byte needs to be shifted until it lands in the right byte bucket.  The
4430   // shift amount depends on the position: if the byte is coming from the high
4431   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4432   // low part, it must be shifted left.
4433   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4434   if (InputByteNo < ByteValues.size()/2) {
4435     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4436       return true;
4437   } else {
4438     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4439       return true;
4440   }
4441   
4442   // If the destination byte value is already defined, the values are or'd
4443   // together, which isn't a bswap (unless it's an or of the same bits).
4444   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4445     return true;
4446   ByteValues[DestByteNo] = V;
4447   return false;
4448 }
4449
4450 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4451 /// If so, insert the new bswap intrinsic and return it.
4452 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4453   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4454   if (!ITy || ITy->getBitWidth() % 16 || 
4455       // ByteMask only allows up to 32-byte values.
4456       ITy->getBitWidth() > 32*8) 
4457     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4458   
4459   /// ByteValues - For each byte of the result, we keep track of which value
4460   /// defines each byte.
4461   SmallVector<Value*, 8> ByteValues;
4462   ByteValues.resize(ITy->getBitWidth()/8);
4463     
4464   // Try to find all the pieces corresponding to the bswap.
4465   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4466   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4467     return 0;
4468   
4469   // Check to see if all of the bytes come from the same value.
4470   Value *V = ByteValues[0];
4471   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4472   
4473   // Check to make sure that all of the bytes come from the same value.
4474   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4475     if (ByteValues[i] != V)
4476       return 0;
4477   const Type *Tys[] = { ITy };
4478   Module *M = I.getParent()->getParent()->getParent();
4479   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4480   return CallInst::Create(F, V);
4481 }
4482
4483 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4484 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4485 /// we can simplify this expression to "cond ? C : D or B".
4486 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4487                                          Value *C, Value *D,
4488                                          LLVMContext *Context) {
4489   // If A is not a select of -1/0, this cannot match.
4490   Value *Cond = 0;
4491   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4492     return 0;
4493
4494   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4495   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4496     return SelectInst::Create(Cond, C, B);
4497   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4498     return SelectInst::Create(Cond, C, B);
4499   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4500   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4501     return SelectInst::Create(Cond, C, D);
4502   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4503     return SelectInst::Create(Cond, C, D);
4504   return 0;
4505 }
4506
4507 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4508 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4509                                          ICmpInst *LHS, ICmpInst *RHS) {
4510   Value *Val, *Val2;
4511   ConstantInt *LHSCst, *RHSCst;
4512   ICmpInst::Predicate LHSCC, RHSCC;
4513   
4514   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4515   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4516              m_ConstantInt(LHSCst))) ||
4517       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4518              m_ConstantInt(RHSCst))))
4519     return 0;
4520   
4521   // From here on, we only handle:
4522   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4523   if (Val != Val2) return 0;
4524   
4525   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4526   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4527       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4528       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4529       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4530     return 0;
4531   
4532   // We can't fold (ugt x, C) | (sgt x, C2).
4533   if (!PredicatesFoldable(LHSCC, RHSCC))
4534     return 0;
4535   
4536   // Ensure that the larger constant is on the RHS.
4537   bool ShouldSwap;
4538   if (CmpInst::isSigned(LHSCC) ||
4539       (ICmpInst::isEquality(LHSCC) && 
4540        CmpInst::isSigned(RHSCC)))
4541     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4542   else
4543     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4544   
4545   if (ShouldSwap) {
4546     std::swap(LHS, RHS);
4547     std::swap(LHSCst, RHSCst);
4548     std::swap(LHSCC, RHSCC);
4549   }
4550   
4551   // At this point, we know we have have two icmp instructions
4552   // comparing a value against two constants and or'ing the result
4553   // together.  Because of the above check, we know that we only have
4554   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4555   // FoldICmpLogical check above), that the two constants are not
4556   // equal.
4557   assert(LHSCst != RHSCst && "Compares not folded above?");
4558
4559   switch (LHSCC) {
4560   default: llvm_unreachable("Unknown integer condition code!");
4561   case ICmpInst::ICMP_EQ:
4562     switch (RHSCC) {
4563     default: llvm_unreachable("Unknown integer condition code!");
4564     case ICmpInst::ICMP_EQ:
4565       if (LHSCst == SubOne(RHSCst)) {
4566         // (X == 13 | X == 14) -> X-13 <u 2
4567         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4568         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
4569         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4570         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4571       }
4572       break;                         // (X == 13 | X == 15) -> no change
4573     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4574     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4575       break;
4576     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4577     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4578     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4579       return ReplaceInstUsesWith(I, RHS);
4580     }
4581     break;
4582   case ICmpInst::ICMP_NE:
4583     switch (RHSCC) {
4584     default: llvm_unreachable("Unknown integer condition code!");
4585     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4586     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4587     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4588       return ReplaceInstUsesWith(I, LHS);
4589     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4590     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4591     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4592       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4593     }
4594     break;
4595   case ICmpInst::ICMP_ULT:
4596     switch (RHSCC) {
4597     default: llvm_unreachable("Unknown integer condition code!");
4598     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4599       break;
4600     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4601       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4602       // this can cause overflow.
4603       if (RHSCst->isMaxValue(false))
4604         return ReplaceInstUsesWith(I, LHS);
4605       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4606                              false, false, I);
4607     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4608       break;
4609     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4610     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4611       return ReplaceInstUsesWith(I, RHS);
4612     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4613       break;
4614     }
4615     break;
4616   case ICmpInst::ICMP_SLT:
4617     switch (RHSCC) {
4618     default: llvm_unreachable("Unknown integer condition code!");
4619     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4620       break;
4621     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4622       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4623       // this can cause overflow.
4624       if (RHSCst->isMaxValue(true))
4625         return ReplaceInstUsesWith(I, LHS);
4626       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4627                              true, false, I);
4628     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4629       break;
4630     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4631     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4632       return ReplaceInstUsesWith(I, RHS);
4633     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4634       break;
4635     }
4636     break;
4637   case ICmpInst::ICMP_UGT:
4638     switch (RHSCC) {
4639     default: llvm_unreachable("Unknown integer condition code!");
4640     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4641     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4642       return ReplaceInstUsesWith(I, LHS);
4643     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4644       break;
4645     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4646     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4647       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4648     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4649       break;
4650     }
4651     break;
4652   case ICmpInst::ICMP_SGT:
4653     switch (RHSCC) {
4654     default: llvm_unreachable("Unknown integer condition code!");
4655     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4656     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4657       return ReplaceInstUsesWith(I, LHS);
4658     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4659       break;
4660     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4661     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4662       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4663     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4664       break;
4665     }
4666     break;
4667   }
4668   return 0;
4669 }
4670
4671 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4672                                          FCmpInst *RHS) {
4673   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4674       RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4675       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4676     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4677       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4678         // If either of the constants are nans, then the whole thing returns
4679         // true.
4680         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4681           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4682         
4683         // Otherwise, no need to compare the two constants, compare the
4684         // rest.
4685         return new FCmpInst(FCmpInst::FCMP_UNO,
4686                             LHS->getOperand(0), RHS->getOperand(0));
4687       }
4688     
4689     // Handle vector zeros.  This occurs because the canonical form of
4690     // "fcmp uno x,x" is "fcmp uno x, 0".
4691     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4692         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4693       return new FCmpInst(FCmpInst::FCMP_UNO,
4694                           LHS->getOperand(0), RHS->getOperand(0));
4695     
4696     return 0;
4697   }
4698   
4699   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4700   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4701   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4702   
4703   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4704     // Swap RHS operands to match LHS.
4705     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4706     std::swap(Op1LHS, Op1RHS);
4707   }
4708   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4709     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4710     if (Op0CC == Op1CC)
4711       return new FCmpInst((FCmpInst::Predicate)Op0CC,
4712                           Op0LHS, Op0RHS);
4713     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
4714       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4715     if (Op0CC == FCmpInst::FCMP_FALSE)
4716       return ReplaceInstUsesWith(I, RHS);
4717     if (Op1CC == FCmpInst::FCMP_FALSE)
4718       return ReplaceInstUsesWith(I, LHS);
4719     bool Op0Ordered;
4720     bool Op1Ordered;
4721     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4722     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4723     if (Op0Ordered == Op1Ordered) {
4724       // If both are ordered or unordered, return a new fcmp with
4725       // or'ed predicates.
4726       Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4727                                Op0LHS, Op0RHS, Context);
4728       if (Instruction *I = dyn_cast<Instruction>(RV))
4729         return I;
4730       // Otherwise, it's a constant boolean value...
4731       return ReplaceInstUsesWith(I, RV);
4732     }
4733   }
4734   return 0;
4735 }
4736
4737 /// FoldOrWithConstants - This helper function folds:
4738 ///
4739 ///     ((A | B) & C1) | (B & C2)
4740 ///
4741 /// into:
4742 /// 
4743 ///     (A & C1) | B
4744 ///
4745 /// when the XOR of the two constants is "all ones" (-1).
4746 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4747                                                Value *A, Value *B, Value *C) {
4748   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4749   if (!CI1) return 0;
4750
4751   Value *V1 = 0;
4752   ConstantInt *CI2 = 0;
4753   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4754
4755   APInt Xor = CI1->getValue() ^ CI2->getValue();
4756   if (!Xor.isAllOnesValue()) return 0;
4757
4758   if (V1 == A || V1 == B) {
4759     Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
4760     return BinaryOperator::CreateOr(NewOp, V1);
4761   }
4762
4763   return 0;
4764 }
4765
4766 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4767   bool Changed = SimplifyCommutative(I);
4768   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4769
4770   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4771     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4772
4773   // or X, X = X
4774   if (Op0 == Op1)
4775     return ReplaceInstUsesWith(I, Op0);
4776
4777   // See if we can simplify any instructions used by the instruction whose sole 
4778   // purpose is to compute bits we don't care about.
4779   if (SimplifyDemandedInstructionBits(I))
4780     return &I;
4781   if (isa<VectorType>(I.getType())) {
4782     if (isa<ConstantAggregateZero>(Op1)) {
4783       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4784     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4785       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4786         return ReplaceInstUsesWith(I, I.getOperand(1));
4787     }
4788   }
4789
4790   // or X, -1 == -1
4791   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4792     ConstantInt *C1 = 0; Value *X = 0;
4793     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4794     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
4795         isOnlyUse(Op0)) {
4796       Value *Or = Builder->CreateOr(X, RHS);
4797       Or->takeName(Op0);
4798       return BinaryOperator::CreateAnd(Or, 
4799                ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
4800     }
4801
4802     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4803     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
4804         isOnlyUse(Op0)) {
4805       Value *Or = Builder->CreateOr(X, RHS);
4806       Or->takeName(Op0);
4807       return BinaryOperator::CreateXor(Or,
4808                  ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
4809     }
4810
4811     // Try to fold constant and into select arguments.
4812     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4813       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4814         return R;
4815     if (isa<PHINode>(Op0))
4816       if (Instruction *NV = FoldOpIntoPhi(I))
4817         return NV;
4818   }
4819
4820   Value *A = 0, *B = 0;
4821   ConstantInt *C1 = 0, *C2 = 0;
4822
4823   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4824     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4825       return ReplaceInstUsesWith(I, Op1);
4826   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4827     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4828       return ReplaceInstUsesWith(I, Op0);
4829
4830   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4831   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4832   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4833       match(Op1, m_Or(m_Value(), m_Value())) ||
4834       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4835        match(Op1, m_Shift(m_Value(), m_Value())))) {
4836     if (Instruction *BSwap = MatchBSwap(I))
4837       return BSwap;
4838   }
4839   
4840   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4841   if (Op0->hasOneUse() &&
4842       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4843       MaskedValueIsZero(Op1, C1->getValue())) {
4844     Value *NOr = Builder->CreateOr(A, Op1);
4845     NOr->takeName(Op0);
4846     return BinaryOperator::CreateXor(NOr, C1);
4847   }
4848
4849   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4850   if (Op1->hasOneUse() &&
4851       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4852       MaskedValueIsZero(Op0, C1->getValue())) {
4853     Value *NOr = Builder->CreateOr(A, Op0);
4854     NOr->takeName(Op0);
4855     return BinaryOperator::CreateXor(NOr, C1);
4856   }
4857
4858   // (A & C)|(B & D)
4859   Value *C = 0, *D = 0;
4860   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4861       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4862     Value *V1 = 0, *V2 = 0, *V3 = 0;
4863     C1 = dyn_cast<ConstantInt>(C);
4864     C2 = dyn_cast<ConstantInt>(D);
4865     if (C1 && C2) {  // (A & C1)|(B & C2)
4866       // If we have: ((V + N) & C1) | (V & C2)
4867       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4868       // replace with V+N.
4869       if (C1->getValue() == ~C2->getValue()) {
4870         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4871             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4872           // Add commutes, try both ways.
4873           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4874             return ReplaceInstUsesWith(I, A);
4875           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4876             return ReplaceInstUsesWith(I, A);
4877         }
4878         // Or commutes, try both ways.
4879         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4880             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4881           // Add commutes, try both ways.
4882           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4883             return ReplaceInstUsesWith(I, B);
4884           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4885             return ReplaceInstUsesWith(I, B);
4886         }
4887       }
4888       V1 = 0; V2 = 0; V3 = 0;
4889     }
4890     
4891     // Check to see if we have any common things being and'ed.  If so, find the
4892     // terms for V1 & (V2|V3).
4893     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4894       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4895         V1 = A, V2 = C, V3 = D;
4896       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4897         V1 = A, V2 = B, V3 = C;
4898       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4899         V1 = C, V2 = A, V3 = D;
4900       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4901         V1 = C, V2 = A, V3 = B;
4902       
4903       if (V1) {
4904         Value *Or = Builder->CreateOr(V2, V3, "tmp");
4905         return BinaryOperator::CreateAnd(V1, Or);
4906       }
4907     }
4908
4909     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4910     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4911       return Match;
4912     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4913       return Match;
4914     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4915       return Match;
4916     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4917       return Match;
4918
4919     // ((A&~B)|(~A&B)) -> A^B
4920     if ((match(C, m_Not(m_Specific(D))) &&
4921          match(B, m_Not(m_Specific(A)))))
4922       return BinaryOperator::CreateXor(A, D);
4923     // ((~B&A)|(~A&B)) -> A^B
4924     if ((match(A, m_Not(m_Specific(D))) &&
4925          match(B, m_Not(m_Specific(C)))))
4926       return BinaryOperator::CreateXor(C, D);
4927     // ((A&~B)|(B&~A)) -> A^B
4928     if ((match(C, m_Not(m_Specific(B))) &&
4929          match(D, m_Not(m_Specific(A)))))
4930       return BinaryOperator::CreateXor(A, B);
4931     // ((~B&A)|(B&~A)) -> A^B
4932     if ((match(A, m_Not(m_Specific(B))) &&
4933          match(D, m_Not(m_Specific(C)))))
4934       return BinaryOperator::CreateXor(C, B);
4935   }
4936   
4937   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4938   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4939     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4940       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4941           SI0->getOperand(1) == SI1->getOperand(1) &&
4942           (SI0->hasOneUse() || SI1->hasOneUse())) {
4943         Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4944                                          SI0->getName());
4945         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4946                                       SI1->getOperand(1));
4947       }
4948   }
4949
4950   // ((A|B)&1)|(B&-2) -> (A&1) | B
4951   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4952       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4953     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4954     if (Ret) return Ret;
4955   }
4956   // (B&-2)|((A|B)&1) -> (A&1) | B
4957   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4958       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4959     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4960     if (Ret) return Ret;
4961   }
4962
4963   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4964     if (A == Op1)   // ~A | A == -1
4965       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4966   } else {
4967     A = 0;
4968   }
4969   // Note, A is still live here!
4970   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4971     if (Op0 == B)
4972       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4973
4974     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4975     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4976       Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
4977       return BinaryOperator::CreateNot(And);
4978     }
4979   }
4980
4981   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4982   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4983     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4984       return R;
4985
4986     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4987       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4988         return Res;
4989   }
4990     
4991   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4992   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4993     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4994       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4995         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4996             !isa<ICmpInst>(Op1C->getOperand(0))) {
4997           const Type *SrcTy = Op0C->getOperand(0)->getType();
4998           if (SrcTy == Op1C->getOperand(0)->getType() &&
4999               SrcTy->isIntOrIntVector() &&
5000               // Only do this if the casts both really cause code to be
5001               // generated.
5002               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5003                                 I.getType(), TD) &&
5004               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5005                                 I.getType(), TD)) {
5006             Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5007                                              Op1C->getOperand(0), I.getName());
5008             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5009           }
5010         }
5011       }
5012   }
5013   
5014     
5015   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
5016   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
5017     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5018       if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5019         return Res;
5020   }
5021
5022   return Changed ? &I : 0;
5023 }
5024
5025 namespace {
5026
5027 // XorSelf - Implements: X ^ X --> 0
5028 struct XorSelf {
5029   Value *RHS;
5030   XorSelf(Value *rhs) : RHS(rhs) {}
5031   bool shouldApply(Value *LHS) const { return LHS == RHS; }
5032   Instruction *apply(BinaryOperator &Xor) const {
5033     return &Xor;
5034   }
5035 };
5036
5037 }
5038
5039 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5040   bool Changed = SimplifyCommutative(I);
5041   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5042
5043   if (isa<UndefValue>(Op1)) {
5044     if (isa<UndefValue>(Op0))
5045       // Handle undef ^ undef -> 0 special case. This is a common
5046       // idiom (misuse).
5047       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5048     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5049   }
5050
5051   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5052   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
5053     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5054     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5055   }
5056   
5057   // See if we can simplify any instructions used by the instruction whose sole 
5058   // purpose is to compute bits we don't care about.
5059   if (SimplifyDemandedInstructionBits(I))
5060     return &I;
5061   if (isa<VectorType>(I.getType()))
5062     if (isa<ConstantAggregateZero>(Op1))
5063       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5064
5065   // Is this a ~ operation?
5066   if (Value *NotOp = dyn_castNotVal(&I)) {
5067     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5068     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5069     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5070       if (Op0I->getOpcode() == Instruction::And || 
5071           Op0I->getOpcode() == Instruction::Or) {
5072         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5073         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5074           Value *NotY =
5075             Builder->CreateNot(Op0I->getOperand(1),
5076                                Op0I->getOperand(1)->getName()+".not");
5077           if (Op0I->getOpcode() == Instruction::And)
5078             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5079           return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5080         }
5081       }
5082     }
5083   }
5084   
5085   
5086   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5087     if (RHS->isOne() && Op0->hasOneUse()) {
5088       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5089       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5090         return new ICmpInst(ICI->getInversePredicate(),
5091                             ICI->getOperand(0), ICI->getOperand(1));
5092
5093       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5094         return new FCmpInst(FCI->getInversePredicate(),
5095                             FCI->getOperand(0), FCI->getOperand(1));
5096     }
5097
5098     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5099     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5100       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5101         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5102           Instruction::CastOps Opcode = Op0C->getOpcode();
5103           if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5104               (RHS == ConstantExpr::getCast(Opcode, 
5105                                             ConstantInt::getTrue(*Context),
5106                                             Op0C->getDestTy()))) {
5107             CI->setPredicate(CI->getInversePredicate());
5108             return CastInst::Create(Opcode, CI, Op0C->getType());
5109           }
5110         }
5111       }
5112     }
5113
5114     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5115       // ~(c-X) == X-c-1 == X+(-c-1)
5116       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5117         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5118           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5119           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5120                                       ConstantInt::get(I.getType(), 1));
5121           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5122         }
5123           
5124       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5125         if (Op0I->getOpcode() == Instruction::Add) {
5126           // ~(X-c) --> (-c-1)-X
5127           if (RHS->isAllOnesValue()) {
5128             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5129             return BinaryOperator::CreateSub(
5130                            ConstantExpr::getSub(NegOp0CI,
5131                                       ConstantInt::get(I.getType(), 1)),
5132                                       Op0I->getOperand(0));
5133           } else if (RHS->getValue().isSignBit()) {
5134             // (X + C) ^ signbit -> (X + C + signbit)
5135             Constant *C = ConstantInt::get(*Context,
5136                                            RHS->getValue() + Op0CI->getValue());
5137             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5138
5139           }
5140         } else if (Op0I->getOpcode() == Instruction::Or) {
5141           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5142           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5143             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5144             // Anything in both C1 and C2 is known to be zero, remove it from
5145             // NewRHS.
5146             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5147             NewRHS = ConstantExpr::getAnd(NewRHS, 
5148                                        ConstantExpr::getNot(CommonBits));
5149             Worklist.Add(Op0I);
5150             I.setOperand(0, Op0I->getOperand(0));
5151             I.setOperand(1, NewRHS);
5152             return &I;
5153           }
5154         }
5155       }
5156     }
5157
5158     // Try to fold constant and into select arguments.
5159     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5160       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5161         return R;
5162     if (isa<PHINode>(Op0))
5163       if (Instruction *NV = FoldOpIntoPhi(I))
5164         return NV;
5165   }
5166
5167   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
5168     if (X == Op1)
5169       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5170
5171   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5172     if (X == Op0)
5173       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5174
5175   
5176   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5177   if (Op1I) {
5178     Value *A, *B;
5179     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5180       if (A == Op0) {              // B^(B|A) == (A|B)^B
5181         Op1I->swapOperands();
5182         I.swapOperands();
5183         std::swap(Op0, Op1);
5184       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5185         I.swapOperands();     // Simplified below.
5186         std::swap(Op0, Op1);
5187       }
5188     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5189       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5190     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5191       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5192     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && 
5193                Op1I->hasOneUse()){
5194       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5195         Op1I->swapOperands();
5196         std::swap(A, B);
5197       }
5198       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5199         I.swapOperands();     // Simplified below.
5200         std::swap(Op0, Op1);
5201       }
5202     }
5203   }
5204   
5205   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5206   if (Op0I) {
5207     Value *A, *B;
5208     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5209         Op0I->hasOneUse()) {
5210       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5211         std::swap(A, B);
5212       if (B == Op1)                                  // (A|B)^B == A & ~B
5213         return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
5214     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5215       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5216     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5217       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5218     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && 
5219                Op0I->hasOneUse()){
5220       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5221         std::swap(A, B);
5222       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5223           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5224         return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
5225       }
5226     }
5227   }
5228   
5229   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5230   if (Op0I && Op1I && Op0I->isShift() && 
5231       Op0I->getOpcode() == Op1I->getOpcode() && 
5232       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5233       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5234     Value *NewOp =
5235       Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5236                          Op0I->getName());
5237     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5238                                   Op1I->getOperand(1));
5239   }
5240     
5241   if (Op0I && Op1I) {
5242     Value *A, *B, *C, *D;
5243     // (A & B)^(A | B) -> A ^ B
5244     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5245         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5246       if ((A == C && B == D) || (A == D && B == C)) 
5247         return BinaryOperator::CreateXor(A, B);
5248     }
5249     // (A | B)^(A & B) -> A ^ B
5250     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5251         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5252       if ((A == C && B == D) || (A == D && B == C)) 
5253         return BinaryOperator::CreateXor(A, B);
5254     }
5255     
5256     // (A & B)^(C & D)
5257     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5258         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5259         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5260       // (X & Y)^(X & Y) -> (Y^Z) & X
5261       Value *X = 0, *Y = 0, *Z = 0;
5262       if (A == C)
5263         X = A, Y = B, Z = D;
5264       else if (A == D)
5265         X = A, Y = B, Z = C;
5266       else if (B == C)
5267         X = B, Y = A, Z = D;
5268       else if (B == D)
5269         X = B, Y = A, Z = C;
5270       
5271       if (X) {
5272         Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
5273         return BinaryOperator::CreateAnd(NewOp, X);
5274       }
5275     }
5276   }
5277     
5278   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5279   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5280     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5281       return R;
5282
5283   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5284   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5285     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5286       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5287         const Type *SrcTy = Op0C->getOperand(0)->getType();
5288         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5289             // Only do this if the casts both really cause code to be generated.
5290             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5291                               I.getType(), TD) &&
5292             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5293                               I.getType(), TD)) {
5294           Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5295                                             Op1C->getOperand(0), I.getName());
5296           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5297         }
5298       }
5299   }
5300
5301   return Changed ? &I : 0;
5302 }
5303
5304 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5305                                    LLVMContext *Context) {
5306   return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5307 }
5308
5309 static bool HasAddOverflow(ConstantInt *Result,
5310                            ConstantInt *In1, ConstantInt *In2,
5311                            bool IsSigned) {
5312   if (IsSigned)
5313     if (In2->getValue().isNegative())
5314       return Result->getValue().sgt(In1->getValue());
5315     else
5316       return Result->getValue().slt(In1->getValue());
5317   else
5318     return Result->getValue().ult(In1->getValue());
5319 }
5320
5321 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5322 /// overflowed for this type.
5323 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5324                             Constant *In2, LLVMContext *Context,
5325                             bool IsSigned = false) {
5326   Result = ConstantExpr::getAdd(In1, In2);
5327
5328   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5329     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5330       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5331       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5332                          ExtractElement(In1, Idx, Context),
5333                          ExtractElement(In2, Idx, Context),
5334                          IsSigned))
5335         return true;
5336     }
5337     return false;
5338   }
5339
5340   return HasAddOverflow(cast<ConstantInt>(Result),
5341                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5342                         IsSigned);
5343 }
5344
5345 static bool HasSubOverflow(ConstantInt *Result,
5346                            ConstantInt *In1, ConstantInt *In2,
5347                            bool IsSigned) {
5348   if (IsSigned)
5349     if (In2->getValue().isNegative())
5350       return Result->getValue().slt(In1->getValue());
5351     else
5352       return Result->getValue().sgt(In1->getValue());
5353   else
5354     return Result->getValue().ugt(In1->getValue());
5355 }
5356
5357 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5358 /// overflowed for this type.
5359 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5360                             Constant *In2, LLVMContext *Context,
5361                             bool IsSigned = false) {
5362   Result = ConstantExpr::getSub(In1, In2);
5363
5364   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5365     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5366       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5367       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5368                          ExtractElement(In1, Idx, Context),
5369                          ExtractElement(In2, Idx, Context),
5370                          IsSigned))
5371         return true;
5372     }
5373     return false;
5374   }
5375
5376   return HasSubOverflow(cast<ConstantInt>(Result),
5377                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5378                         IsSigned);
5379 }
5380
5381 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5382 /// code necessary to compute the offset from the base pointer (without adding
5383 /// in the base pointer).  Return the result as a signed integer of intptr size.
5384 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5385   TargetData &TD = *IC.getTargetData();
5386   gep_type_iterator GTI = gep_type_begin(GEP);
5387   const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
5388   Value *Result = Constant::getNullValue(IntPtrTy);
5389
5390   // Build a mask for high order bits.
5391   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5392   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5393
5394   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5395        ++i, ++GTI) {
5396     Value *Op = *i;
5397     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5398     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5399       if (OpC->isZero()) continue;
5400       
5401       // Handle a struct index, which adds its field offset to the pointer.
5402       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5403         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5404         
5405         Result = IC.Builder->CreateAdd(Result,
5406                                        ConstantInt::get(IntPtrTy, Size),
5407                                        GEP->getName()+".offs");
5408         continue;
5409       }
5410       
5411       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5412       Constant *OC =
5413               ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5414       Scale = ConstantExpr::getMul(OC, Scale);
5415       // Emit an add instruction.
5416       Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
5417       continue;
5418     }
5419     // Convert to correct type.
5420     if (Op->getType() != IntPtrTy)
5421       Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
5422     if (Size != 1) {
5423       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5424       // We'll let instcombine(mul) convert this to a shl if possible.
5425       Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
5426     }
5427
5428     // Emit an add instruction.
5429     Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
5430   }
5431   return Result;
5432 }
5433
5434
5435 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5436 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
5437 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
5438 /// be complex, and scales are involved.  The above expression would also be
5439 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5440 /// This later form is less amenable to optimization though, and we are allowed
5441 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5442 ///
5443 /// If we can't emit an optimized form for this expression, this returns null.
5444 /// 
5445 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5446                                           InstCombiner &IC) {
5447   TargetData &TD = *IC.getTargetData();
5448   gep_type_iterator GTI = gep_type_begin(GEP);
5449
5450   // Check to see if this gep only has a single variable index.  If so, and if
5451   // any constant indices are a multiple of its scale, then we can compute this
5452   // in terms of the scale of the variable index.  For example, if the GEP
5453   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5454   // because the expression will cross zero at the same point.
5455   unsigned i, e = GEP->getNumOperands();
5456   int64_t Offset = 0;
5457   for (i = 1; i != e; ++i, ++GTI) {
5458     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5459       // Compute the aggregate offset of constant indices.
5460       if (CI->isZero()) continue;
5461
5462       // Handle a struct index, which adds its field offset to the pointer.
5463       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5464         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5465       } else {
5466         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5467         Offset += Size*CI->getSExtValue();
5468       }
5469     } else {
5470       // Found our variable index.
5471       break;
5472     }
5473   }
5474   
5475   // If there are no variable indices, we must have a constant offset, just
5476   // evaluate it the general way.
5477   if (i == e) return 0;
5478   
5479   Value *VariableIdx = GEP->getOperand(i);
5480   // Determine the scale factor of the variable element.  For example, this is
5481   // 4 if the variable index is into an array of i32.
5482   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5483   
5484   // Verify that there are no other variable indices.  If so, emit the hard way.
5485   for (++i, ++GTI; i != e; ++i, ++GTI) {
5486     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5487     if (!CI) return 0;
5488    
5489     // Compute the aggregate offset of constant indices.
5490     if (CI->isZero()) continue;
5491     
5492     // Handle a struct index, which adds its field offset to the pointer.
5493     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5494       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5495     } else {
5496       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5497       Offset += Size*CI->getSExtValue();
5498     }
5499   }
5500   
5501   // Okay, we know we have a single variable index, which must be a
5502   // pointer/array/vector index.  If there is no offset, life is simple, return
5503   // the index.
5504   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5505   if (Offset == 0) {
5506     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5507     // we don't need to bother extending: the extension won't affect where the
5508     // computation crosses zero.
5509     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5510       VariableIdx = new TruncInst(VariableIdx, 
5511                                   TD.getIntPtrType(VariableIdx->getContext()),
5512                                   VariableIdx->getName(), &I);
5513     return VariableIdx;
5514   }
5515   
5516   // Otherwise, there is an index.  The computation we will do will be modulo
5517   // the pointer size, so get it.
5518   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5519   
5520   Offset &= PtrSizeMask;
5521   VariableScale &= PtrSizeMask;
5522
5523   // To do this transformation, any constant index must be a multiple of the
5524   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5525   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5526   // multiple of the variable scale.
5527   int64_t NewOffs = Offset / (int64_t)VariableScale;
5528   if (Offset != NewOffs*(int64_t)VariableScale)
5529     return 0;
5530
5531   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5532   const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
5533   if (VariableIdx->getType() != IntPtrTy)
5534     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5535                                               true /*SExt*/, 
5536                                               VariableIdx->getName(), &I);
5537   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5538   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5539 }
5540
5541
5542 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5543 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5544 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
5545                                        ICmpInst::Predicate Cond,
5546                                        Instruction &I) {
5547   // Look through bitcasts.
5548   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5549     RHS = BCI->getOperand(0);
5550
5551   Value *PtrBase = GEPLHS->getOperand(0);
5552   if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
5553     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5554     // This transformation (ignoring the base and scales) is valid because we
5555     // know pointers can't overflow since the gep is inbounds.  See if we can
5556     // output an optimized form.
5557     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5558     
5559     // If not, synthesize the offset the hard way.
5560     if (Offset == 0)
5561       Offset = EmitGEPOffset(GEPLHS, I, *this);
5562     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5563                         Constant::getNullValue(Offset->getType()));
5564   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
5565     // If the base pointers are different, but the indices are the same, just
5566     // compare the base pointer.
5567     if (PtrBase != GEPRHS->getOperand(0)) {
5568       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5569       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5570                         GEPRHS->getOperand(0)->getType();
5571       if (IndicesTheSame)
5572         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5573           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5574             IndicesTheSame = false;
5575             break;
5576           }
5577
5578       // If all indices are the same, just compare the base pointers.
5579       if (IndicesTheSame)
5580         return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5581                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5582
5583       // Otherwise, the base pointers are different and the indices are
5584       // different, bail out.
5585       return 0;
5586     }
5587
5588     // If one of the GEPs has all zero indices, recurse.
5589     bool AllZeros = true;
5590     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5591       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5592           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5593         AllZeros = false;
5594         break;
5595       }
5596     if (AllZeros)
5597       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5598                           ICmpInst::getSwappedPredicate(Cond), I);
5599
5600     // If the other GEP has all zero indices, recurse.
5601     AllZeros = true;
5602     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5603       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5604           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5605         AllZeros = false;
5606         break;
5607       }
5608     if (AllZeros)
5609       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5610
5611     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5612       // If the GEPs only differ by one index, compare it.
5613       unsigned NumDifferences = 0;  // Keep track of # differences.
5614       unsigned DiffOperand = 0;     // The operand that differs.
5615       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5616         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5617           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5618                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5619             // Irreconcilable differences.
5620             NumDifferences = 2;
5621             break;
5622           } else {
5623             if (NumDifferences++) break;
5624             DiffOperand = i;
5625           }
5626         }
5627
5628       if (NumDifferences == 0)   // SAME GEP?
5629         return ReplaceInstUsesWith(I, // No comparison is needed here.
5630                                    ConstantInt::get(Type::getInt1Ty(*Context),
5631                                              ICmpInst::isTrueWhenEqual(Cond)));
5632
5633       else if (NumDifferences == 1) {
5634         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5635         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5636         // Make sure we do a signed comparison here.
5637         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5638       }
5639     }
5640
5641     // Only lower this if the icmp is the only user of the GEP or if we expect
5642     // the result to fold to a constant!
5643     if (TD &&
5644         (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5645         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5646       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5647       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5648       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5649       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5650     }
5651   }
5652   return 0;
5653 }
5654
5655 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5656 ///
5657 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5658                                                 Instruction *LHSI,
5659                                                 Constant *RHSC) {
5660   if (!isa<ConstantFP>(RHSC)) return 0;
5661   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5662   
5663   // Get the width of the mantissa.  We don't want to hack on conversions that
5664   // might lose information from the integer, e.g. "i64 -> float"
5665   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5666   if (MantissaWidth == -1) return 0;  // Unknown.
5667   
5668   // Check to see that the input is converted from an integer type that is small
5669   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5670   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5671   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5672   
5673   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5674   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5675   if (LHSUnsigned)
5676     ++InputSize;
5677   
5678   // If the conversion would lose info, don't hack on this.
5679   if ((int)InputSize > MantissaWidth)
5680     return 0;
5681   
5682   // Otherwise, we can potentially simplify the comparison.  We know that it
5683   // will always come through as an integer value and we know the constant is
5684   // not a NAN (it would have been previously simplified).
5685   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5686   
5687   ICmpInst::Predicate Pred;
5688   switch (I.getPredicate()) {
5689   default: llvm_unreachable("Unexpected predicate!");
5690   case FCmpInst::FCMP_UEQ:
5691   case FCmpInst::FCMP_OEQ:
5692     Pred = ICmpInst::ICMP_EQ;
5693     break;
5694   case FCmpInst::FCMP_UGT:
5695   case FCmpInst::FCMP_OGT:
5696     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5697     break;
5698   case FCmpInst::FCMP_UGE:
5699   case FCmpInst::FCMP_OGE:
5700     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5701     break;
5702   case FCmpInst::FCMP_ULT:
5703   case FCmpInst::FCMP_OLT:
5704     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5705     break;
5706   case FCmpInst::FCMP_ULE:
5707   case FCmpInst::FCMP_OLE:
5708     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5709     break;
5710   case FCmpInst::FCMP_UNE:
5711   case FCmpInst::FCMP_ONE:
5712     Pred = ICmpInst::ICMP_NE;
5713     break;
5714   case FCmpInst::FCMP_ORD:
5715     return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5716   case FCmpInst::FCMP_UNO:
5717     return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5718   }
5719   
5720   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5721   
5722   // Now we know that the APFloat is a normal number, zero or inf.
5723   
5724   // See if the FP constant is too large for the integer.  For example,
5725   // comparing an i8 to 300.0.
5726   unsigned IntWidth = IntTy->getScalarSizeInBits();
5727   
5728   if (!LHSUnsigned) {
5729     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5730     // and large values.
5731     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5732     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5733                           APFloat::rmNearestTiesToEven);
5734     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5735       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5736           Pred == ICmpInst::ICMP_SLE)
5737         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5738       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5739     }
5740   } else {
5741     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5742     // +INF and large values.
5743     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5744     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5745                           APFloat::rmNearestTiesToEven);
5746     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5747       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5748           Pred == ICmpInst::ICMP_ULE)
5749         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5750       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5751     }
5752   }
5753   
5754   if (!LHSUnsigned) {
5755     // See if the RHS value is < SignedMin.
5756     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5757     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5758                           APFloat::rmNearestTiesToEven);
5759     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5760       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5761           Pred == ICmpInst::ICMP_SGE)
5762         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5763       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5764     }
5765   }
5766
5767   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5768   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5769   // casting the FP value to the integer value and back, checking for equality.
5770   // Don't do this for zero, because -0.0 is not fractional.
5771   Constant *RHSInt = LHSUnsigned
5772     ? ConstantExpr::getFPToUI(RHSC, IntTy)
5773     : ConstantExpr::getFPToSI(RHSC, IntTy);
5774   if (!RHS.isZero()) {
5775     bool Equal = LHSUnsigned
5776       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5777       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5778     if (!Equal) {
5779       // If we had a comparison against a fractional value, we have to adjust
5780       // the compare predicate and sometimes the value.  RHSC is rounded towards
5781       // zero at this point.
5782       switch (Pred) {
5783       default: llvm_unreachable("Unexpected integer comparison!");
5784       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5785         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5786       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5787         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5788       case ICmpInst::ICMP_ULE:
5789         // (float)int <= 4.4   --> int <= 4
5790         // (float)int <= -4.4  --> false
5791         if (RHS.isNegative())
5792           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5793         break;
5794       case ICmpInst::ICMP_SLE:
5795         // (float)int <= 4.4   --> int <= 4
5796         // (float)int <= -4.4  --> int < -4
5797         if (RHS.isNegative())
5798           Pred = ICmpInst::ICMP_SLT;
5799         break;
5800       case ICmpInst::ICMP_ULT:
5801         // (float)int < -4.4   --> false
5802         // (float)int < 4.4    --> int <= 4
5803         if (RHS.isNegative())
5804           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5805         Pred = ICmpInst::ICMP_ULE;
5806         break;
5807       case ICmpInst::ICMP_SLT:
5808         // (float)int < -4.4   --> int < -4
5809         // (float)int < 4.4    --> int <= 4
5810         if (!RHS.isNegative())
5811           Pred = ICmpInst::ICMP_SLE;
5812         break;
5813       case ICmpInst::ICMP_UGT:
5814         // (float)int > 4.4    --> int > 4
5815         // (float)int > -4.4   --> true
5816         if (RHS.isNegative())
5817           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5818         break;
5819       case ICmpInst::ICMP_SGT:
5820         // (float)int > 4.4    --> int > 4
5821         // (float)int > -4.4   --> int >= -4
5822         if (RHS.isNegative())
5823           Pred = ICmpInst::ICMP_SGE;
5824         break;
5825       case ICmpInst::ICMP_UGE:
5826         // (float)int >= -4.4   --> true
5827         // (float)int >= 4.4    --> int > 4
5828         if (!RHS.isNegative())
5829           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5830         Pred = ICmpInst::ICMP_UGT;
5831         break;
5832       case ICmpInst::ICMP_SGE:
5833         // (float)int >= -4.4   --> int >= -4
5834         // (float)int >= 4.4    --> int > 4
5835         if (!RHS.isNegative())
5836           Pred = ICmpInst::ICMP_SGT;
5837         break;
5838       }
5839     }
5840   }
5841
5842   // Lower this FP comparison into an appropriate integer version of the
5843   // comparison.
5844   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5845 }
5846
5847 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5848   bool Changed = SimplifyCompare(I);
5849   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5850
5851   // Fold trivial predicates.
5852   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5853     return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
5854   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5855     return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
5856   
5857   // Simplify 'fcmp pred X, X'
5858   if (Op0 == Op1) {
5859     switch (I.getPredicate()) {
5860     default: llvm_unreachable("Unknown predicate!");
5861     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5862     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5863     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5864       return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
5865     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5866     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5867     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5868       return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
5869       
5870     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5871     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5872     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5873     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5874       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5875       I.setPredicate(FCmpInst::FCMP_UNO);
5876       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5877       return &I;
5878       
5879     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5880     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5881     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5882     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5883       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5884       I.setPredicate(FCmpInst::FCMP_ORD);
5885       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5886       return &I;
5887     }
5888   }
5889     
5890   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5891     return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
5892
5893   // Handle fcmp with constant RHS
5894   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5895     // If the constant is a nan, see if we can fold the comparison based on it.
5896     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5897       if (CFP->getValueAPF().isNaN()) {
5898         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5899           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5900         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5901                "Comparison must be either ordered or unordered!");
5902         // True if unordered.
5903         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5904       }
5905     }
5906     
5907     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5908       switch (LHSI->getOpcode()) {
5909       case Instruction::PHI:
5910         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5911         // block.  If in the same block, we're encouraging jump threading.  If
5912         // not, we are just pessimizing the code by making an i1 phi.
5913         if (LHSI->getParent() == I.getParent())
5914           if (Instruction *NV = FoldOpIntoPhi(I, true))
5915             return NV;
5916         break;
5917       case Instruction::SIToFP:
5918       case Instruction::UIToFP:
5919         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5920           return NV;
5921         break;
5922       case Instruction::Select:
5923         // If either operand of the select is a constant, we can fold the
5924         // comparison into the select arms, which will cause one to be
5925         // constant folded and the select turned into a bitwise or.
5926         Value *Op1 = 0, *Op2 = 0;
5927         if (LHSI->hasOneUse()) {
5928           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5929             // Fold the known value into the constant operand.
5930             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5931             // Insert a new FCmp of the other select operand.
5932             Op2 = Builder->CreateFCmp(I.getPredicate(),
5933                                       LHSI->getOperand(2), RHSC, I.getName());
5934           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5935             // Fold the known value into the constant operand.
5936             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5937             // Insert a new FCmp of the other select operand.
5938             Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5939                                       RHSC, I.getName());
5940           }
5941         }
5942
5943         if (Op1)
5944           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5945         break;
5946       }
5947   }
5948
5949   return Changed ? &I : 0;
5950 }
5951
5952 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5953   bool Changed = SimplifyCompare(I);
5954   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5955   const Type *Ty = Op0->getType();
5956
5957   // icmp X, X
5958   if (Op0 == Op1)
5959     return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(),
5960                                                    I.isTrueWhenEqual()));
5961
5962   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5963     return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
5964   
5965   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5966   // addresses never equal each other!  We already know that Op0 != Op1.
5967   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) || 
5968        isa<ConstantPointerNull>(Op0)) &&
5969       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) || 
5970        isa<ConstantPointerNull>(Op1)))
5971     return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context), 
5972                                                    !I.isTrueWhenEqual()));
5973
5974   // icmp's with boolean values can always be turned into bitwise operations
5975   if (Ty == Type::getInt1Ty(*Context)) {
5976     switch (I.getPredicate()) {
5977     default: llvm_unreachable("Invalid icmp instruction!");
5978     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5979       Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
5980       return BinaryOperator::CreateNot(Xor);
5981     }
5982     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5983       return BinaryOperator::CreateXor(Op0, Op1);
5984
5985     case ICmpInst::ICMP_UGT:
5986       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5987       // FALL THROUGH
5988     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5989       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
5990       return BinaryOperator::CreateAnd(Not, Op1);
5991     }
5992     case ICmpInst::ICMP_SGT:
5993       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5994       // FALL THROUGH
5995     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5996       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
5997       return BinaryOperator::CreateAnd(Not, Op0);
5998     }
5999     case ICmpInst::ICMP_UGE:
6000       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6001       // FALL THROUGH
6002     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6003       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
6004       return BinaryOperator::CreateOr(Not, Op1);
6005     }
6006     case ICmpInst::ICMP_SGE:
6007       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6008       // FALL THROUGH
6009     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6010       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
6011       return BinaryOperator::CreateOr(Not, Op0);
6012     }
6013     }
6014   }
6015
6016   unsigned BitWidth = 0;
6017   if (TD)
6018     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6019   else if (Ty->isIntOrIntVector())
6020     BitWidth = Ty->getScalarSizeInBits();
6021
6022   bool isSignBit = false;
6023
6024   // See if we are doing a comparison with a constant.
6025   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6026     Value *A = 0, *B = 0;
6027     
6028     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6029     if (I.isEquality() && CI->isNullValue() &&
6030         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
6031       // (icmp cond A B) if cond is equality
6032       return new ICmpInst(I.getPredicate(), A, B);
6033     }
6034     
6035     // If we have an icmp le or icmp ge instruction, turn it into the
6036     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6037     // them being folded in the code below.
6038     switch (I.getPredicate()) {
6039     default: break;
6040     case ICmpInst::ICMP_ULE:
6041       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
6042         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6043       return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
6044                           AddOne(CI));
6045     case ICmpInst::ICMP_SLE:
6046       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
6047         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6048       return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6049                           AddOne(CI));
6050     case ICmpInst::ICMP_UGE:
6051       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
6052         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6053       return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
6054                           SubOne(CI));
6055     case ICmpInst::ICMP_SGE:
6056       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
6057         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6058       return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6059                           SubOne(CI));
6060     }
6061     
6062     // If this comparison is a normal comparison, it demands all
6063     // bits, if it is a sign bit comparison, it only demands the sign bit.
6064     bool UnusedBit;
6065     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6066   }
6067
6068   // See if we can fold the comparison based on range information we can get
6069   // by checking whether bits are known to be zero or one in the input.
6070   if (BitWidth != 0) {
6071     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6072     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6073
6074     if (SimplifyDemandedBits(I.getOperandUse(0),
6075                              isSignBit ? APInt::getSignBit(BitWidth)
6076                                        : APInt::getAllOnesValue(BitWidth),
6077                              Op0KnownZero, Op0KnownOne, 0))
6078       return &I;
6079     if (SimplifyDemandedBits(I.getOperandUse(1),
6080                              APInt::getAllOnesValue(BitWidth),
6081                              Op1KnownZero, Op1KnownOne, 0))
6082       return &I;
6083
6084     // Given the known and unknown bits, compute a range that the LHS could be
6085     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6086     // EQ and NE we use unsigned values.
6087     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6088     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6089     if (I.isSigned()) {
6090       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6091                                              Op0Min, Op0Max);
6092       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6093                                              Op1Min, Op1Max);
6094     } else {
6095       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6096                                                Op0Min, Op0Max);
6097       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6098                                                Op1Min, Op1Max);
6099     }
6100
6101     // If Min and Max are known to be the same, then SimplifyDemandedBits
6102     // figured out that the LHS is a constant.  Just constant fold this now so
6103     // that code below can assume that Min != Max.
6104     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6105       return new ICmpInst(I.getPredicate(),
6106                           ConstantInt::get(*Context, Op0Min), Op1);
6107     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6108       return new ICmpInst(I.getPredicate(), Op0,
6109                           ConstantInt::get(*Context, Op1Min));
6110
6111     // Based on the range information we know about the LHS, see if we can
6112     // simplify this comparison.  For example, (x&4) < 8  is always true.
6113     switch (I.getPredicate()) {
6114     default: llvm_unreachable("Unknown icmp opcode!");
6115     case ICmpInst::ICMP_EQ:
6116       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6117         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6118       break;
6119     case ICmpInst::ICMP_NE:
6120       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6121         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6122       break;
6123     case ICmpInst::ICMP_ULT:
6124       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6125         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6126       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6127         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6128       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6129         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6130       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6131         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6132           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6133                               SubOne(CI));
6134
6135         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6136         if (CI->isMinValue(true))
6137           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6138                            Constant::getAllOnesValue(Op0->getType()));
6139       }
6140       break;
6141     case ICmpInst::ICMP_UGT:
6142       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6143         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6144       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6145         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6146
6147       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6148         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6149       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6150         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6151           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6152                               AddOne(CI));
6153
6154         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6155         if (CI->isMaxValue(true))
6156           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6157                               Constant::getNullValue(Op0->getType()));
6158       }
6159       break;
6160     case ICmpInst::ICMP_SLT:
6161       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6162         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6163       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6164         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6165       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6166         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6167       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6168         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6169           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6170                               SubOne(CI));
6171       }
6172       break;
6173     case ICmpInst::ICMP_SGT:
6174       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6175         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6176       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6177         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6178
6179       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6180         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6181       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6182         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6183           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6184                               AddOne(CI));
6185       }
6186       break;
6187     case ICmpInst::ICMP_SGE:
6188       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6189       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6190         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6191       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6192         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6193       break;
6194     case ICmpInst::ICMP_SLE:
6195       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6196       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6197         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6198       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6199         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6200       break;
6201     case ICmpInst::ICMP_UGE:
6202       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6203       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6204         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6205       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6206         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6207       break;
6208     case ICmpInst::ICMP_ULE:
6209       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6210       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6211         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6212       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6213         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6214       break;
6215     }
6216
6217     // Turn a signed comparison into an unsigned one if both operands
6218     // are known to have the same sign.
6219     if (I.isSigned() &&
6220         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6221          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6222       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6223   }
6224
6225   // Test if the ICmpInst instruction is used exclusively by a select as
6226   // part of a minimum or maximum operation. If so, refrain from doing
6227   // any other folding. This helps out other analyses which understand
6228   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6229   // and CodeGen. And in this case, at least one of the comparison
6230   // operands has at least one user besides the compare (the select),
6231   // which would often largely negate the benefit of folding anyway.
6232   if (I.hasOneUse())
6233     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6234       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6235           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6236         return 0;
6237
6238   // See if we are doing a comparison between a constant and an instruction that
6239   // can be folded into the comparison.
6240   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6241     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6242     // instruction, see if that instruction also has constants so that the 
6243     // instruction can be folded into the icmp 
6244     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6245       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6246         return Res;
6247   }
6248
6249   // Handle icmp with constant (but not simple integer constant) RHS
6250   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6251     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6252       switch (LHSI->getOpcode()) {
6253       case Instruction::GetElementPtr:
6254         if (RHSC->isNullValue()) {
6255           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6256           bool isAllZeros = true;
6257           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6258             if (!isa<Constant>(LHSI->getOperand(i)) ||
6259                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6260               isAllZeros = false;
6261               break;
6262             }
6263           if (isAllZeros)
6264             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6265                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
6266         }
6267         break;
6268
6269       case Instruction::PHI:
6270         // Only fold icmp into the PHI if the phi and icmp are in the same
6271         // block.  If in the same block, we're encouraging jump threading.  If
6272         // not, we are just pessimizing the code by making an i1 phi.
6273         if (LHSI->getParent() == I.getParent())
6274           if (Instruction *NV = FoldOpIntoPhi(I, true))
6275             return NV;
6276         break;
6277       case Instruction::Select: {
6278         // If either operand of the select is a constant, we can fold the
6279         // comparison into the select arms, which will cause one to be
6280         // constant folded and the select turned into a bitwise or.
6281         Value *Op1 = 0, *Op2 = 0;
6282         if (LHSI->hasOneUse()) {
6283           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6284             // Fold the known value into the constant operand.
6285             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6286             // Insert a new ICmp of the other select operand.
6287             Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6288                                       RHSC, I.getName());
6289           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6290             // Fold the known value into the constant operand.
6291             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6292             // Insert a new ICmp of the other select operand.
6293             Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6294                                       RHSC, I.getName());
6295           }
6296         }
6297
6298         if (Op1)
6299           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6300         break;
6301       }
6302       case Instruction::Call:
6303         // If we have (malloc != null), and if the malloc has a single use, we
6304         // can assume it is successful and remove the malloc.
6305         if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6306             isa<ConstantPointerNull>(RHSC)) {
6307           // Need to explicitly erase malloc call here, instead of adding it to
6308           // Worklist, because it won't get DCE'd from the Worklist since
6309           // isInstructionTriviallyDead() returns false for function calls.
6310           // It is OK to replace LHSI/MallocCall with Undef because the 
6311           // instruction that uses it will be erased via Worklist.
6312           if (extractMallocCall(LHSI)) {
6313             LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6314             EraseInstFromFunction(*LHSI);
6315             return ReplaceInstUsesWith(I,
6316                                      ConstantInt::get(Type::getInt1Ty(*Context),
6317                                                       !I.isTrueWhenEqual()));
6318           }
6319           if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6320             if (MallocCall->hasOneUse()) {
6321               MallocCall->replaceAllUsesWith(
6322                                         UndefValue::get(MallocCall->getType()));
6323               EraseInstFromFunction(*MallocCall);
6324               Worklist.Add(LHSI); // The malloc's bitcast use.
6325               return ReplaceInstUsesWith(I,
6326                                      ConstantInt::get(Type::getInt1Ty(*Context),
6327                                                       !I.isTrueWhenEqual()));
6328             }
6329         }
6330         break;
6331       }
6332   }
6333
6334   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6335   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6336     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6337       return NI;
6338   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6339     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6340                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6341       return NI;
6342
6343   // Test to see if the operands of the icmp are casted versions of other
6344   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6345   // now.
6346   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6347     if (isa<PointerType>(Op0->getType()) && 
6348         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6349       // We keep moving the cast from the left operand over to the right
6350       // operand, where it can often be eliminated completely.
6351       Op0 = CI->getOperand(0);
6352
6353       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6354       // so eliminate it as well.
6355       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6356         Op1 = CI2->getOperand(0);
6357
6358       // If Op1 is a constant, we can fold the cast into the constant.
6359       if (Op0->getType() != Op1->getType()) {
6360         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6361           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6362         } else {
6363           // Otherwise, cast the RHS right before the icmp
6364           Op1 = Builder->CreateBitCast(Op1, Op0->getType());
6365         }
6366       }
6367       return new ICmpInst(I.getPredicate(), Op0, Op1);
6368     }
6369   }
6370   
6371   if (isa<CastInst>(Op0)) {
6372     // Handle the special case of: icmp (cast bool to X), <cst>
6373     // This comes up when you have code like
6374     //   int X = A < B;
6375     //   if (X) ...
6376     // For generality, we handle any zero-extension of any operand comparison
6377     // with a constant or another cast from the same type.
6378     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6379       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6380         return R;
6381   }
6382   
6383   // See if it's the same type of instruction on the left and right.
6384   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6385     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6386       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6387           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6388         switch (Op0I->getOpcode()) {
6389         default: break;
6390         case Instruction::Add:
6391         case Instruction::Sub:
6392         case Instruction::Xor:
6393           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6394             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6395                                 Op1I->getOperand(0));
6396           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6397           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6398             if (CI->getValue().isSignBit()) {
6399               ICmpInst::Predicate Pred = I.isSigned()
6400                                              ? I.getUnsignedPredicate()
6401                                              : I.getSignedPredicate();
6402               return new ICmpInst(Pred, Op0I->getOperand(0),
6403                                   Op1I->getOperand(0));
6404             }
6405             
6406             if (CI->getValue().isMaxSignedValue()) {
6407               ICmpInst::Predicate Pred = I.isSigned()
6408                                              ? I.getUnsignedPredicate()
6409                                              : I.getSignedPredicate();
6410               Pred = I.getSwappedPredicate(Pred);
6411               return new ICmpInst(Pred, Op0I->getOperand(0),
6412                                   Op1I->getOperand(0));
6413             }
6414           }
6415           break;
6416         case Instruction::Mul:
6417           if (!I.isEquality())
6418             break;
6419
6420           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6421             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6422             // Mask = -1 >> count-trailing-zeros(Cst).
6423             if (!CI->isZero() && !CI->isOne()) {
6424               const APInt &AP = CI->getValue();
6425               ConstantInt *Mask = ConstantInt::get(*Context, 
6426                                       APInt::getLowBitsSet(AP.getBitWidth(),
6427                                                            AP.getBitWidth() -
6428                                                       AP.countTrailingZeros()));
6429               Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6430               Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
6431               return new ICmpInst(I.getPredicate(), And1, And2);
6432             }
6433           }
6434           break;
6435         }
6436       }
6437     }
6438   }
6439   
6440   // ~x < ~y --> y < x
6441   { Value *A, *B;
6442     if (match(Op0, m_Not(m_Value(A))) &&
6443         match(Op1, m_Not(m_Value(B))))
6444       return new ICmpInst(I.getPredicate(), B, A);
6445   }
6446   
6447   if (I.isEquality()) {
6448     Value *A, *B, *C, *D;
6449     
6450     // -x == -y --> x == y
6451     if (match(Op0, m_Neg(m_Value(A))) &&
6452         match(Op1, m_Neg(m_Value(B))))
6453       return new ICmpInst(I.getPredicate(), A, B);
6454     
6455     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6456       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6457         Value *OtherVal = A == Op1 ? B : A;
6458         return new ICmpInst(I.getPredicate(), OtherVal,
6459                             Constant::getNullValue(A->getType()));
6460       }
6461
6462       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6463         // A^c1 == C^c2 --> A == C^(c1^c2)
6464         ConstantInt *C1, *C2;
6465         if (match(B, m_ConstantInt(C1)) &&
6466             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6467           Constant *NC = 
6468                    ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6469           Value *Xor = Builder->CreateXor(C, NC, "tmp");
6470           return new ICmpInst(I.getPredicate(), A, Xor);
6471         }
6472         
6473         // A^B == A^D -> B == D
6474         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6475         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6476         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6477         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6478       }
6479     }
6480     
6481     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6482         (A == Op0 || B == Op0)) {
6483       // A == (A^B)  ->  B == 0
6484       Value *OtherVal = A == Op0 ? B : A;
6485       return new ICmpInst(I.getPredicate(), OtherVal,
6486                           Constant::getNullValue(A->getType()));
6487     }
6488
6489     // (A-B) == A  ->  B == 0
6490     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6491       return new ICmpInst(I.getPredicate(), B, 
6492                           Constant::getNullValue(B->getType()));
6493
6494     // A == (A-B)  ->  B == 0
6495     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6496       return new ICmpInst(I.getPredicate(), B,
6497                           Constant::getNullValue(B->getType()));
6498     
6499     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6500     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6501         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6502         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6503       Value *X = 0, *Y = 0, *Z = 0;
6504       
6505       if (A == C) {
6506         X = B; Y = D; Z = A;
6507       } else if (A == D) {
6508         X = B; Y = C; Z = A;
6509       } else if (B == C) {
6510         X = A; Y = D; Z = B;
6511       } else if (B == D) {
6512         X = A; Y = C; Z = B;
6513       }
6514       
6515       if (X) {   // Build (X^Y) & Z
6516         Op1 = Builder->CreateXor(X, Y, "tmp");
6517         Op1 = Builder->CreateAnd(Op1, Z, "tmp");
6518         I.setOperand(0, Op1);
6519         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6520         return &I;
6521       }
6522     }
6523   }
6524   return Changed ? &I : 0;
6525 }
6526
6527
6528 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6529 /// and CmpRHS are both known to be integer constants.
6530 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6531                                           ConstantInt *DivRHS) {
6532   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6533   const APInt &CmpRHSV = CmpRHS->getValue();
6534   
6535   // FIXME: If the operand types don't match the type of the divide 
6536   // then don't attempt this transform. The code below doesn't have the
6537   // logic to deal with a signed divide and an unsigned compare (and
6538   // vice versa). This is because (x /s C1) <s C2  produces different 
6539   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6540   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6541   // work. :(  The if statement below tests that condition and bails 
6542   // if it finds it. 
6543   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6544   if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
6545     return 0;
6546   if (DivRHS->isZero())
6547     return 0; // The ProdOV computation fails on divide by zero.
6548   if (DivIsSigned && DivRHS->isAllOnesValue())
6549     return 0; // The overflow computation also screws up here
6550   if (DivRHS->isOne())
6551     return 0; // Not worth bothering, and eliminates some funny cases
6552               // with INT_MIN.
6553
6554   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6555   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6556   // C2 (CI). By solving for X we can turn this into a range check 
6557   // instead of computing a divide. 
6558   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6559
6560   // Determine if the product overflows by seeing if the product is
6561   // not equal to the divide. Make sure we do the same kind of divide
6562   // as in the LHS instruction that we're folding. 
6563   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6564                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6565
6566   // Get the ICmp opcode
6567   ICmpInst::Predicate Pred = ICI.getPredicate();
6568
6569   // Figure out the interval that is being checked.  For example, a comparison
6570   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6571   // Compute this interval based on the constants involved and the signedness of
6572   // the compare/divide.  This computes a half-open interval, keeping track of
6573   // whether either value in the interval overflows.  After analysis each
6574   // overflow variable is set to 0 if it's corresponding bound variable is valid
6575   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6576   int LoOverflow = 0, HiOverflow = 0;
6577   Constant *LoBound = 0, *HiBound = 0;
6578   
6579   if (!DivIsSigned) {  // udiv
6580     // e.g. X/5 op 3  --> [15, 20)
6581     LoBound = Prod;
6582     HiOverflow = LoOverflow = ProdOV;
6583     if (!HiOverflow)
6584       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6585   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6586     if (CmpRHSV == 0) {       // (X / pos) op 0
6587       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6588       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6589       HiBound = DivRHS;
6590     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6591       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6592       HiOverflow = LoOverflow = ProdOV;
6593       if (!HiOverflow)
6594         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6595     } else {                       // (X / pos) op neg
6596       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6597       HiBound = AddOne(Prod);
6598       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6599       if (!LoOverflow) {
6600         ConstantInt* DivNeg =
6601                          cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6602         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6603                                      true) ? -1 : 0;
6604        }
6605     }
6606   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6607     if (CmpRHSV == 0) {       // (X / neg) op 0
6608       // e.g. X/-5 op 0  --> [-4, 5)
6609       LoBound = AddOne(DivRHS);
6610       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6611       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6612         HiOverflow = 1;            // [INTMIN+1, overflow)
6613         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6614       }
6615     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6616       // e.g. X/-5 op 3  --> [-19, -14)
6617       HiBound = AddOne(Prod);
6618       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6619       if (!LoOverflow)
6620         LoOverflow = AddWithOverflow(LoBound, HiBound,
6621                                      DivRHS, Context, true) ? -1 : 0;
6622     } else {                       // (X / neg) op neg
6623       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6624       LoOverflow = HiOverflow = ProdOV;
6625       if (!HiOverflow)
6626         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6627     }
6628     
6629     // Dividing by a negative swaps the condition.  LT <-> GT
6630     Pred = ICmpInst::getSwappedPredicate(Pred);
6631   }
6632
6633   Value *X = DivI->getOperand(0);
6634   switch (Pred) {
6635   default: llvm_unreachable("Unhandled icmp opcode!");
6636   case ICmpInst::ICMP_EQ:
6637     if (LoOverflow && HiOverflow)
6638       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6639     else if (HiOverflow)
6640       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6641                           ICmpInst::ICMP_UGE, X, LoBound);
6642     else if (LoOverflow)
6643       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6644                           ICmpInst::ICMP_ULT, X, HiBound);
6645     else
6646       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6647   case ICmpInst::ICMP_NE:
6648     if (LoOverflow && HiOverflow)
6649       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6650     else if (HiOverflow)
6651       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6652                           ICmpInst::ICMP_ULT, X, LoBound);
6653     else if (LoOverflow)
6654       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6655                           ICmpInst::ICMP_UGE, X, HiBound);
6656     else
6657       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6658   case ICmpInst::ICMP_ULT:
6659   case ICmpInst::ICMP_SLT:
6660     if (LoOverflow == +1)   // Low bound is greater than input range.
6661       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6662     if (LoOverflow == -1)   // Low bound is less than input range.
6663       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6664     return new ICmpInst(Pred, X, LoBound);
6665   case ICmpInst::ICMP_UGT:
6666   case ICmpInst::ICMP_SGT:
6667     if (HiOverflow == +1)       // High bound greater than input range.
6668       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6669     else if (HiOverflow == -1)  // High bound less than input range.
6670       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6671     if (Pred == ICmpInst::ICMP_UGT)
6672       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6673     else
6674       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6675   }
6676 }
6677
6678
6679 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6680 ///
6681 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6682                                                           Instruction *LHSI,
6683                                                           ConstantInt *RHS) {
6684   const APInt &RHSV = RHS->getValue();
6685   
6686   switch (LHSI->getOpcode()) {
6687   case Instruction::Trunc:
6688     if (ICI.isEquality() && LHSI->hasOneUse()) {
6689       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6690       // of the high bits truncated out of x are known.
6691       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6692              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6693       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6694       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6695       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6696       
6697       // If all the high bits are known, we can do this xform.
6698       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6699         // Pull in the high bits from known-ones set.
6700         APInt NewRHS(RHS->getValue());
6701         NewRHS.zext(SrcBits);
6702         NewRHS |= KnownOne;
6703         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6704                             ConstantInt::get(*Context, NewRHS));
6705       }
6706     }
6707     break;
6708       
6709   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6710     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6711       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6712       // fold the xor.
6713       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6714           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6715         Value *CompareVal = LHSI->getOperand(0);
6716         
6717         // If the sign bit of the XorCST is not set, there is no change to
6718         // the operation, just stop using the Xor.
6719         if (!XorCST->getValue().isNegative()) {
6720           ICI.setOperand(0, CompareVal);
6721           Worklist.Add(LHSI);
6722           return &ICI;
6723         }
6724         
6725         // Was the old condition true if the operand is positive?
6726         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6727         
6728         // If so, the new one isn't.
6729         isTrueIfPositive ^= true;
6730         
6731         if (isTrueIfPositive)
6732           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
6733                               SubOne(RHS));
6734         else
6735           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
6736                               AddOne(RHS));
6737       }
6738
6739       if (LHSI->hasOneUse()) {
6740         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6741         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6742           const APInt &SignBit = XorCST->getValue();
6743           ICmpInst::Predicate Pred = ICI.isSigned()
6744                                          ? ICI.getUnsignedPredicate()
6745                                          : ICI.getSignedPredicate();
6746           return new ICmpInst(Pred, LHSI->getOperand(0),
6747                               ConstantInt::get(*Context, RHSV ^ SignBit));
6748         }
6749
6750         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6751         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6752           const APInt &NotSignBit = XorCST->getValue();
6753           ICmpInst::Predicate Pred = ICI.isSigned()
6754                                          ? ICI.getUnsignedPredicate()
6755                                          : ICI.getSignedPredicate();
6756           Pred = ICI.getSwappedPredicate(Pred);
6757           return new ICmpInst(Pred, LHSI->getOperand(0),
6758                               ConstantInt::get(*Context, RHSV ^ NotSignBit));
6759         }
6760       }
6761     }
6762     break;
6763   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6764     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6765         LHSI->getOperand(0)->hasOneUse()) {
6766       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6767       
6768       // If the LHS is an AND of a truncating cast, we can widen the
6769       // and/compare to be the input width without changing the value
6770       // produced, eliminating a cast.
6771       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6772         // We can do this transformation if either the AND constant does not
6773         // have its sign bit set or if it is an equality comparison. 
6774         // Extending a relational comparison when we're checking the sign
6775         // bit would not work.
6776         if (Cast->hasOneUse() &&
6777             (ICI.isEquality() ||
6778              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6779           uint32_t BitWidth = 
6780             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6781           APInt NewCST = AndCST->getValue();
6782           NewCST.zext(BitWidth);
6783           APInt NewCI = RHSV;
6784           NewCI.zext(BitWidth);
6785           Value *NewAnd = 
6786             Builder->CreateAnd(Cast->getOperand(0),
6787                            ConstantInt::get(*Context, NewCST), LHSI->getName());
6788           return new ICmpInst(ICI.getPredicate(), NewAnd,
6789                               ConstantInt::get(*Context, NewCI));
6790         }
6791       }
6792       
6793       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6794       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6795       // happens a LOT in code produced by the C front-end, for bitfield
6796       // access.
6797       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6798       if (Shift && !Shift->isShift())
6799         Shift = 0;
6800       
6801       ConstantInt *ShAmt;
6802       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6803       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6804       const Type *AndTy = AndCST->getType();          // Type of the and.
6805       
6806       // We can fold this as long as we can't shift unknown bits
6807       // into the mask.  This can only happen with signed shift
6808       // rights, as they sign-extend.
6809       if (ShAmt) {
6810         bool CanFold = Shift->isLogicalShift();
6811         if (!CanFold) {
6812           // To test for the bad case of the signed shr, see if any
6813           // of the bits shifted in could be tested after the mask.
6814           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6815           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6816           
6817           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6818           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6819                AndCST->getValue()) == 0)
6820             CanFold = true;
6821         }
6822         
6823         if (CanFold) {
6824           Constant *NewCst;
6825           if (Shift->getOpcode() == Instruction::Shl)
6826             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6827           else
6828             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6829           
6830           // Check to see if we are shifting out any of the bits being
6831           // compared.
6832           if (ConstantExpr::get(Shift->getOpcode(),
6833                                        NewCst, ShAmt) != RHS) {
6834             // If we shifted bits out, the fold is not going to work out.
6835             // As a special case, check to see if this means that the
6836             // result is always true or false now.
6837             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6838               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6839             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6840               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6841           } else {
6842             ICI.setOperand(1, NewCst);
6843             Constant *NewAndCST;
6844             if (Shift->getOpcode() == Instruction::Shl)
6845               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6846             else
6847               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6848             LHSI->setOperand(1, NewAndCST);
6849             LHSI->setOperand(0, Shift->getOperand(0));
6850             Worklist.Add(Shift); // Shift is dead.
6851             return &ICI;
6852           }
6853         }
6854       }
6855       
6856       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6857       // preferable because it allows the C<<Y expression to be hoisted out
6858       // of a loop if Y is invariant and X is not.
6859       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6860           ICI.isEquality() && !Shift->isArithmeticShift() &&
6861           !isa<Constant>(Shift->getOperand(0))) {
6862         // Compute C << Y.
6863         Value *NS;
6864         if (Shift->getOpcode() == Instruction::LShr) {
6865           NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
6866         } else {
6867           // Insert a logical shift.
6868           NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
6869         }
6870         
6871         // Compute X & (C << Y).
6872         Value *NewAnd = 
6873           Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6874         
6875         ICI.setOperand(0, NewAnd);
6876         return &ICI;
6877       }
6878     }
6879     break;
6880     
6881   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6882     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6883     if (!ShAmt) break;
6884     
6885     uint32_t TypeBits = RHSV.getBitWidth();
6886     
6887     // Check that the shift amount is in range.  If not, don't perform
6888     // undefined shifts.  When the shift is visited it will be
6889     // simplified.
6890     if (ShAmt->uge(TypeBits))
6891       break;
6892     
6893     if (ICI.isEquality()) {
6894       // If we are comparing against bits always shifted out, the
6895       // comparison cannot succeed.
6896       Constant *Comp =
6897         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
6898                                                                  ShAmt);
6899       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6900         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6901         Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6902         return ReplaceInstUsesWith(ICI, Cst);
6903       }
6904       
6905       if (LHSI->hasOneUse()) {
6906         // Otherwise strength reduce the shift into an and.
6907         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6908         Constant *Mask =
6909           ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits, 
6910                                                        TypeBits-ShAmtVal));
6911         
6912         Value *And =
6913           Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
6914         return new ICmpInst(ICI.getPredicate(), And,
6915                             ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
6916       }
6917     }
6918     
6919     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6920     bool TrueIfSigned = false;
6921     if (LHSI->hasOneUse() &&
6922         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6923       // (X << 31) <s 0  --> (X&1) != 0
6924       Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
6925                                            (TypeBits-ShAmt->getZExtValue()-1));
6926       Value *And =
6927         Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
6928       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6929                           And, Constant::getNullValue(And->getType()));
6930     }
6931     break;
6932   }
6933     
6934   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6935   case Instruction::AShr: {
6936     // Only handle equality comparisons of shift-by-constant.
6937     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6938     if (!ShAmt || !ICI.isEquality()) break;
6939
6940     // Check that the shift amount is in range.  If not, don't perform
6941     // undefined shifts.  When the shift is visited it will be
6942     // simplified.
6943     uint32_t TypeBits = RHSV.getBitWidth();
6944     if (ShAmt->uge(TypeBits))
6945       break;
6946     
6947     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6948       
6949     // If we are comparing against bits always shifted out, the
6950     // comparison cannot succeed.
6951     APInt Comp = RHSV << ShAmtVal;
6952     if (LHSI->getOpcode() == Instruction::LShr)
6953       Comp = Comp.lshr(ShAmtVal);
6954     else
6955       Comp = Comp.ashr(ShAmtVal);
6956     
6957     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6958       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6959       Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6960       return ReplaceInstUsesWith(ICI, Cst);
6961     }
6962     
6963     // Otherwise, check to see if the bits shifted out are known to be zero.
6964     // If so, we can compare against the unshifted value:
6965     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6966     if (LHSI->hasOneUse() &&
6967         MaskedValueIsZero(LHSI->getOperand(0), 
6968                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6969       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6970                           ConstantExpr::getShl(RHS, ShAmt));
6971     }
6972       
6973     if (LHSI->hasOneUse()) {
6974       // Otherwise strength reduce the shift into an and.
6975       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6976       Constant *Mask = ConstantInt::get(*Context, Val);
6977       
6978       Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6979                                       Mask, LHSI->getName()+".mask");
6980       return new ICmpInst(ICI.getPredicate(), And,
6981                           ConstantExpr::getShl(RHS, ShAmt));
6982     }
6983     break;
6984   }
6985     
6986   case Instruction::SDiv:
6987   case Instruction::UDiv:
6988     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6989     // Fold this div into the comparison, producing a range check. 
6990     // Determine, based on the divide type, what the range is being 
6991     // checked.  If there is an overflow on the low or high side, remember 
6992     // it, otherwise compute the range [low, hi) bounding the new value.
6993     // See: InsertRangeTest above for the kinds of replacements possible.
6994     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6995       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6996                                           DivRHS))
6997         return R;
6998     break;
6999
7000   case Instruction::Add:
7001     // Fold: icmp pred (add, X, C1), C2
7002
7003     if (!ICI.isEquality()) {
7004       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7005       if (!LHSC) break;
7006       const APInt &LHSV = LHSC->getValue();
7007
7008       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7009                             .subtract(LHSV);
7010
7011       if (ICI.isSigned()) {
7012         if (CR.getLower().isSignBit()) {
7013           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7014                               ConstantInt::get(*Context, CR.getUpper()));
7015         } else if (CR.getUpper().isSignBit()) {
7016           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7017                               ConstantInt::get(*Context, CR.getLower()));
7018         }
7019       } else {
7020         if (CR.getLower().isMinValue()) {
7021           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7022                               ConstantInt::get(*Context, CR.getUpper()));
7023         } else if (CR.getUpper().isMinValue()) {
7024           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7025                               ConstantInt::get(*Context, CR.getLower()));
7026         }
7027       }
7028     }
7029     break;
7030   }
7031   
7032   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7033   if (ICI.isEquality()) {
7034     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7035     
7036     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7037     // the second operand is a constant, simplify a bit.
7038     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7039       switch (BO->getOpcode()) {
7040       case Instruction::SRem:
7041         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7042         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7043           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7044           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7045             Value *NewRem =
7046               Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7047                                   BO->getName());
7048             return new ICmpInst(ICI.getPredicate(), NewRem,
7049                                 Constant::getNullValue(BO->getType()));
7050           }
7051         }
7052         break;
7053       case Instruction::Add:
7054         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7055         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7056           if (BO->hasOneUse())
7057             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7058                                 ConstantExpr::getSub(RHS, BOp1C));
7059         } else if (RHSV == 0) {
7060           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7061           // efficiently invertible, or if the add has just this one use.
7062           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7063           
7064           if (Value *NegVal = dyn_castNegVal(BOp1))
7065             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
7066           else if (Value *NegVal = dyn_castNegVal(BOp0))
7067             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
7068           else if (BO->hasOneUse()) {
7069             Value *Neg = Builder->CreateNeg(BOp1);
7070             Neg->takeName(BO);
7071             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
7072           }
7073         }
7074         break;
7075       case Instruction::Xor:
7076         // For the xor case, we can xor two constants together, eliminating
7077         // the explicit xor.
7078         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7079           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
7080                               ConstantExpr::getXor(RHS, BOC));
7081         
7082         // FALLTHROUGH
7083       case Instruction::Sub:
7084         // Replace (([sub|xor] A, B) != 0) with (A != B)
7085         if (RHSV == 0)
7086           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7087                               BO->getOperand(1));
7088         break;
7089         
7090       case Instruction::Or:
7091         // If bits are being or'd in that are not present in the constant we
7092         // are comparing against, then the comparison could never succeed!
7093         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7094           Constant *NotCI = ConstantExpr::getNot(RHS);
7095           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7096             return ReplaceInstUsesWith(ICI,
7097                                        ConstantInt::get(Type::getInt1Ty(*Context), 
7098                                        isICMP_NE));
7099         }
7100         break;
7101         
7102       case Instruction::And:
7103         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7104           // If bits are being compared against that are and'd out, then the
7105           // comparison can never succeed!
7106           if ((RHSV & ~BOC->getValue()) != 0)
7107             return ReplaceInstUsesWith(ICI,
7108                                        ConstantInt::get(Type::getInt1Ty(*Context),
7109                                        isICMP_NE));
7110           
7111           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7112           if (RHS == BOC && RHSV.isPowerOf2())
7113             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7114                                 ICmpInst::ICMP_NE, LHSI,
7115                                 Constant::getNullValue(RHS->getType()));
7116           
7117           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7118           if (BOC->getValue().isSignBit()) {
7119             Value *X = BO->getOperand(0);
7120             Constant *Zero = Constant::getNullValue(X->getType());
7121             ICmpInst::Predicate pred = isICMP_NE ? 
7122               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7123             return new ICmpInst(pred, X, Zero);
7124           }
7125           
7126           // ((X & ~7) == 0) --> X < 8
7127           if (RHSV == 0 && isHighOnes(BOC)) {
7128             Value *X = BO->getOperand(0);
7129             Constant *NegX = ConstantExpr::getNeg(BOC);
7130             ICmpInst::Predicate pred = isICMP_NE ? 
7131               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7132             return new ICmpInst(pred, X, NegX);
7133           }
7134         }
7135       default: break;
7136       }
7137     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7138       // Handle icmp {eq|ne} <intrinsic>, intcst.
7139       if (II->getIntrinsicID() == Intrinsic::bswap) {
7140         Worklist.Add(II);
7141         ICI.setOperand(0, II->getOperand(1));
7142         ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7143         return &ICI;
7144       }
7145     }
7146   }
7147   return 0;
7148 }
7149
7150 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7151 /// We only handle extending casts so far.
7152 ///
7153 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7154   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7155   Value *LHSCIOp        = LHSCI->getOperand(0);
7156   const Type *SrcTy     = LHSCIOp->getType();
7157   const Type *DestTy    = LHSCI->getType();
7158   Value *RHSCIOp;
7159
7160   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7161   // integer type is the same size as the pointer type.
7162   if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7163       TD->getPointerSizeInBits() ==
7164          cast<IntegerType>(DestTy)->getBitWidth()) {
7165     Value *RHSOp = 0;
7166     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7167       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7168     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7169       RHSOp = RHSC->getOperand(0);
7170       // If the pointer types don't match, insert a bitcast.
7171       if (LHSCIOp->getType() != RHSOp->getType())
7172         RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
7173     }
7174
7175     if (RHSOp)
7176       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7177   }
7178   
7179   // The code below only handles extension cast instructions, so far.
7180   // Enforce this.
7181   if (LHSCI->getOpcode() != Instruction::ZExt &&
7182       LHSCI->getOpcode() != Instruction::SExt)
7183     return 0;
7184
7185   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7186   bool isSignedCmp = ICI.isSigned();
7187
7188   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7189     // Not an extension from the same type?
7190     RHSCIOp = CI->getOperand(0);
7191     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7192       return 0;
7193     
7194     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7195     // and the other is a zext), then we can't handle this.
7196     if (CI->getOpcode() != LHSCI->getOpcode())
7197       return 0;
7198
7199     // Deal with equality cases early.
7200     if (ICI.isEquality())
7201       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7202
7203     // A signed comparison of sign extended values simplifies into a
7204     // signed comparison.
7205     if (isSignedCmp && isSignedExt)
7206       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7207
7208     // The other three cases all fold into an unsigned comparison.
7209     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7210   }
7211
7212   // If we aren't dealing with a constant on the RHS, exit early
7213   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7214   if (!CI)
7215     return 0;
7216
7217   // Compute the constant that would happen if we truncated to SrcTy then
7218   // reextended to DestTy.
7219   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7220   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7221                                                 Res1, DestTy);
7222
7223   // If the re-extended constant didn't change...
7224   if (Res2 == CI) {
7225     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7226     // For example, we might have:
7227     //    %A = sext i16 %X to i32
7228     //    %B = icmp ugt i32 %A, 1330
7229     // It is incorrect to transform this into 
7230     //    %B = icmp ugt i16 %X, 1330
7231     // because %A may have negative value. 
7232     //
7233     // However, we allow this when the compare is EQ/NE, because they are
7234     // signless.
7235     if (isSignedExt == isSignedCmp || ICI.isEquality())
7236       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7237     return 0;
7238   }
7239
7240   // The re-extended constant changed so the constant cannot be represented 
7241   // in the shorter type. Consequently, we cannot emit a simple comparison.
7242
7243   // First, handle some easy cases. We know the result cannot be equal at this
7244   // point so handle the ICI.isEquality() cases
7245   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7246     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7247   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7248     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7249
7250   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7251   // should have been folded away previously and not enter in here.
7252   Value *Result;
7253   if (isSignedCmp) {
7254     // We're performing a signed comparison.
7255     if (cast<ConstantInt>(CI)->getValue().isNegative())
7256       Result = ConstantInt::getFalse(*Context);          // X < (small) --> false
7257     else
7258       Result = ConstantInt::getTrue(*Context);           // X < (large) --> true
7259   } else {
7260     // We're performing an unsigned comparison.
7261     if (isSignedExt) {
7262       // We're performing an unsigned comp with a sign extended value.
7263       // This is true if the input is >= 0. [aka >s -1]
7264       Constant *NegOne = Constant::getAllOnesValue(SrcTy);
7265       Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
7266     } else {
7267       // Unsigned extend & unsigned compare -> always true.
7268       Result = ConstantInt::getTrue(*Context);
7269     }
7270   }
7271
7272   // Finally, return the value computed.
7273   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7274       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7275     return ReplaceInstUsesWith(ICI, Result);
7276
7277   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7278           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7279          "ICmp should be folded!");
7280   if (Constant *CI = dyn_cast<Constant>(Result))
7281     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7282   return BinaryOperator::CreateNot(Result);
7283 }
7284
7285 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7286   return commonShiftTransforms(I);
7287 }
7288
7289 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7290   return commonShiftTransforms(I);
7291 }
7292
7293 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7294   if (Instruction *R = commonShiftTransforms(I))
7295     return R;
7296   
7297   Value *Op0 = I.getOperand(0);
7298   
7299   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7300   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7301     if (CSI->isAllOnesValue())
7302       return ReplaceInstUsesWith(I, CSI);
7303
7304   // See if we can turn a signed shr into an unsigned shr.
7305   if (MaskedValueIsZero(Op0,
7306                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7307     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7308
7309   // Arithmetic shifting an all-sign-bit value is a no-op.
7310   unsigned NumSignBits = ComputeNumSignBits(Op0);
7311   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7312     return ReplaceInstUsesWith(I, Op0);
7313
7314   return 0;
7315 }
7316
7317 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7318   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7319   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7320
7321   // shl X, 0 == X and shr X, 0 == X
7322   // shl 0, X == 0 and shr 0, X == 0
7323   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7324       Op0 == Constant::getNullValue(Op0->getType()))
7325     return ReplaceInstUsesWith(I, Op0);
7326   
7327   if (isa<UndefValue>(Op0)) {            
7328     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7329       return ReplaceInstUsesWith(I, Op0);
7330     else                                    // undef << X -> 0, undef >>u X -> 0
7331       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7332   }
7333   if (isa<UndefValue>(Op1)) {
7334     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7335       return ReplaceInstUsesWith(I, Op0);          
7336     else                                     // X << undef, X >>u undef -> 0
7337       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7338   }
7339
7340   // See if we can fold away this shift.
7341   if (SimplifyDemandedInstructionBits(I))
7342     return &I;
7343
7344   // Try to fold constant and into select arguments.
7345   if (isa<Constant>(Op0))
7346     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7347       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7348         return R;
7349
7350   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7351     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7352       return Res;
7353   return 0;
7354 }
7355
7356 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7357                                                BinaryOperator &I) {
7358   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7359
7360   // See if we can simplify any instructions used by the instruction whose sole 
7361   // purpose is to compute bits we don't care about.
7362   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7363   
7364   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7365   // a signed shift.
7366   //
7367   if (Op1->uge(TypeBits)) {
7368     if (I.getOpcode() != Instruction::AShr)
7369       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7370     else {
7371       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7372       return &I;
7373     }
7374   }
7375   
7376   // ((X*C1) << C2) == (X * (C1 << C2))
7377   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7378     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7379       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7380         return BinaryOperator::CreateMul(BO->getOperand(0),
7381                                         ConstantExpr::getShl(BOOp, Op1));
7382   
7383   // Try to fold constant and into select arguments.
7384   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7385     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7386       return R;
7387   if (isa<PHINode>(Op0))
7388     if (Instruction *NV = FoldOpIntoPhi(I))
7389       return NV;
7390   
7391   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7392   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7393     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7394     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7395     // place.  Don't try to do this transformation in this case.  Also, we
7396     // require that the input operand is a shift-by-constant so that we have
7397     // confidence that the shifts will get folded together.  We could do this
7398     // xform in more cases, but it is unlikely to be profitable.
7399     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7400         isa<ConstantInt>(TrOp->getOperand(1))) {
7401       // Okay, we'll do this xform.  Make the shift of shift.
7402       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7403       // (shift2 (shift1 & 0x00FF), c2)
7404       Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
7405
7406       // For logical shifts, the truncation has the effect of making the high
7407       // part of the register be zeros.  Emulate this by inserting an AND to
7408       // clear the top bits as needed.  This 'and' will usually be zapped by
7409       // other xforms later if dead.
7410       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7411       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7412       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7413       
7414       // The mask we constructed says what the trunc would do if occurring
7415       // between the shifts.  We want to know the effect *after* the second
7416       // shift.  We know that it is a logical shift by a constant, so adjust the
7417       // mask as appropriate.
7418       if (I.getOpcode() == Instruction::Shl)
7419         MaskV <<= Op1->getZExtValue();
7420       else {
7421         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7422         MaskV = MaskV.lshr(Op1->getZExtValue());
7423       }
7424
7425       // shift1 & 0x00FF
7426       Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7427                                       TI->getName());
7428
7429       // Return the value truncated to the interesting size.
7430       return new TruncInst(And, I.getType());
7431     }
7432   }
7433   
7434   if (Op0->hasOneUse()) {
7435     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7436       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7437       Value *V1, *V2;
7438       ConstantInt *CC;
7439       switch (Op0BO->getOpcode()) {
7440         default: break;
7441         case Instruction::Add:
7442         case Instruction::And:
7443         case Instruction::Or:
7444         case Instruction::Xor: {
7445           // These operators commute.
7446           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7447           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7448               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7449                     m_Specific(Op1)))) {
7450             Value *YS =         // (Y << C)
7451               Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7452             // (X + (Y << C))
7453             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7454                                             Op0BO->getOperand(1)->getName());
7455             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7456             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7457                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7458           }
7459           
7460           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7461           Value *Op0BOOp1 = Op0BO->getOperand(1);
7462           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7463               match(Op0BOOp1, 
7464                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7465                           m_ConstantInt(CC))) &&
7466               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7467             Value *YS =   // (Y << C)
7468               Builder->CreateShl(Op0BO->getOperand(0), Op1,
7469                                            Op0BO->getName());
7470             // X & (CC << C)
7471             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7472                                            V1->getName()+".mask");
7473             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7474           }
7475         }
7476           
7477         // FALL THROUGH.
7478         case Instruction::Sub: {
7479           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7480           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7481               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7482                     m_Specific(Op1)))) {
7483             Value *YS =  // (Y << C)
7484               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7485             // (X + (Y << C))
7486             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7487                                             Op0BO->getOperand(0)->getName());
7488             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7489             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7490                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7491           }
7492           
7493           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7494           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7495               match(Op0BO->getOperand(0),
7496                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7497                           m_ConstantInt(CC))) && V2 == Op1 &&
7498               cast<BinaryOperator>(Op0BO->getOperand(0))
7499                   ->getOperand(0)->hasOneUse()) {
7500             Value *YS = // (Y << C)
7501               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7502             // X & (CC << C)
7503             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7504                                            V1->getName()+".mask");
7505             
7506             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7507           }
7508           
7509           break;
7510         }
7511       }
7512       
7513       
7514       // If the operand is an bitwise operator with a constant RHS, and the
7515       // shift is the only use, we can pull it out of the shift.
7516       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7517         bool isValid = true;     // Valid only for And, Or, Xor
7518         bool highBitSet = false; // Transform if high bit of constant set?
7519         
7520         switch (Op0BO->getOpcode()) {
7521           default: isValid = false; break;   // Do not perform transform!
7522           case Instruction::Add:
7523             isValid = isLeftShift;
7524             break;
7525           case Instruction::Or:
7526           case Instruction::Xor:
7527             highBitSet = false;
7528             break;
7529           case Instruction::And:
7530             highBitSet = true;
7531             break;
7532         }
7533         
7534         // If this is a signed shift right, and the high bit is modified
7535         // by the logical operation, do not perform the transformation.
7536         // The highBitSet boolean indicates the value of the high bit of
7537         // the constant which would cause it to be modified for this
7538         // operation.
7539         //
7540         if (isValid && I.getOpcode() == Instruction::AShr)
7541           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7542         
7543         if (isValid) {
7544           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7545           
7546           Value *NewShift =
7547             Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
7548           NewShift->takeName(Op0BO);
7549           
7550           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7551                                         NewRHS);
7552         }
7553       }
7554     }
7555   }
7556   
7557   // Find out if this is a shift of a shift by a constant.
7558   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7559   if (ShiftOp && !ShiftOp->isShift())
7560     ShiftOp = 0;
7561   
7562   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7563     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7564     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7565     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7566     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7567     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7568     Value *X = ShiftOp->getOperand(0);
7569     
7570     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7571     
7572     const IntegerType *Ty = cast<IntegerType>(I.getType());
7573     
7574     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7575     if (I.getOpcode() == ShiftOp->getOpcode()) {
7576       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7577       // saturates.
7578       if (AmtSum >= TypeBits) {
7579         if (I.getOpcode() != Instruction::AShr)
7580           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7581         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7582       }
7583       
7584       return BinaryOperator::Create(I.getOpcode(), X,
7585                                     ConstantInt::get(Ty, AmtSum));
7586     }
7587     
7588     if (ShiftOp->getOpcode() == Instruction::LShr &&
7589         I.getOpcode() == Instruction::AShr) {
7590       if (AmtSum >= TypeBits)
7591         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7592       
7593       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7594       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7595     }
7596     
7597     if (ShiftOp->getOpcode() == Instruction::AShr &&
7598         I.getOpcode() == Instruction::LShr) {
7599       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7600       if (AmtSum >= TypeBits)
7601         AmtSum = TypeBits-1;
7602       
7603       Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7604
7605       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7606       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
7607     }
7608     
7609     // Okay, if we get here, one shift must be left, and the other shift must be
7610     // right.  See if the amounts are equal.
7611     if (ShiftAmt1 == ShiftAmt2) {
7612       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7613       if (I.getOpcode() == Instruction::Shl) {
7614         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7615         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7616       }
7617       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7618       if (I.getOpcode() == Instruction::LShr) {
7619         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7620         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7621       }
7622       // We can simplify ((X << C) >>s C) into a trunc + sext.
7623       // NOTE: we could do this for any C, but that would make 'unusual' integer
7624       // types.  For now, just stick to ones well-supported by the code
7625       // generators.
7626       const Type *SExtType = 0;
7627       switch (Ty->getBitWidth() - ShiftAmt1) {
7628       case 1  :
7629       case 8  :
7630       case 16 :
7631       case 32 :
7632       case 64 :
7633       case 128:
7634         SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
7635         break;
7636       default: break;
7637       }
7638       if (SExtType)
7639         return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
7640       // Otherwise, we can't handle it yet.
7641     } else if (ShiftAmt1 < ShiftAmt2) {
7642       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7643       
7644       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7645       if (I.getOpcode() == Instruction::Shl) {
7646         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7647                ShiftOp->getOpcode() == Instruction::AShr);
7648         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7649         
7650         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7651         return BinaryOperator::CreateAnd(Shift,
7652                                          ConstantInt::get(*Context, Mask));
7653       }
7654       
7655       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7656       if (I.getOpcode() == Instruction::LShr) {
7657         assert(ShiftOp->getOpcode() == Instruction::Shl);
7658         Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7659         
7660         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7661         return BinaryOperator::CreateAnd(Shift,
7662                                          ConstantInt::get(*Context, Mask));
7663       }
7664       
7665       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7666     } else {
7667       assert(ShiftAmt2 < ShiftAmt1);
7668       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7669
7670       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7671       if (I.getOpcode() == Instruction::Shl) {
7672         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7673                ShiftOp->getOpcode() == Instruction::AShr);
7674         Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7675                                             ConstantInt::get(Ty, ShiftDiff));
7676         
7677         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7678         return BinaryOperator::CreateAnd(Shift,
7679                                          ConstantInt::get(*Context, Mask));
7680       }
7681       
7682       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7683       if (I.getOpcode() == Instruction::LShr) {
7684         assert(ShiftOp->getOpcode() == Instruction::Shl);
7685         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7686         
7687         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7688         return BinaryOperator::CreateAnd(Shift,
7689                                          ConstantInt::get(*Context, Mask));
7690       }
7691       
7692       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7693     }
7694   }
7695   return 0;
7696 }
7697
7698
7699 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7700 /// expression.  If so, decompose it, returning some value X, such that Val is
7701 /// X*Scale+Offset.
7702 ///
7703 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7704                                         int &Offset, LLVMContext *Context) {
7705   assert(Val->getType() == Type::getInt32Ty(*Context) && 
7706          "Unexpected allocation size type!");
7707   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7708     Offset = CI->getZExtValue();
7709     Scale  = 0;
7710     return ConstantInt::get(Type::getInt32Ty(*Context), 0);
7711   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7712     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7713       if (I->getOpcode() == Instruction::Shl) {
7714         // This is a value scaled by '1 << the shift amt'.
7715         Scale = 1U << RHS->getZExtValue();
7716         Offset = 0;
7717         return I->getOperand(0);
7718       } else if (I->getOpcode() == Instruction::Mul) {
7719         // This value is scaled by 'RHS'.
7720         Scale = RHS->getZExtValue();
7721         Offset = 0;
7722         return I->getOperand(0);
7723       } else if (I->getOpcode() == Instruction::Add) {
7724         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7725         // where C1 is divisible by C2.
7726         unsigned SubScale;
7727         Value *SubVal = 
7728           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7729                                     Offset, Context);
7730         Offset += RHS->getZExtValue();
7731         Scale = SubScale;
7732         return SubVal;
7733       }
7734     }
7735   }
7736
7737   // Otherwise, we can't look past this.
7738   Scale = 1;
7739   Offset = 0;
7740   return Val;
7741 }
7742
7743
7744 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7745 /// try to eliminate the cast by moving the type information into the alloc.
7746 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7747                                                    AllocaInst &AI) {
7748   const PointerType *PTy = cast<PointerType>(CI.getType());
7749   
7750   BuilderTy AllocaBuilder(*Builder);
7751   AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7752   
7753   // Remove any uses of AI that are dead.
7754   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7755   
7756   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7757     Instruction *User = cast<Instruction>(*UI++);
7758     if (isInstructionTriviallyDead(User)) {
7759       while (UI != E && *UI == User)
7760         ++UI; // If this instruction uses AI more than once, don't break UI.
7761       
7762       ++NumDeadInst;
7763       DEBUG(errs() << "IC: DCE: " << *User << '\n');
7764       EraseInstFromFunction(*User);
7765     }
7766   }
7767
7768   // This requires TargetData to get the alloca alignment and size information.
7769   if (!TD) return 0;
7770
7771   // Get the type really allocated and the type casted to.
7772   const Type *AllocElTy = AI.getAllocatedType();
7773   const Type *CastElTy = PTy->getElementType();
7774   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7775
7776   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7777   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7778   if (CastElTyAlign < AllocElTyAlign) return 0;
7779
7780   // If the allocation has multiple uses, only promote it if we are strictly
7781   // increasing the alignment of the resultant allocation.  If we keep it the
7782   // same, we open the door to infinite loops of various kinds.  (A reference
7783   // from a dbg.declare doesn't count as a use for this purpose.)
7784   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7785       CastElTyAlign == AllocElTyAlign) return 0;
7786
7787   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7788   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7789   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7790
7791   // See if we can satisfy the modulus by pulling a scale out of the array
7792   // size argument.
7793   unsigned ArraySizeScale;
7794   int ArrayOffset;
7795   Value *NumElements = // See if the array size is a decomposable linear expr.
7796     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7797                               ArrayOffset, Context);
7798  
7799   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7800   // do the xform.
7801   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7802       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7803
7804   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7805   Value *Amt = 0;
7806   if (Scale == 1) {
7807     Amt = NumElements;
7808   } else {
7809     Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
7810     // Insert before the alloca, not before the cast.
7811     Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
7812   }
7813   
7814   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7815     Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
7816     Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
7817   }
7818   
7819   AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7820   New->setAlignment(AI.getAlignment());
7821   New->takeName(&AI);
7822   
7823   // If the allocation has one real use plus a dbg.declare, just remove the
7824   // declare.
7825   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7826     EraseInstFromFunction(*DI);
7827   }
7828   // If the allocation has multiple real uses, insert a cast and change all
7829   // things that used it to use the new cast.  This will also hack on CI, but it
7830   // will die soon.
7831   else if (!AI.hasOneUse()) {
7832     // New is the allocation instruction, pointer typed. AI is the original
7833     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7834     Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
7835     AI.replaceAllUsesWith(NewCast);
7836   }
7837   return ReplaceInstUsesWith(CI, New);
7838 }
7839
7840 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7841 /// and return it as type Ty without inserting any new casts and without
7842 /// changing the computed value.  This is used by code that tries to decide
7843 /// whether promoting or shrinking integer operations to wider or smaller types
7844 /// will allow us to eliminate a truncate or extend.
7845 ///
7846 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7847 /// extension operation if Ty is larger.
7848 ///
7849 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7850 /// should return true if trunc(V) can be computed by computing V in the smaller
7851 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7852 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7853 /// efficiently truncated.
7854 ///
7855 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7856 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7857 /// the final result.
7858 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7859                                               unsigned CastOpc,
7860                                               int &NumCastsRemoved){
7861   // We can always evaluate constants in another type.
7862   if (isa<Constant>(V))
7863     return true;
7864   
7865   Instruction *I = dyn_cast<Instruction>(V);
7866   if (!I) return false;
7867   
7868   const Type *OrigTy = V->getType();
7869   
7870   // If this is an extension or truncate, we can often eliminate it.
7871   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7872     // If this is a cast from the destination type, we can trivially eliminate
7873     // it, and this will remove a cast overall.
7874     if (I->getOperand(0)->getType() == Ty) {
7875       // If the first operand is itself a cast, and is eliminable, do not count
7876       // this as an eliminable cast.  We would prefer to eliminate those two
7877       // casts first.
7878       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7879         ++NumCastsRemoved;
7880       return true;
7881     }
7882   }
7883
7884   // We can't extend or shrink something that has multiple uses: doing so would
7885   // require duplicating the instruction in general, which isn't profitable.
7886   if (!I->hasOneUse()) return false;
7887
7888   unsigned Opc = I->getOpcode();
7889   switch (Opc) {
7890   case Instruction::Add:
7891   case Instruction::Sub:
7892   case Instruction::Mul:
7893   case Instruction::And:
7894   case Instruction::Or:
7895   case Instruction::Xor:
7896     // These operators can all arbitrarily be extended or truncated.
7897     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7898                                       NumCastsRemoved) &&
7899            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7900                                       NumCastsRemoved);
7901
7902   case Instruction::UDiv:
7903   case Instruction::URem: {
7904     // UDiv and URem can be truncated if all the truncated bits are zero.
7905     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7906     uint32_t BitWidth = Ty->getScalarSizeInBits();
7907     if (BitWidth < OrigBitWidth) {
7908       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7909       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7910           MaskedValueIsZero(I->getOperand(1), Mask)) {
7911         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7912                                           NumCastsRemoved) &&
7913                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7914                                           NumCastsRemoved);
7915       }
7916     }
7917     break;
7918   }
7919   case Instruction::Shl:
7920     // If we are truncating the result of this SHL, and if it's a shift of a
7921     // constant amount, we can always perform a SHL in a smaller type.
7922     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7923       uint32_t BitWidth = Ty->getScalarSizeInBits();
7924       if (BitWidth < OrigTy->getScalarSizeInBits() &&
7925           CI->getLimitedValue(BitWidth) < BitWidth)
7926         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7927                                           NumCastsRemoved);
7928     }
7929     break;
7930   case Instruction::LShr:
7931     // If this is a truncate of a logical shr, we can truncate it to a smaller
7932     // lshr iff we know that the bits we would otherwise be shifting in are
7933     // already zeros.
7934     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7935       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7936       uint32_t BitWidth = Ty->getScalarSizeInBits();
7937       if (BitWidth < OrigBitWidth &&
7938           MaskedValueIsZero(I->getOperand(0),
7939             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7940           CI->getLimitedValue(BitWidth) < BitWidth) {
7941         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7942                                           NumCastsRemoved);
7943       }
7944     }
7945     break;
7946   case Instruction::ZExt:
7947   case Instruction::SExt:
7948   case Instruction::Trunc:
7949     // If this is the same kind of case as our original (e.g. zext+zext), we
7950     // can safely replace it.  Note that replacing it does not reduce the number
7951     // of casts in the input.
7952     if (Opc == CastOpc)
7953       return true;
7954
7955     // sext (zext ty1), ty2 -> zext ty2
7956     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7957       return true;
7958     break;
7959   case Instruction::Select: {
7960     SelectInst *SI = cast<SelectInst>(I);
7961     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7962                                       NumCastsRemoved) &&
7963            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7964                                       NumCastsRemoved);
7965   }
7966   case Instruction::PHI: {
7967     // We can change a phi if we can change all operands.
7968     PHINode *PN = cast<PHINode>(I);
7969     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7970       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7971                                       NumCastsRemoved))
7972         return false;
7973     return true;
7974   }
7975   default:
7976     // TODO: Can handle more cases here.
7977     break;
7978   }
7979   
7980   return false;
7981 }
7982
7983 /// EvaluateInDifferentType - Given an expression that 
7984 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7985 /// evaluate the expression.
7986 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7987                                              bool isSigned) {
7988   if (Constant *C = dyn_cast<Constant>(V))
7989     return ConstantExpr::getIntegerCast(C, Ty,
7990                                                isSigned /*Sext or ZExt*/);
7991
7992   // Otherwise, it must be an instruction.
7993   Instruction *I = cast<Instruction>(V);
7994   Instruction *Res = 0;
7995   unsigned Opc = I->getOpcode();
7996   switch (Opc) {
7997   case Instruction::Add:
7998   case Instruction::Sub:
7999   case Instruction::Mul:
8000   case Instruction::And:
8001   case Instruction::Or:
8002   case Instruction::Xor:
8003   case Instruction::AShr:
8004   case Instruction::LShr:
8005   case Instruction::Shl:
8006   case Instruction::UDiv:
8007   case Instruction::URem: {
8008     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8009     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8010     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8011     break;
8012   }    
8013   case Instruction::Trunc:
8014   case Instruction::ZExt:
8015   case Instruction::SExt:
8016     // If the source type of the cast is the type we're trying for then we can
8017     // just return the source.  There's no need to insert it because it is not
8018     // new.
8019     if (I->getOperand(0)->getType() == Ty)
8020       return I->getOperand(0);
8021     
8022     // Otherwise, must be the same type of cast, so just reinsert a new one.
8023     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8024                            Ty);
8025     break;
8026   case Instruction::Select: {
8027     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8028     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8029     Res = SelectInst::Create(I->getOperand(0), True, False);
8030     break;
8031   }
8032   case Instruction::PHI: {
8033     PHINode *OPN = cast<PHINode>(I);
8034     PHINode *NPN = PHINode::Create(Ty);
8035     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8036       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8037       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8038     }
8039     Res = NPN;
8040     break;
8041   }
8042   default: 
8043     // TODO: Can handle more cases here.
8044     llvm_unreachable("Unreachable!");
8045     break;
8046   }
8047   
8048   Res->takeName(I);
8049   return InsertNewInstBefore(Res, *I);
8050 }
8051
8052 /// @brief Implement the transforms common to all CastInst visitors.
8053 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8054   Value *Src = CI.getOperand(0);
8055
8056   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8057   // eliminate it now.
8058   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8059     if (Instruction::CastOps opc = 
8060         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8061       // The first cast (CSrc) is eliminable so we need to fix up or replace
8062       // the second cast (CI). CSrc will then have a good chance of being dead.
8063       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8064     }
8065   }
8066
8067   // If we are casting a select then fold the cast into the select
8068   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8069     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8070       return NV;
8071
8072   // If we are casting a PHI then fold the cast into the PHI
8073   if (isa<PHINode>(Src))
8074     if (Instruction *NV = FoldOpIntoPhi(CI))
8075       return NV;
8076   
8077   return 0;
8078 }
8079
8080 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8081 /// or not there is a sequence of GEP indices into the type that will land us at
8082 /// the specified offset.  If so, fill them into NewIndices and return the
8083 /// resultant element type, otherwise return null.
8084 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8085                                        SmallVectorImpl<Value*> &NewIndices,
8086                                        const TargetData *TD,
8087                                        LLVMContext *Context) {
8088   if (!TD) return 0;
8089   if (!Ty->isSized()) return 0;
8090   
8091   // Start with the index over the outer type.  Note that the type size
8092   // might be zero (even if the offset isn't zero) if the indexed type
8093   // is something like [0 x {int, int}]
8094   const Type *IntPtrTy = TD->getIntPtrType(*Context);
8095   int64_t FirstIdx = 0;
8096   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8097     FirstIdx = Offset/TySize;
8098     Offset -= FirstIdx*TySize;
8099     
8100     // Handle hosts where % returns negative instead of values [0..TySize).
8101     if (Offset < 0) {
8102       --FirstIdx;
8103       Offset += TySize;
8104       assert(Offset >= 0);
8105     }
8106     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8107   }
8108   
8109   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8110     
8111   // Index into the types.  If we fail, set OrigBase to null.
8112   while (Offset) {
8113     // Indexing into tail padding between struct/array elements.
8114     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8115       return 0;
8116     
8117     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8118       const StructLayout *SL = TD->getStructLayout(STy);
8119       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8120              "Offset must stay within the indexed type");
8121       
8122       unsigned Elt = SL->getElementContainingOffset(Offset);
8123       NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
8124       
8125       Offset -= SL->getElementOffset(Elt);
8126       Ty = STy->getElementType(Elt);
8127     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8128       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8129       assert(EltSize && "Cannot index into a zero-sized array");
8130       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8131       Offset %= EltSize;
8132       Ty = AT->getElementType();
8133     } else {
8134       // Otherwise, we can't index into the middle of this atomic type, bail.
8135       return 0;
8136     }
8137   }
8138   
8139   return Ty;
8140 }
8141
8142 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8143 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8144   Value *Src = CI.getOperand(0);
8145   
8146   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8147     // If casting the result of a getelementptr instruction with no offset, turn
8148     // this into a cast of the original pointer!
8149     if (GEP->hasAllZeroIndices()) {
8150       // Changing the cast operand is usually not a good idea but it is safe
8151       // here because the pointer operand is being replaced with another 
8152       // pointer operand so the opcode doesn't need to change.
8153       Worklist.Add(GEP);
8154       CI.setOperand(0, GEP->getOperand(0));
8155       return &CI;
8156     }
8157     
8158     // If the GEP has a single use, and the base pointer is a bitcast, and the
8159     // GEP computes a constant offset, see if we can convert these three
8160     // instructions into fewer.  This typically happens with unions and other
8161     // non-type-safe code.
8162     if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8163       if (GEP->hasAllConstantIndices()) {
8164         // We are guaranteed to get a constant from EmitGEPOffset.
8165         ConstantInt *OffsetV =
8166                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8167         int64_t Offset = OffsetV->getSExtValue();
8168         
8169         // Get the base pointer input of the bitcast, and the type it points to.
8170         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8171         const Type *GEPIdxTy =
8172           cast<PointerType>(OrigBase->getType())->getElementType();
8173         SmallVector<Value*, 8> NewIndices;
8174         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8175           // If we were able to index down into an element, create the GEP
8176           // and bitcast the result.  This eliminates one bitcast, potentially
8177           // two.
8178           Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8179             Builder->CreateInBoundsGEP(OrigBase,
8180                                        NewIndices.begin(), NewIndices.end()) :
8181             Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
8182           NGEP->takeName(GEP);
8183           
8184           if (isa<BitCastInst>(CI))
8185             return new BitCastInst(NGEP, CI.getType());
8186           assert(isa<PtrToIntInst>(CI));
8187           return new PtrToIntInst(NGEP, CI.getType());
8188         }
8189       }      
8190     }
8191   }
8192     
8193   return commonCastTransforms(CI);
8194 }
8195
8196 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8197 /// type like i42.  We don't want to introduce operations on random non-legal
8198 /// integer types where they don't already exist in the code.  In the future,
8199 /// we should consider making this based off target-data, so that 32-bit targets
8200 /// won't get i64 operations etc.
8201 static bool isSafeIntegerType(const Type *Ty) {
8202   switch (Ty->getPrimitiveSizeInBits()) {
8203   case 8:
8204   case 16:
8205   case 32:
8206   case 64:
8207     return true;
8208   default: 
8209     return false;
8210   }
8211 }
8212
8213 /// commonIntCastTransforms - This function implements the common transforms
8214 /// for trunc, zext, and sext.
8215 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8216   if (Instruction *Result = commonCastTransforms(CI))
8217     return Result;
8218
8219   Value *Src = CI.getOperand(0);
8220   const Type *SrcTy = Src->getType();
8221   const Type *DestTy = CI.getType();
8222   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8223   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8224
8225   // See if we can simplify any instructions used by the LHS whose sole 
8226   // purpose is to compute bits we don't care about.
8227   if (SimplifyDemandedInstructionBits(CI))
8228     return &CI;
8229
8230   // If the source isn't an instruction or has more than one use then we
8231   // can't do anything more. 
8232   Instruction *SrcI = dyn_cast<Instruction>(Src);
8233   if (!SrcI || !Src->hasOneUse())
8234     return 0;
8235
8236   // Attempt to propagate the cast into the instruction for int->int casts.
8237   int NumCastsRemoved = 0;
8238   // Only do this if the dest type is a simple type, don't convert the
8239   // expression tree to something weird like i93 unless the source is also
8240   // strange.
8241   if ((isSafeIntegerType(DestTy->getScalarType()) ||
8242        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8243       CanEvaluateInDifferentType(SrcI, DestTy,
8244                                  CI.getOpcode(), NumCastsRemoved)) {
8245     // If this cast is a truncate, evaluting in a different type always
8246     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8247     // we need to do an AND to maintain the clear top-part of the computation,
8248     // so we require that the input have eliminated at least one cast.  If this
8249     // is a sign extension, we insert two new casts (to do the extension) so we
8250     // require that two casts have been eliminated.
8251     bool DoXForm = false;
8252     bool JustReplace = false;
8253     switch (CI.getOpcode()) {
8254     default:
8255       // All the others use floating point so we shouldn't actually 
8256       // get here because of the check above.
8257       llvm_unreachable("Unknown cast type");
8258     case Instruction::Trunc:
8259       DoXForm = true;
8260       break;
8261     case Instruction::ZExt: {
8262       DoXForm = NumCastsRemoved >= 1;
8263       if (!DoXForm && 0) {
8264         // If it's unnecessary to issue an AND to clear the high bits, it's
8265         // always profitable to do this xform.
8266         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8267         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8268         if (MaskedValueIsZero(TryRes, Mask))
8269           return ReplaceInstUsesWith(CI, TryRes);
8270         
8271         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8272           if (TryI->use_empty())
8273             EraseInstFromFunction(*TryI);
8274       }
8275       break;
8276     }
8277     case Instruction::SExt: {
8278       DoXForm = NumCastsRemoved >= 2;
8279       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8280         // If we do not have to emit the truncate + sext pair, then it's always
8281         // profitable to do this xform.
8282         //
8283         // It's not safe to eliminate the trunc + sext pair if one of the
8284         // eliminated cast is a truncate. e.g.
8285         // t2 = trunc i32 t1 to i16
8286         // t3 = sext i16 t2 to i32
8287         // !=
8288         // i32 t1
8289         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8290         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8291         if (NumSignBits > (DestBitSize - SrcBitSize))
8292           return ReplaceInstUsesWith(CI, TryRes);
8293         
8294         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8295           if (TryI->use_empty())
8296             EraseInstFromFunction(*TryI);
8297       }
8298       break;
8299     }
8300     }
8301     
8302     if (DoXForm) {
8303       DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8304             " to avoid cast: " << CI);
8305       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8306                                            CI.getOpcode() == Instruction::SExt);
8307       if (JustReplace)
8308         // Just replace this cast with the result.
8309         return ReplaceInstUsesWith(CI, Res);
8310
8311       assert(Res->getType() == DestTy);
8312       switch (CI.getOpcode()) {
8313       default: llvm_unreachable("Unknown cast type!");
8314       case Instruction::Trunc:
8315         // Just replace this cast with the result.
8316         return ReplaceInstUsesWith(CI, Res);
8317       case Instruction::ZExt: {
8318         assert(SrcBitSize < DestBitSize && "Not a zext?");
8319
8320         // If the high bits are already zero, just replace this cast with the
8321         // result.
8322         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8323         if (MaskedValueIsZero(Res, Mask))
8324           return ReplaceInstUsesWith(CI, Res);
8325
8326         // We need to emit an AND to clear the high bits.
8327         Constant *C = ConstantInt::get(*Context, 
8328                                  APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8329         return BinaryOperator::CreateAnd(Res, C);
8330       }
8331       case Instruction::SExt: {
8332         // If the high bits are already filled with sign bit, just replace this
8333         // cast with the result.
8334         unsigned NumSignBits = ComputeNumSignBits(Res);
8335         if (NumSignBits > (DestBitSize - SrcBitSize))
8336           return ReplaceInstUsesWith(CI, Res);
8337
8338         // We need to emit a cast to truncate, then a cast to sext.
8339         return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
8340       }
8341       }
8342     }
8343   }
8344   
8345   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8346   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8347
8348   switch (SrcI->getOpcode()) {
8349   case Instruction::Add:
8350   case Instruction::Mul:
8351   case Instruction::And:
8352   case Instruction::Or:
8353   case Instruction::Xor:
8354     // If we are discarding information, rewrite.
8355     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8356       // Don't insert two casts unless at least one can be eliminated.
8357       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8358           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8359         Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8360         Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8361         return BinaryOperator::Create(
8362             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8363       }
8364     }
8365
8366     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8367     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8368         SrcI->getOpcode() == Instruction::Xor &&
8369         Op1 == ConstantInt::getTrue(*Context) &&
8370         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8371       Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
8372       return BinaryOperator::CreateXor(New,
8373                                       ConstantInt::get(CI.getType(), 1));
8374     }
8375     break;
8376
8377   case Instruction::Shl: {
8378     // Canonicalize trunc inside shl, if we can.
8379     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8380     if (CI && DestBitSize < SrcBitSize &&
8381         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8382       Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8383       Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8384       return BinaryOperator::CreateShl(Op0c, Op1c);
8385     }
8386     break;
8387   }
8388   }
8389   return 0;
8390 }
8391
8392 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8393   if (Instruction *Result = commonIntCastTransforms(CI))
8394     return Result;
8395   
8396   Value *Src = CI.getOperand(0);
8397   const Type *Ty = CI.getType();
8398   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8399   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8400
8401   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8402   if (DestBitWidth == 1) {
8403     Constant *One = ConstantInt::get(Src->getType(), 1);
8404     Src = Builder->CreateAnd(Src, One, "tmp");
8405     Value *Zero = Constant::getNullValue(Src->getType());
8406     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8407   }
8408
8409   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8410   ConstantInt *ShAmtV = 0;
8411   Value *ShiftOp = 0;
8412   if (Src->hasOneUse() &&
8413       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8414     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8415     
8416     // Get a mask for the bits shifting in.
8417     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8418     if (MaskedValueIsZero(ShiftOp, Mask)) {
8419       if (ShAmt >= DestBitWidth)        // All zeros.
8420         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8421       
8422       // Okay, we can shrink this.  Truncate the input, then return a new
8423       // shift.
8424       Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
8425       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8426       return BinaryOperator::CreateLShr(V1, V2);
8427     }
8428   }
8429   
8430   return 0;
8431 }
8432
8433 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8434 /// in order to eliminate the icmp.
8435 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8436                                              bool DoXform) {
8437   // If we are just checking for a icmp eq of a single bit and zext'ing it
8438   // to an integer, then shift the bit to the appropriate place and then
8439   // cast to integer to avoid the comparison.
8440   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8441     const APInt &Op1CV = Op1C->getValue();
8442       
8443     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8444     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8445     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8446         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8447       if (!DoXform) return ICI;
8448
8449       Value *In = ICI->getOperand(0);
8450       Value *Sh = ConstantInt::get(In->getType(),
8451                                    In->getType()->getScalarSizeInBits()-1);
8452       In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
8453       if (In->getType() != CI.getType())
8454         In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
8455
8456       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8457         Constant *One = ConstantInt::get(In->getType(), 1);
8458         In = Builder->CreateXor(In, One, In->getName()+".not");
8459       }
8460
8461       return ReplaceInstUsesWith(CI, In);
8462     }
8463       
8464       
8465       
8466     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8467     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8468     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8469     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8470     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8471     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8472     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8473     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8474     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8475         // This only works for EQ and NE
8476         ICI->isEquality()) {
8477       // If Op1C some other power of two, convert:
8478       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8479       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8480       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8481       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8482         
8483       APInt KnownZeroMask(~KnownZero);
8484       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8485         if (!DoXform) return ICI;
8486
8487         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8488         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8489           // (X&4) == 2 --> false
8490           // (X&4) != 2 --> true
8491           Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
8492           Res = ConstantExpr::getZExt(Res, CI.getType());
8493           return ReplaceInstUsesWith(CI, Res);
8494         }
8495           
8496         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8497         Value *In = ICI->getOperand(0);
8498         if (ShiftAmt) {
8499           // Perform a logical shr by shiftamt.
8500           // Insert the shift to put the result in the low bit.
8501           In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8502                                    In->getName()+".lobit");
8503         }
8504           
8505         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8506           Constant *One = ConstantInt::get(In->getType(), 1);
8507           In = Builder->CreateXor(In, One, "tmp");
8508         }
8509           
8510         if (CI.getType() == In->getType())
8511           return ReplaceInstUsesWith(CI, In);
8512         else
8513           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8514       }
8515     }
8516   }
8517
8518   return 0;
8519 }
8520
8521 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8522   // If one of the common conversion will work ..
8523   if (Instruction *Result = commonIntCastTransforms(CI))
8524     return Result;
8525
8526   Value *Src = CI.getOperand(0);
8527
8528   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8529   // types and if the sizes are just right we can convert this into a logical
8530   // 'and' which will be much cheaper than the pair of casts.
8531   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8532     // Get the sizes of the types involved.  We know that the intermediate type
8533     // will be smaller than A or C, but don't know the relation between A and C.
8534     Value *A = CSrc->getOperand(0);
8535     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8536     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8537     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8538     // If we're actually extending zero bits, then if
8539     // SrcSize <  DstSize: zext(a & mask)
8540     // SrcSize == DstSize: a & mask
8541     // SrcSize  > DstSize: trunc(a) & mask
8542     if (SrcSize < DstSize) {
8543       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8544       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8545       Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
8546       return new ZExtInst(And, CI.getType());
8547     }
8548     
8549     if (SrcSize == DstSize) {
8550       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8551       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8552                                                            AndValue));
8553     }
8554     if (SrcSize > DstSize) {
8555       Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
8556       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8557       return BinaryOperator::CreateAnd(Trunc, 
8558                                        ConstantInt::get(Trunc->getType(),
8559                                                                AndValue));
8560     }
8561   }
8562
8563   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8564     return transformZExtICmp(ICI, CI);
8565
8566   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8567   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8568     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8569     // of the (zext icmp) will be transformed.
8570     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8571     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8572     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8573         (transformZExtICmp(LHS, CI, false) ||
8574          transformZExtICmp(RHS, CI, false))) {
8575       Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8576       Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
8577       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8578     }
8579   }
8580
8581   // zext(trunc(t) & C) -> (t & zext(C)).
8582   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8583     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8584       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8585         Value *TI0 = TI->getOperand(0);
8586         if (TI0->getType() == CI.getType())
8587           return
8588             BinaryOperator::CreateAnd(TI0,
8589                                 ConstantExpr::getZExt(C, CI.getType()));
8590       }
8591
8592   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8593   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8594     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8595       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8596         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8597             And->getOperand(1) == C)
8598           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8599             Value *TI0 = TI->getOperand(0);
8600             if (TI0->getType() == CI.getType()) {
8601               Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8602               Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
8603               return BinaryOperator::CreateXor(NewAnd, ZC);
8604             }
8605           }
8606
8607   return 0;
8608 }
8609
8610 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8611   if (Instruction *I = commonIntCastTransforms(CI))
8612     return I;
8613   
8614   Value *Src = CI.getOperand(0);
8615   
8616   // Canonicalize sign-extend from i1 to a select.
8617   if (Src->getType() == Type::getInt1Ty(*Context))
8618     return SelectInst::Create(Src,
8619                               Constant::getAllOnesValue(CI.getType()),
8620                               Constant::getNullValue(CI.getType()));
8621
8622   // See if the value being truncated is already sign extended.  If so, just
8623   // eliminate the trunc/sext pair.
8624   if (Operator::getOpcode(Src) == Instruction::Trunc) {
8625     Value *Op = cast<User>(Src)->getOperand(0);
8626     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8627     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8628     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8629     unsigned NumSignBits = ComputeNumSignBits(Op);
8630
8631     if (OpBits == DestBits) {
8632       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8633       // bits, it is already ready.
8634       if (NumSignBits > DestBits-MidBits)
8635         return ReplaceInstUsesWith(CI, Op);
8636     } else if (OpBits < DestBits) {
8637       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8638       // bits, just sext from i32.
8639       if (NumSignBits > OpBits-MidBits)
8640         return new SExtInst(Op, CI.getType(), "tmp");
8641     } else {
8642       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8643       // bits, just truncate to i32.
8644       if (NumSignBits > OpBits-MidBits)
8645         return new TruncInst(Op, CI.getType(), "tmp");
8646     }
8647   }
8648
8649   // If the input is a shl/ashr pair of a same constant, then this is a sign
8650   // extension from a smaller value.  If we could trust arbitrary bitwidth
8651   // integers, we could turn this into a truncate to the smaller bit and then
8652   // use a sext for the whole extension.  Since we don't, look deeper and check
8653   // for a truncate.  If the source and dest are the same type, eliminate the
8654   // trunc and extend and just do shifts.  For example, turn:
8655   //   %a = trunc i32 %i to i8
8656   //   %b = shl i8 %a, 6
8657   //   %c = ashr i8 %b, 6
8658   //   %d = sext i8 %c to i32
8659   // into:
8660   //   %a = shl i32 %i, 30
8661   //   %d = ashr i32 %a, 30
8662   Value *A = 0;
8663   ConstantInt *BA = 0, *CA = 0;
8664   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8665                         m_ConstantInt(CA))) &&
8666       BA == CA && isa<TruncInst>(A)) {
8667     Value *I = cast<TruncInst>(A)->getOperand(0);
8668     if (I->getType() == CI.getType()) {
8669       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8670       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8671       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8672       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8673       I = Builder->CreateShl(I, ShAmtV, CI.getName());
8674       return BinaryOperator::CreateAShr(I, ShAmtV);
8675     }
8676   }
8677   
8678   return 0;
8679 }
8680
8681 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8682 /// in the specified FP type without changing its value.
8683 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8684                               LLVMContext *Context) {
8685   bool losesInfo;
8686   APFloat F = CFP->getValueAPF();
8687   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8688   if (!losesInfo)
8689     return ConstantFP::get(*Context, F);
8690   return 0;
8691 }
8692
8693 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8694 /// through it until we get the source value.
8695 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8696   if (Instruction *I = dyn_cast<Instruction>(V))
8697     if (I->getOpcode() == Instruction::FPExt)
8698       return LookThroughFPExtensions(I->getOperand(0), Context);
8699   
8700   // If this value is a constant, return the constant in the smallest FP type
8701   // that can accurately represent it.  This allows us to turn
8702   // (float)((double)X+2.0) into x+2.0f.
8703   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8704     if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
8705       return V;  // No constant folding of this.
8706     // See if the value can be truncated to float and then reextended.
8707     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8708       return V;
8709     if (CFP->getType() == Type::getDoubleTy(*Context))
8710       return V;  // Won't shrink.
8711     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8712       return V;
8713     // Don't try to shrink to various long double types.
8714   }
8715   
8716   return V;
8717 }
8718
8719 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8720   if (Instruction *I = commonCastTransforms(CI))
8721     return I;
8722   
8723   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8724   // smaller than the destination type, we can eliminate the truncate by doing
8725   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8726   // many builtins (sqrt, etc).
8727   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8728   if (OpI && OpI->hasOneUse()) {
8729     switch (OpI->getOpcode()) {
8730     default: break;
8731     case Instruction::FAdd:
8732     case Instruction::FSub:
8733     case Instruction::FMul:
8734     case Instruction::FDiv:
8735     case Instruction::FRem:
8736       const Type *SrcTy = OpI->getType();
8737       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8738       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8739       if (LHSTrunc->getType() != SrcTy && 
8740           RHSTrunc->getType() != SrcTy) {
8741         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8742         // If the source types were both smaller than the destination type of
8743         // the cast, do this xform.
8744         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8745             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8746           LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8747           RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
8748           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8749         }
8750       }
8751       break;  
8752     }
8753   }
8754   return 0;
8755 }
8756
8757 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8758   return commonCastTransforms(CI);
8759 }
8760
8761 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8762   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8763   if (OpI == 0)
8764     return commonCastTransforms(FI);
8765
8766   // fptoui(uitofp(X)) --> X
8767   // fptoui(sitofp(X)) --> X
8768   // This is safe if the intermediate type has enough bits in its mantissa to
8769   // accurately represent all values of X.  For example, do not do this with
8770   // i64->float->i64.  This is also safe for sitofp case, because any negative
8771   // 'X' value would cause an undefined result for the fptoui. 
8772   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8773       OpI->getOperand(0)->getType() == FI.getType() &&
8774       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8775                     OpI->getType()->getFPMantissaWidth())
8776     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8777
8778   return commonCastTransforms(FI);
8779 }
8780
8781 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8782   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8783   if (OpI == 0)
8784     return commonCastTransforms(FI);
8785   
8786   // fptosi(sitofp(X)) --> X
8787   // fptosi(uitofp(X)) --> X
8788   // This is safe if the intermediate type has enough bits in its mantissa to
8789   // accurately represent all values of X.  For example, do not do this with
8790   // i64->float->i64.  This is also safe for sitofp case, because any negative
8791   // 'X' value would cause an undefined result for the fptoui. 
8792   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8793       OpI->getOperand(0)->getType() == FI.getType() &&
8794       (int)FI.getType()->getScalarSizeInBits() <=
8795                     OpI->getType()->getFPMantissaWidth())
8796     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8797   
8798   return commonCastTransforms(FI);
8799 }
8800
8801 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8802   return commonCastTransforms(CI);
8803 }
8804
8805 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8806   return commonCastTransforms(CI);
8807 }
8808
8809 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8810   // If the destination integer type is smaller than the intptr_t type for
8811   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8812   // trunc to be exposed to other transforms.  Don't do this for extending
8813   // ptrtoint's, because we don't know if the target sign or zero extends its
8814   // pointers.
8815   if (TD &&
8816       CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8817     Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8818                                        TD->getIntPtrType(CI.getContext()),
8819                                        "tmp");
8820     return new TruncInst(P, CI.getType());
8821   }
8822   
8823   return commonPointerCastTransforms(CI);
8824 }
8825
8826 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8827   // If the source integer type is larger than the intptr_t type for
8828   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8829   // allows the trunc to be exposed to other transforms.  Don't do this for
8830   // extending inttoptr's, because we don't know if the target sign or zero
8831   // extends to pointers.
8832   if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
8833       TD->getPointerSizeInBits()) {
8834     Value *P = Builder->CreateTrunc(CI.getOperand(0),
8835                                     TD->getIntPtrType(CI.getContext()), "tmp");
8836     return new IntToPtrInst(P, CI.getType());
8837   }
8838   
8839   if (Instruction *I = commonCastTransforms(CI))
8840     return I;
8841
8842   return 0;
8843 }
8844
8845 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8846   // If the operands are integer typed then apply the integer transforms,
8847   // otherwise just apply the common ones.
8848   Value *Src = CI.getOperand(0);
8849   const Type *SrcTy = Src->getType();
8850   const Type *DestTy = CI.getType();
8851
8852   if (isa<PointerType>(SrcTy)) {
8853     if (Instruction *I = commonPointerCastTransforms(CI))
8854       return I;
8855   } else {
8856     if (Instruction *Result = commonCastTransforms(CI))
8857       return Result;
8858   }
8859
8860
8861   // Get rid of casts from one type to the same type. These are useless and can
8862   // be replaced by the operand.
8863   if (DestTy == Src->getType())
8864     return ReplaceInstUsesWith(CI, Src);
8865
8866   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8867     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8868     const Type *DstElTy = DstPTy->getElementType();
8869     const Type *SrcElTy = SrcPTy->getElementType();
8870     
8871     // If the address spaces don't match, don't eliminate the bitcast, which is
8872     // required for changing types.
8873     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8874       return 0;
8875     
8876     // If we are casting a alloca to a pointer to a type of the same
8877     // size, rewrite the allocation instruction to allocate the "right" type.
8878     // There is no need to modify malloc calls because it is their bitcast that
8879     // needs to be cleaned up.
8880     if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
8881       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8882         return V;
8883     
8884     // If the source and destination are pointers, and this cast is equivalent
8885     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8886     // This can enhance SROA and other transforms that want type-safe pointers.
8887     Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
8888     unsigned NumZeros = 0;
8889     while (SrcElTy != DstElTy && 
8890            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8891            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8892       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8893       ++NumZeros;
8894     }
8895
8896     // If we found a path from the src to dest, create the getelementptr now.
8897     if (SrcElTy == DstElTy) {
8898       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8899       return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8900                                                ((Instruction*) NULL));
8901     }
8902   }
8903
8904   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8905     if (DestVTy->getNumElements() == 1) {
8906       if (!isa<VectorType>(SrcTy)) {
8907         Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
8908         return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
8909                             Constant::getNullValue(Type::getInt32Ty(*Context)));
8910       }
8911       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8912     }
8913   }
8914
8915   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8916     if (SrcVTy->getNumElements() == 1) {
8917       if (!isa<VectorType>(DestTy)) {
8918         Value *Elem = 
8919           Builder->CreateExtractElement(Src,
8920                             Constant::getNullValue(Type::getInt32Ty(*Context)));
8921         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8922       }
8923     }
8924   }
8925
8926   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8927     if (SVI->hasOneUse()) {
8928       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8929       // a bitconvert to a vector with the same # elts.
8930       if (isa<VectorType>(DestTy) && 
8931           cast<VectorType>(DestTy)->getNumElements() ==
8932                 SVI->getType()->getNumElements() &&
8933           SVI->getType()->getNumElements() ==
8934             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8935         CastInst *Tmp;
8936         // If either of the operands is a cast from CI.getType(), then
8937         // evaluating the shuffle in the casted destination's type will allow
8938         // us to eliminate at least one cast.
8939         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8940              Tmp->getOperand(0)->getType() == DestTy) ||
8941             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8942              Tmp->getOperand(0)->getType() == DestTy)) {
8943           Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8944           Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
8945           // Return a new shuffle vector.  Use the same element ID's, as we
8946           // know the vector types match #elts.
8947           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8948         }
8949       }
8950     }
8951   }
8952   return 0;
8953 }
8954
8955 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8956 ///   %C = or %A, %B
8957 ///   %D = select %cond, %C, %A
8958 /// into:
8959 ///   %C = select %cond, %B, 0
8960 ///   %D = or %A, %C
8961 ///
8962 /// Assuming that the specified instruction is an operand to the select, return
8963 /// a bitmask indicating which operands of this instruction are foldable if they
8964 /// equal the other incoming value of the select.
8965 ///
8966 static unsigned GetSelectFoldableOperands(Instruction *I) {
8967   switch (I->getOpcode()) {
8968   case Instruction::Add:
8969   case Instruction::Mul:
8970   case Instruction::And:
8971   case Instruction::Or:
8972   case Instruction::Xor:
8973     return 3;              // Can fold through either operand.
8974   case Instruction::Sub:   // Can only fold on the amount subtracted.
8975   case Instruction::Shl:   // Can only fold on the shift amount.
8976   case Instruction::LShr:
8977   case Instruction::AShr:
8978     return 1;
8979   default:
8980     return 0;              // Cannot fold
8981   }
8982 }
8983
8984 /// GetSelectFoldableConstant - For the same transformation as the previous
8985 /// function, return the identity constant that goes into the select.
8986 static Constant *GetSelectFoldableConstant(Instruction *I,
8987                                            LLVMContext *Context) {
8988   switch (I->getOpcode()) {
8989   default: llvm_unreachable("This cannot happen!");
8990   case Instruction::Add:
8991   case Instruction::Sub:
8992   case Instruction::Or:
8993   case Instruction::Xor:
8994   case Instruction::Shl:
8995   case Instruction::LShr:
8996   case Instruction::AShr:
8997     return Constant::getNullValue(I->getType());
8998   case Instruction::And:
8999     return Constant::getAllOnesValue(I->getType());
9000   case Instruction::Mul:
9001     return ConstantInt::get(I->getType(), 1);
9002   }
9003 }
9004
9005 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9006 /// have the same opcode and only one use each.  Try to simplify this.
9007 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9008                                           Instruction *FI) {
9009   if (TI->getNumOperands() == 1) {
9010     // If this is a non-volatile load or a cast from the same type,
9011     // merge.
9012     if (TI->isCast()) {
9013       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9014         return 0;
9015     } else {
9016       return 0;  // unknown unary op.
9017     }
9018
9019     // Fold this by inserting a select from the input values.
9020     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9021                                           FI->getOperand(0), SI.getName()+".v");
9022     InsertNewInstBefore(NewSI, SI);
9023     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9024                             TI->getType());
9025   }
9026
9027   // Only handle binary operators here.
9028   if (!isa<BinaryOperator>(TI))
9029     return 0;
9030
9031   // Figure out if the operations have any operands in common.
9032   Value *MatchOp, *OtherOpT, *OtherOpF;
9033   bool MatchIsOpZero;
9034   if (TI->getOperand(0) == FI->getOperand(0)) {
9035     MatchOp  = TI->getOperand(0);
9036     OtherOpT = TI->getOperand(1);
9037     OtherOpF = FI->getOperand(1);
9038     MatchIsOpZero = true;
9039   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9040     MatchOp  = TI->getOperand(1);
9041     OtherOpT = TI->getOperand(0);
9042     OtherOpF = FI->getOperand(0);
9043     MatchIsOpZero = false;
9044   } else if (!TI->isCommutative()) {
9045     return 0;
9046   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9047     MatchOp  = TI->getOperand(0);
9048     OtherOpT = TI->getOperand(1);
9049     OtherOpF = FI->getOperand(0);
9050     MatchIsOpZero = true;
9051   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9052     MatchOp  = TI->getOperand(1);
9053     OtherOpT = TI->getOperand(0);
9054     OtherOpF = FI->getOperand(1);
9055     MatchIsOpZero = true;
9056   } else {
9057     return 0;
9058   }
9059
9060   // If we reach here, they do have operations in common.
9061   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9062                                          OtherOpF, SI.getName()+".v");
9063   InsertNewInstBefore(NewSI, SI);
9064
9065   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9066     if (MatchIsOpZero)
9067       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9068     else
9069       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9070   }
9071   llvm_unreachable("Shouldn't get here");
9072   return 0;
9073 }
9074
9075 static bool isSelect01(Constant *C1, Constant *C2) {
9076   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9077   if (!C1I)
9078     return false;
9079   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9080   if (!C2I)
9081     return false;
9082   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9083 }
9084
9085 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9086 /// facilitate further optimization.
9087 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9088                                             Value *FalseVal) {
9089   // See the comment above GetSelectFoldableOperands for a description of the
9090   // transformation we are doing here.
9091   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9092     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9093         !isa<Constant>(FalseVal)) {
9094       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9095         unsigned OpToFold = 0;
9096         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9097           OpToFold = 1;
9098         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9099           OpToFold = 2;
9100         }
9101
9102         if (OpToFold) {
9103           Constant *C = GetSelectFoldableConstant(TVI, Context);
9104           Value *OOp = TVI->getOperand(2-OpToFold);
9105           // Avoid creating select between 2 constants unless it's selecting
9106           // between 0 and 1.
9107           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9108             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9109             InsertNewInstBefore(NewSel, SI);
9110             NewSel->takeName(TVI);
9111             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9112               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9113             llvm_unreachable("Unknown instruction!!");
9114           }
9115         }
9116       }
9117     }
9118   }
9119
9120   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9121     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9122         !isa<Constant>(TrueVal)) {
9123       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9124         unsigned OpToFold = 0;
9125         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9126           OpToFold = 1;
9127         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9128           OpToFold = 2;
9129         }
9130
9131         if (OpToFold) {
9132           Constant *C = GetSelectFoldableConstant(FVI, Context);
9133           Value *OOp = FVI->getOperand(2-OpToFold);
9134           // Avoid creating select between 2 constants unless it's selecting
9135           // between 0 and 1.
9136           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9137             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9138             InsertNewInstBefore(NewSel, SI);
9139             NewSel->takeName(FVI);
9140             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9141               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9142             llvm_unreachable("Unknown instruction!!");
9143           }
9144         }
9145       }
9146     }
9147   }
9148
9149   return 0;
9150 }
9151
9152 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9153 /// ICmpInst as its first operand.
9154 ///
9155 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9156                                                    ICmpInst *ICI) {
9157   bool Changed = false;
9158   ICmpInst::Predicate Pred = ICI->getPredicate();
9159   Value *CmpLHS = ICI->getOperand(0);
9160   Value *CmpRHS = ICI->getOperand(1);
9161   Value *TrueVal = SI.getTrueValue();
9162   Value *FalseVal = SI.getFalseValue();
9163
9164   // Check cases where the comparison is with a constant that
9165   // can be adjusted to fit the min/max idiom. We may edit ICI in
9166   // place here, so make sure the select is the only user.
9167   if (ICI->hasOneUse())
9168     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9169       switch (Pred) {
9170       default: break;
9171       case ICmpInst::ICMP_ULT:
9172       case ICmpInst::ICMP_SLT: {
9173         // X < MIN ? T : F  -->  F
9174         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9175           return ReplaceInstUsesWith(SI, FalseVal);
9176         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9177         Constant *AdjustedRHS = SubOne(CI);
9178         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9179             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9180           Pred = ICmpInst::getSwappedPredicate(Pred);
9181           CmpRHS = AdjustedRHS;
9182           std::swap(FalseVal, TrueVal);
9183           ICI->setPredicate(Pred);
9184           ICI->setOperand(1, CmpRHS);
9185           SI.setOperand(1, TrueVal);
9186           SI.setOperand(2, FalseVal);
9187           Changed = true;
9188         }
9189         break;
9190       }
9191       case ICmpInst::ICMP_UGT:
9192       case ICmpInst::ICMP_SGT: {
9193         // X > MAX ? T : F  -->  F
9194         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9195           return ReplaceInstUsesWith(SI, FalseVal);
9196         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9197         Constant *AdjustedRHS = AddOne(CI);
9198         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9199             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9200           Pred = ICmpInst::getSwappedPredicate(Pred);
9201           CmpRHS = AdjustedRHS;
9202           std::swap(FalseVal, TrueVal);
9203           ICI->setPredicate(Pred);
9204           ICI->setOperand(1, CmpRHS);
9205           SI.setOperand(1, TrueVal);
9206           SI.setOperand(2, FalseVal);
9207           Changed = true;
9208         }
9209         break;
9210       }
9211       }
9212
9213       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9214       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9215       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9216       if (match(TrueVal, m_ConstantInt<-1>()) &&
9217           match(FalseVal, m_ConstantInt<0>()))
9218         Pred = ICI->getPredicate();
9219       else if (match(TrueVal, m_ConstantInt<0>()) &&
9220                match(FalseVal, m_ConstantInt<-1>()))
9221         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9222       
9223       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9224         // If we are just checking for a icmp eq of a single bit and zext'ing it
9225         // to an integer, then shift the bit to the appropriate place and then
9226         // cast to integer to avoid the comparison.
9227         const APInt &Op1CV = CI->getValue();
9228     
9229         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9230         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9231         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9232             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9233           Value *In = ICI->getOperand(0);
9234           Value *Sh = ConstantInt::get(In->getType(),
9235                                        In->getType()->getScalarSizeInBits()-1);
9236           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9237                                                         In->getName()+".lobit"),
9238                                    *ICI);
9239           if (In->getType() != SI.getType())
9240             In = CastInst::CreateIntegerCast(In, SI.getType(),
9241                                              true/*SExt*/, "tmp", ICI);
9242     
9243           if (Pred == ICmpInst::ICMP_SGT)
9244             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9245                                        In->getName()+".not"), *ICI);
9246     
9247           return ReplaceInstUsesWith(SI, In);
9248         }
9249       }
9250     }
9251
9252   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9253     // Transform (X == Y) ? X : Y  -> Y
9254     if (Pred == ICmpInst::ICMP_EQ)
9255       return ReplaceInstUsesWith(SI, FalseVal);
9256     // Transform (X != Y) ? X : Y  -> X
9257     if (Pred == ICmpInst::ICMP_NE)
9258       return ReplaceInstUsesWith(SI, TrueVal);
9259     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9260
9261   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9262     // Transform (X == Y) ? Y : X  -> X
9263     if (Pred == ICmpInst::ICMP_EQ)
9264       return ReplaceInstUsesWith(SI, FalseVal);
9265     // Transform (X != Y) ? Y : X  -> Y
9266     if (Pred == ICmpInst::ICMP_NE)
9267       return ReplaceInstUsesWith(SI, TrueVal);
9268     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9269   }
9270
9271   /// NOTE: if we wanted to, this is where to detect integer ABS
9272
9273   return Changed ? &SI : 0;
9274 }
9275
9276
9277 /// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9278 /// PHI node (but the two may be in different blocks).  See if the true/false
9279 /// values (V) are live in all of the predecessor blocks of the PHI.  For
9280 /// example, cases like this cannot be mapped:
9281 ///
9282 ///   X = phi [ C1, BB1], [C2, BB2]
9283 ///   Y = add
9284 ///   Z = select X, Y, 0
9285 ///
9286 /// because Y is not live in BB1/BB2.
9287 ///
9288 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9289                                                    const SelectInst &SI) {
9290   // If the value is a non-instruction value like a constant or argument, it
9291   // can always be mapped.
9292   const Instruction *I = dyn_cast<Instruction>(V);
9293   if (I == 0) return true;
9294   
9295   // If V is a PHI node defined in the same block as the condition PHI, we can
9296   // map the arguments.
9297   const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9298   
9299   if (const PHINode *VP = dyn_cast<PHINode>(I))
9300     if (VP->getParent() == CondPHI->getParent())
9301       return true;
9302   
9303   // Otherwise, if the PHI and select are defined in the same block and if V is
9304   // defined in a different block, then we can transform it.
9305   if (SI.getParent() == CondPHI->getParent() &&
9306       I->getParent() != CondPHI->getParent())
9307     return true;
9308   
9309   // Otherwise we have a 'hard' case and we can't tell without doing more
9310   // detailed dominator based analysis, punt.
9311   return false;
9312 }
9313
9314 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9315   Value *CondVal = SI.getCondition();
9316   Value *TrueVal = SI.getTrueValue();
9317   Value *FalseVal = SI.getFalseValue();
9318
9319   // select true, X, Y  -> X
9320   // select false, X, Y -> Y
9321   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9322     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9323
9324   // select C, X, X -> X
9325   if (TrueVal == FalseVal)
9326     return ReplaceInstUsesWith(SI, TrueVal);
9327
9328   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9329     return ReplaceInstUsesWith(SI, FalseVal);
9330   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9331     return ReplaceInstUsesWith(SI, TrueVal);
9332   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9333     if (isa<Constant>(TrueVal))
9334       return ReplaceInstUsesWith(SI, TrueVal);
9335     else
9336       return ReplaceInstUsesWith(SI, FalseVal);
9337   }
9338
9339   if (SI.getType() == Type::getInt1Ty(*Context)) {
9340     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9341       if (C->getZExtValue()) {
9342         // Change: A = select B, true, C --> A = or B, C
9343         return BinaryOperator::CreateOr(CondVal, FalseVal);
9344       } else {
9345         // Change: A = select B, false, C --> A = and !B, C
9346         Value *NotCond =
9347           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9348                                              "not."+CondVal->getName()), SI);
9349         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9350       }
9351     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9352       if (C->getZExtValue() == false) {
9353         // Change: A = select B, C, false --> A = and B, C
9354         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9355       } else {
9356         // Change: A = select B, C, true --> A = or !B, C
9357         Value *NotCond =
9358           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9359                                              "not."+CondVal->getName()), SI);
9360         return BinaryOperator::CreateOr(NotCond, TrueVal);
9361       }
9362     }
9363     
9364     // select a, b, a  -> a&b
9365     // select a, a, b  -> a|b
9366     if (CondVal == TrueVal)
9367       return BinaryOperator::CreateOr(CondVal, FalseVal);
9368     else if (CondVal == FalseVal)
9369       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9370   }
9371
9372   // Selecting between two integer constants?
9373   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9374     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9375       // select C, 1, 0 -> zext C to int
9376       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9377         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9378       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9379         // select C, 0, 1 -> zext !C to int
9380         Value *NotCond =
9381           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9382                                                "not."+CondVal->getName()), SI);
9383         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9384       }
9385
9386       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9387         // If one of the constants is zero (we know they can't both be) and we
9388         // have an icmp instruction with zero, and we have an 'and' with the
9389         // non-constant value, eliminate this whole mess.  This corresponds to
9390         // cases like this: ((X & 27) ? 27 : 0)
9391         if (TrueValC->isZero() || FalseValC->isZero())
9392           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9393               cast<Constant>(IC->getOperand(1))->isNullValue())
9394             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9395               if (ICA->getOpcode() == Instruction::And &&
9396                   isa<ConstantInt>(ICA->getOperand(1)) &&
9397                   (ICA->getOperand(1) == TrueValC ||
9398                    ICA->getOperand(1) == FalseValC) &&
9399                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9400                 // Okay, now we know that everything is set up, we just don't
9401                 // know whether we have a icmp_ne or icmp_eq and whether the 
9402                 // true or false val is the zero.
9403                 bool ShouldNotVal = !TrueValC->isZero();
9404                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9405                 Value *V = ICA;
9406                 if (ShouldNotVal)
9407                   V = InsertNewInstBefore(BinaryOperator::Create(
9408                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9409                 return ReplaceInstUsesWith(SI, V);
9410               }
9411       }
9412     }
9413
9414   // See if we are selecting two values based on a comparison of the two values.
9415   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9416     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9417       // Transform (X == Y) ? X : Y  -> Y
9418       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9419         // This is not safe in general for floating point:  
9420         // consider X== -0, Y== +0.
9421         // It becomes safe if either operand is a nonzero constant.
9422         ConstantFP *CFPt, *CFPf;
9423         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9424               !CFPt->getValueAPF().isZero()) ||
9425             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9426              !CFPf->getValueAPF().isZero()))
9427         return ReplaceInstUsesWith(SI, FalseVal);
9428       }
9429       // Transform (X != Y) ? X : Y  -> X
9430       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9431         return ReplaceInstUsesWith(SI, TrueVal);
9432       // NOTE: if we wanted to, this is where to detect MIN/MAX
9433
9434     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9435       // Transform (X == Y) ? Y : X  -> X
9436       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9437         // This is not safe in general for floating point:  
9438         // consider X== -0, Y== +0.
9439         // It becomes safe if either operand is a nonzero constant.
9440         ConstantFP *CFPt, *CFPf;
9441         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9442               !CFPt->getValueAPF().isZero()) ||
9443             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9444              !CFPf->getValueAPF().isZero()))
9445           return ReplaceInstUsesWith(SI, FalseVal);
9446       }
9447       // Transform (X != Y) ? Y : X  -> Y
9448       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9449         return ReplaceInstUsesWith(SI, TrueVal);
9450       // NOTE: if we wanted to, this is where to detect MIN/MAX
9451     }
9452     // NOTE: if we wanted to, this is where to detect ABS
9453   }
9454
9455   // See if we are selecting two values based on a comparison of the two values.
9456   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9457     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9458       return Result;
9459
9460   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9461     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9462       if (TI->hasOneUse() && FI->hasOneUse()) {
9463         Instruction *AddOp = 0, *SubOp = 0;
9464
9465         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9466         if (TI->getOpcode() == FI->getOpcode())
9467           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9468             return IV;
9469
9470         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9471         // even legal for FP.
9472         if ((TI->getOpcode() == Instruction::Sub &&
9473              FI->getOpcode() == Instruction::Add) ||
9474             (TI->getOpcode() == Instruction::FSub &&
9475              FI->getOpcode() == Instruction::FAdd)) {
9476           AddOp = FI; SubOp = TI;
9477         } else if ((FI->getOpcode() == Instruction::Sub &&
9478                     TI->getOpcode() == Instruction::Add) ||
9479                    (FI->getOpcode() == Instruction::FSub &&
9480                     TI->getOpcode() == Instruction::FAdd)) {
9481           AddOp = TI; SubOp = FI;
9482         }
9483
9484         if (AddOp) {
9485           Value *OtherAddOp = 0;
9486           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9487             OtherAddOp = AddOp->getOperand(1);
9488           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9489             OtherAddOp = AddOp->getOperand(0);
9490           }
9491
9492           if (OtherAddOp) {
9493             // So at this point we know we have (Y -> OtherAddOp):
9494             //        select C, (add X, Y), (sub X, Z)
9495             Value *NegVal;  // Compute -Z
9496             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9497               NegVal = ConstantExpr::getNeg(C);
9498             } else {
9499               NegVal = InsertNewInstBefore(
9500                     BinaryOperator::CreateNeg(SubOp->getOperand(1),
9501                                               "tmp"), SI);
9502             }
9503
9504             Value *NewTrueOp = OtherAddOp;
9505             Value *NewFalseOp = NegVal;
9506             if (AddOp != TI)
9507               std::swap(NewTrueOp, NewFalseOp);
9508             Instruction *NewSel =
9509               SelectInst::Create(CondVal, NewTrueOp,
9510                                  NewFalseOp, SI.getName() + ".p");
9511
9512             NewSel = InsertNewInstBefore(NewSel, SI);
9513             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9514           }
9515         }
9516       }
9517
9518   // See if we can fold the select into one of our operands.
9519   if (SI.getType()->isInteger()) {
9520     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9521     if (FoldI)
9522       return FoldI;
9523   }
9524
9525   // See if we can fold the select into a phi node if the condition is a select.
9526   if (isa<PHINode>(SI.getCondition())) 
9527     // The true/false values have to be live in the PHI predecessor's blocks.
9528     if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
9529         CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
9530       if (Instruction *NV = FoldOpIntoPhi(SI))
9531         return NV;
9532
9533   if (BinaryOperator::isNot(CondVal)) {
9534     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9535     SI.setOperand(1, FalseVal);
9536     SI.setOperand(2, TrueVal);
9537     return &SI;
9538   }
9539
9540   return 0;
9541 }
9542
9543 /// EnforceKnownAlignment - If the specified pointer points to an object that
9544 /// we control, modify the object's alignment to PrefAlign. This isn't
9545 /// often possible though. If alignment is important, a more reliable approach
9546 /// is to simply align all global variables and allocation instructions to
9547 /// their preferred alignment from the beginning.
9548 ///
9549 static unsigned EnforceKnownAlignment(Value *V,
9550                                       unsigned Align, unsigned PrefAlign) {
9551
9552   User *U = dyn_cast<User>(V);
9553   if (!U) return Align;
9554
9555   switch (Operator::getOpcode(U)) {
9556   default: break;
9557   case Instruction::BitCast:
9558     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9559   case Instruction::GetElementPtr: {
9560     // If all indexes are zero, it is just the alignment of the base pointer.
9561     bool AllZeroOperands = true;
9562     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9563       if (!isa<Constant>(*i) ||
9564           !cast<Constant>(*i)->isNullValue()) {
9565         AllZeroOperands = false;
9566         break;
9567       }
9568
9569     if (AllZeroOperands) {
9570       // Treat this like a bitcast.
9571       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9572     }
9573     break;
9574   }
9575   }
9576
9577   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9578     // If there is a large requested alignment and we can, bump up the alignment
9579     // of the global.
9580     if (!GV->isDeclaration()) {
9581       if (GV->getAlignment() >= PrefAlign)
9582         Align = GV->getAlignment();
9583       else {
9584         GV->setAlignment(PrefAlign);
9585         Align = PrefAlign;
9586       }
9587     }
9588   } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9589     // If there is a requested alignment and if this is an alloca, round up.
9590     if (AI->getAlignment() >= PrefAlign)
9591       Align = AI->getAlignment();
9592     else {
9593       AI->setAlignment(PrefAlign);
9594       Align = PrefAlign;
9595     }
9596   }
9597
9598   return Align;
9599 }
9600
9601 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9602 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9603 /// and it is more than the alignment of the ultimate object, see if we can
9604 /// increase the alignment of the ultimate object, making this check succeed.
9605 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9606                                                   unsigned PrefAlign) {
9607   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9608                       sizeof(PrefAlign) * CHAR_BIT;
9609   APInt Mask = APInt::getAllOnesValue(BitWidth);
9610   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9611   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9612   unsigned TrailZ = KnownZero.countTrailingOnes();
9613   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9614
9615   if (PrefAlign > Align)
9616     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9617   
9618     // We don't need to make any adjustment.
9619   return Align;
9620 }
9621
9622 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9623   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9624   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9625   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9626   unsigned CopyAlign = MI->getAlignment();
9627
9628   if (CopyAlign < MinAlign) {
9629     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), 
9630                                              MinAlign, false));
9631     return MI;
9632   }
9633   
9634   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9635   // load/store.
9636   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9637   if (MemOpLength == 0) return 0;
9638   
9639   // Source and destination pointer types are always "i8*" for intrinsic.  See
9640   // if the size is something we can handle with a single primitive load/store.
9641   // A single load+store correctly handles overlapping memory in the memmove
9642   // case.
9643   unsigned Size = MemOpLength->getZExtValue();
9644   if (Size == 0) return MI;  // Delete this mem transfer.
9645   
9646   if (Size > 8 || (Size&(Size-1)))
9647     return 0;  // If not 1/2/4/8 bytes, exit.
9648   
9649   // Use an integer load+store unless we can find something better.
9650   Type *NewPtrTy =
9651                 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
9652   
9653   // Memcpy forces the use of i8* for the source and destination.  That means
9654   // that if you're using memcpy to move one double around, you'll get a cast
9655   // from double* to i8*.  We'd much rather use a double load+store rather than
9656   // an i64 load+store, here because this improves the odds that the source or
9657   // dest address will be promotable.  See if we can find a better type than the
9658   // integer datatype.
9659   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9660     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9661     if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9662       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9663       // down through these levels if so.
9664       while (!SrcETy->isSingleValueType()) {
9665         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9666           if (STy->getNumElements() == 1)
9667             SrcETy = STy->getElementType(0);
9668           else
9669             break;
9670         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9671           if (ATy->getNumElements() == 1)
9672             SrcETy = ATy->getElementType();
9673           else
9674             break;
9675         } else
9676           break;
9677       }
9678       
9679       if (SrcETy->isSingleValueType())
9680         NewPtrTy = PointerType::getUnqual(SrcETy);
9681     }
9682   }
9683   
9684   
9685   // If the memcpy/memmove provides better alignment info than we can
9686   // infer, use it.
9687   SrcAlign = std::max(SrcAlign, CopyAlign);
9688   DstAlign = std::max(DstAlign, CopyAlign);
9689   
9690   Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9691   Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
9692   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9693   InsertNewInstBefore(L, *MI);
9694   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9695
9696   // Set the size of the copy to 0, it will be deleted on the next iteration.
9697   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9698   return MI;
9699 }
9700
9701 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9702   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9703   if (MI->getAlignment() < Alignment) {
9704     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9705                                              Alignment, false));
9706     return MI;
9707   }
9708   
9709   // Extract the length and alignment and fill if they are constant.
9710   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9711   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9712   if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
9713     return 0;
9714   uint64_t Len = LenC->getZExtValue();
9715   Alignment = MI->getAlignment();
9716   
9717   // If the length is zero, this is a no-op
9718   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9719   
9720   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9721   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9722     const Type *ITy = IntegerType::get(*Context, Len*8);  // n=1 -> i8.
9723     
9724     Value *Dest = MI->getDest();
9725     Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
9726
9727     // Alignment 0 is identity for alignment 1 for memset, but not store.
9728     if (Alignment == 0) Alignment = 1;
9729     
9730     // Extract the fill value and store.
9731     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9732     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
9733                                       Dest, false, Alignment), *MI);
9734     
9735     // Set the size of the copy to 0, it will be deleted on the next iteration.
9736     MI->setLength(Constant::getNullValue(LenC->getType()));
9737     return MI;
9738   }
9739
9740   return 0;
9741 }
9742
9743
9744 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9745 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9746 /// the heavy lifting.
9747 ///
9748 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9749   if (isFreeCall(&CI))
9750     return visitFree(CI);
9751
9752   // If the caller function is nounwind, mark the call as nounwind, even if the
9753   // callee isn't.
9754   if (CI.getParent()->getParent()->doesNotThrow() &&
9755       !CI.doesNotThrow()) {
9756     CI.setDoesNotThrow();
9757     return &CI;
9758   }
9759   
9760   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9761   if (!II) return visitCallSite(&CI);
9762   
9763   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9764   // visitCallSite.
9765   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9766     bool Changed = false;
9767
9768     // memmove/cpy/set of zero bytes is a noop.
9769     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9770       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9771
9772       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9773         if (CI->getZExtValue() == 1) {
9774           // Replace the instruction with just byte operations.  We would
9775           // transform other cases to loads/stores, but we don't know if
9776           // alignment is sufficient.
9777         }
9778     }
9779
9780     // If we have a memmove and the source operation is a constant global,
9781     // then the source and dest pointers can't alias, so we can change this
9782     // into a call to memcpy.
9783     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9784       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9785         if (GVSrc->isConstant()) {
9786           Module *M = CI.getParent()->getParent()->getParent();
9787           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9788           const Type *Tys[1];
9789           Tys[0] = CI.getOperand(3)->getType();
9790           CI.setOperand(0, 
9791                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9792           Changed = true;
9793         }
9794
9795       // memmove(x,x,size) -> noop.
9796       if (MMI->getSource() == MMI->getDest())
9797         return EraseInstFromFunction(CI);
9798     }
9799
9800     // If we can determine a pointer alignment that is bigger than currently
9801     // set, update the alignment.
9802     if (isa<MemTransferInst>(MI)) {
9803       if (Instruction *I = SimplifyMemTransfer(MI))
9804         return I;
9805     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9806       if (Instruction *I = SimplifyMemSet(MSI))
9807         return I;
9808     }
9809           
9810     if (Changed) return II;
9811   }
9812   
9813   switch (II->getIntrinsicID()) {
9814   default: break;
9815   case Intrinsic::bswap:
9816     // bswap(bswap(x)) -> x
9817     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9818       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9819         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9820     break;
9821   case Intrinsic::ppc_altivec_lvx:
9822   case Intrinsic::ppc_altivec_lvxl:
9823   case Intrinsic::x86_sse_loadu_ps:
9824   case Intrinsic::x86_sse2_loadu_pd:
9825   case Intrinsic::x86_sse2_loadu_dq:
9826     // Turn PPC lvx     -> load if the pointer is known aligned.
9827     // Turn X86 loadups -> load if the pointer is known aligned.
9828     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9829       Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9830                                          PointerType::getUnqual(II->getType()));
9831       return new LoadInst(Ptr);
9832     }
9833     break;
9834   case Intrinsic::ppc_altivec_stvx:
9835   case Intrinsic::ppc_altivec_stvxl:
9836     // Turn stvx -> store if the pointer is known aligned.
9837     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9838       const Type *OpPtrTy = 
9839         PointerType::getUnqual(II->getOperand(1)->getType());
9840       Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
9841       return new StoreInst(II->getOperand(1), Ptr);
9842     }
9843     break;
9844   case Intrinsic::x86_sse_storeu_ps:
9845   case Intrinsic::x86_sse2_storeu_pd:
9846   case Intrinsic::x86_sse2_storeu_dq:
9847     // Turn X86 storeu -> store if the pointer is known aligned.
9848     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9849       const Type *OpPtrTy = 
9850         PointerType::getUnqual(II->getOperand(2)->getType());
9851       Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
9852       return new StoreInst(II->getOperand(2), Ptr);
9853     }
9854     break;
9855     
9856   case Intrinsic::x86_sse_cvttss2si: {
9857     // These intrinsics only demands the 0th element of its input vector.  If
9858     // we can simplify the input based on that, do so now.
9859     unsigned VWidth =
9860       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9861     APInt DemandedElts(VWidth, 1);
9862     APInt UndefElts(VWidth, 0);
9863     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9864                                               UndefElts)) {
9865       II->setOperand(1, V);
9866       return II;
9867     }
9868     break;
9869   }
9870     
9871   case Intrinsic::ppc_altivec_vperm:
9872     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9873     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9874       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9875       
9876       // Check that all of the elements are integer constants or undefs.
9877       bool AllEltsOk = true;
9878       for (unsigned i = 0; i != 16; ++i) {
9879         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9880             !isa<UndefValue>(Mask->getOperand(i))) {
9881           AllEltsOk = false;
9882           break;
9883         }
9884       }
9885       
9886       if (AllEltsOk) {
9887         // Cast the input vectors to byte vectors.
9888         Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9889         Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
9890         Value *Result = UndefValue::get(Op0->getType());
9891         
9892         // Only extract each element once.
9893         Value *ExtractedElts[32];
9894         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9895         
9896         for (unsigned i = 0; i != 16; ++i) {
9897           if (isa<UndefValue>(Mask->getOperand(i)))
9898             continue;
9899           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9900           Idx &= 31;  // Match the hardware behavior.
9901           
9902           if (ExtractedElts[Idx] == 0) {
9903             ExtractedElts[Idx] = 
9904               Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1, 
9905                   ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9906                                             "tmp");
9907           }
9908         
9909           // Insert this value into the result vector.
9910           Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9911                          ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9912                                                 "tmp");
9913         }
9914         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9915       }
9916     }
9917     break;
9918
9919   case Intrinsic::stackrestore: {
9920     // If the save is right next to the restore, remove the restore.  This can
9921     // happen when variable allocas are DCE'd.
9922     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9923       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9924         BasicBlock::iterator BI = SS;
9925         if (&*++BI == II)
9926           return EraseInstFromFunction(CI);
9927       }
9928     }
9929     
9930     // Scan down this block to see if there is another stack restore in the
9931     // same block without an intervening call/alloca.
9932     BasicBlock::iterator BI = II;
9933     TerminatorInst *TI = II->getParent()->getTerminator();
9934     bool CannotRemove = false;
9935     for (++BI; &*BI != TI; ++BI) {
9936       if (isa<AllocaInst>(BI) || isMalloc(BI)) {
9937         CannotRemove = true;
9938         break;
9939       }
9940       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9941         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9942           // If there is a stackrestore below this one, remove this one.
9943           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9944             return EraseInstFromFunction(CI);
9945           // Otherwise, ignore the intrinsic.
9946         } else {
9947           // If we found a non-intrinsic call, we can't remove the stack
9948           // restore.
9949           CannotRemove = true;
9950           break;
9951         }
9952       }
9953     }
9954     
9955     // If the stack restore is in a return/unwind block and if there are no
9956     // allocas or calls between the restore and the return, nuke the restore.
9957     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9958       return EraseInstFromFunction(CI);
9959     break;
9960   }
9961   }
9962
9963   return visitCallSite(II);
9964 }
9965
9966 // InvokeInst simplification
9967 //
9968 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9969   return visitCallSite(&II);
9970 }
9971
9972 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9973 /// passed through the varargs area, we can eliminate the use of the cast.
9974 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9975                                          const CastInst * const CI,
9976                                          const TargetData * const TD,
9977                                          const int ix) {
9978   if (!CI->isLosslessCast())
9979     return false;
9980
9981   // The size of ByVal arguments is derived from the type, so we
9982   // can't change to a type with a different size.  If the size were
9983   // passed explicitly we could avoid this check.
9984   if (!CS.paramHasAttr(ix, Attribute::ByVal))
9985     return true;
9986
9987   const Type* SrcTy = 
9988             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9989   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9990   if (!SrcTy->isSized() || !DstTy->isSized())
9991     return false;
9992   if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
9993     return false;
9994   return true;
9995 }
9996
9997 // visitCallSite - Improvements for call and invoke instructions.
9998 //
9999 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10000   bool Changed = false;
10001
10002   // If the callee is a constexpr cast of a function, attempt to move the cast
10003   // to the arguments of the call/invoke.
10004   if (transformConstExprCastCall(CS)) return 0;
10005
10006   Value *Callee = CS.getCalledValue();
10007
10008   if (Function *CalleeF = dyn_cast<Function>(Callee))
10009     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10010       Instruction *OldCall = CS.getInstruction();
10011       // If the call and callee calling conventions don't match, this call must
10012       // be unreachable, as the call is undefined.
10013       new StoreInst(ConstantInt::getTrue(*Context),
10014                 UndefValue::get(Type::getInt1PtrTy(*Context)), 
10015                                   OldCall);
10016       // If OldCall dues not return void then replaceAllUsesWith undef.
10017       // This allows ValueHandlers and custom metadata to adjust itself.
10018       if (!OldCall->getType()->isVoidTy())
10019         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
10020       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10021         return EraseInstFromFunction(*OldCall);
10022       return 0;
10023     }
10024
10025   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10026     // This instruction is not reachable, just remove it.  We insert a store to
10027     // undef so that we know that this code is not reachable, despite the fact
10028     // that we can't modify the CFG here.
10029     new StoreInst(ConstantInt::getTrue(*Context),
10030                UndefValue::get(Type::getInt1PtrTy(*Context)),
10031                   CS.getInstruction());
10032
10033     // If CS dues not return void then replaceAllUsesWith undef.
10034     // This allows ValueHandlers and custom metadata to adjust itself.
10035     if (!CS.getInstruction()->getType()->isVoidTy())
10036       CS.getInstruction()->
10037         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
10038
10039     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10040       // Don't break the CFG, insert a dummy cond branch.
10041       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10042                          ConstantInt::getTrue(*Context), II);
10043     }
10044     return EraseInstFromFunction(*CS.getInstruction());
10045   }
10046
10047   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10048     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10049       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10050         return transformCallThroughTrampoline(CS);
10051
10052   const PointerType *PTy = cast<PointerType>(Callee->getType());
10053   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10054   if (FTy->isVarArg()) {
10055     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10056     // See if we can optimize any arguments passed through the varargs area of
10057     // the call.
10058     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10059            E = CS.arg_end(); I != E; ++I, ++ix) {
10060       CastInst *CI = dyn_cast<CastInst>(*I);
10061       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10062         *I = CI->getOperand(0);
10063         Changed = true;
10064       }
10065     }
10066   }
10067
10068   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10069     // Inline asm calls cannot throw - mark them 'nounwind'.
10070     CS.setDoesNotThrow();
10071     Changed = true;
10072   }
10073
10074   return Changed ? CS.getInstruction() : 0;
10075 }
10076
10077 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10078 // attempt to move the cast to the arguments of the call/invoke.
10079 //
10080 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10081   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10082   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10083   if (CE->getOpcode() != Instruction::BitCast || 
10084       !isa<Function>(CE->getOperand(0)))
10085     return false;
10086   Function *Callee = cast<Function>(CE->getOperand(0));
10087   Instruction *Caller = CS.getInstruction();
10088   const AttrListPtr &CallerPAL = CS.getAttributes();
10089
10090   // Okay, this is a cast from a function to a different type.  Unless doing so
10091   // would cause a type conversion of one of our arguments, change this call to
10092   // be a direct call with arguments casted to the appropriate types.
10093   //
10094   const FunctionType *FT = Callee->getFunctionType();
10095   const Type *OldRetTy = Caller->getType();
10096   const Type *NewRetTy = FT->getReturnType();
10097
10098   if (isa<StructType>(NewRetTy))
10099     return false; // TODO: Handle multiple return values.
10100
10101   // Check to see if we are changing the return type...
10102   if (OldRetTy != NewRetTy) {
10103     if (Callee->isDeclaration() &&
10104         // Conversion is ok if changing from one pointer type to another or from
10105         // a pointer to an integer of the same size.
10106         !((isa<PointerType>(OldRetTy) || !TD ||
10107            OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
10108           (isa<PointerType>(NewRetTy) || !TD ||
10109            NewRetTy == TD->getIntPtrType(Caller->getContext()))))
10110       return false;   // Cannot transform this return value.
10111
10112     if (!Caller->use_empty() &&
10113         // void -> non-void is handled specially
10114         !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
10115       return false;   // Cannot transform this return value.
10116
10117     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10118       Attributes RAttrs = CallerPAL.getRetAttributes();
10119       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10120         return false;   // Attribute not compatible with transformed value.
10121     }
10122
10123     // If the callsite is an invoke instruction, and the return value is used by
10124     // a PHI node in a successor, we cannot change the return type of the call
10125     // because there is no place to put the cast instruction (without breaking
10126     // the critical edge).  Bail out in this case.
10127     if (!Caller->use_empty())
10128       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10129         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10130              UI != E; ++UI)
10131           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10132             if (PN->getParent() == II->getNormalDest() ||
10133                 PN->getParent() == II->getUnwindDest())
10134               return false;
10135   }
10136
10137   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10138   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10139
10140   CallSite::arg_iterator AI = CS.arg_begin();
10141   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10142     const Type *ParamTy = FT->getParamType(i);
10143     const Type *ActTy = (*AI)->getType();
10144
10145     if (!CastInst::isCastable(ActTy, ParamTy))
10146       return false;   // Cannot transform this parameter value.
10147
10148     if (CallerPAL.getParamAttributes(i + 1) 
10149         & Attribute::typeIncompatible(ParamTy))
10150       return false;   // Attribute not compatible with transformed value.
10151
10152     // Converting from one pointer type to another or between a pointer and an
10153     // integer of the same size is safe even if we do not have a body.
10154     bool isConvertible = ActTy == ParamTy ||
10155       (TD && ((isa<PointerType>(ParamTy) ||
10156       ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10157               (isa<PointerType>(ActTy) ||
10158               ActTy == TD->getIntPtrType(Caller->getContext()))));
10159     if (Callee->isDeclaration() && !isConvertible) return false;
10160   }
10161
10162   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10163       Callee->isDeclaration())
10164     return false;   // Do not delete arguments unless we have a function body.
10165
10166   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10167       !CallerPAL.isEmpty())
10168     // In this case we have more arguments than the new function type, but we
10169     // won't be dropping them.  Check that these extra arguments have attributes
10170     // that are compatible with being a vararg call argument.
10171     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10172       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10173         break;
10174       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10175       if (PAttrs & Attribute::VarArgsIncompatible)
10176         return false;
10177     }
10178
10179   // Okay, we decided that this is a safe thing to do: go ahead and start
10180   // inserting cast instructions as necessary...
10181   std::vector<Value*> Args;
10182   Args.reserve(NumActualArgs);
10183   SmallVector<AttributeWithIndex, 8> attrVec;
10184   attrVec.reserve(NumCommonArgs);
10185
10186   // Get any return attributes.
10187   Attributes RAttrs = CallerPAL.getRetAttributes();
10188
10189   // If the return value is not being used, the type may not be compatible
10190   // with the existing attributes.  Wipe out any problematic attributes.
10191   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10192
10193   // Add the new return attributes.
10194   if (RAttrs)
10195     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10196
10197   AI = CS.arg_begin();
10198   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10199     const Type *ParamTy = FT->getParamType(i);
10200     if ((*AI)->getType() == ParamTy) {
10201       Args.push_back(*AI);
10202     } else {
10203       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10204           false, ParamTy, false);
10205       Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
10206     }
10207
10208     // Add any parameter attributes.
10209     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10210       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10211   }
10212
10213   // If the function takes more arguments than the call was taking, add them
10214   // now.
10215   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10216     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10217
10218   // If we are removing arguments to the function, emit an obnoxious warning.
10219   if (FT->getNumParams() < NumActualArgs) {
10220     if (!FT->isVarArg()) {
10221       errs() << "WARNING: While resolving call to function '"
10222              << Callee->getName() << "' arguments were dropped!\n";
10223     } else {
10224       // Add all of the arguments in their promoted form to the arg list.
10225       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10226         const Type *PTy = getPromotedType((*AI)->getType());
10227         if (PTy != (*AI)->getType()) {
10228           // Must promote to pass through va_arg area!
10229           Instruction::CastOps opcode =
10230             CastInst::getCastOpcode(*AI, false, PTy, false);
10231           Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
10232         } else {
10233           Args.push_back(*AI);
10234         }
10235
10236         // Add any parameter attributes.
10237         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10238           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10239       }
10240     }
10241   }
10242
10243   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10244     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10245
10246   if (NewRetTy->isVoidTy())
10247     Caller->setName("");   // Void type should not have a name.
10248
10249   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10250                                                      attrVec.end());
10251
10252   Instruction *NC;
10253   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10254     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10255                             Args.begin(), Args.end(),
10256                             Caller->getName(), Caller);
10257     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10258     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10259   } else {
10260     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10261                           Caller->getName(), Caller);
10262     CallInst *CI = cast<CallInst>(Caller);
10263     if (CI->isTailCall())
10264       cast<CallInst>(NC)->setTailCall();
10265     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10266     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10267   }
10268
10269   // Insert a cast of the return type as necessary.
10270   Value *NV = NC;
10271   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10272     if (!NV->getType()->isVoidTy()) {
10273       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10274                                                             OldRetTy, false);
10275       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10276
10277       // If this is an invoke instruction, we should insert it after the first
10278       // non-phi, instruction in the normal successor block.
10279       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10280         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10281         InsertNewInstBefore(NC, *I);
10282       } else {
10283         // Otherwise, it's a call, just insert cast right after the call instr
10284         InsertNewInstBefore(NC, *Caller);
10285       }
10286       Worklist.AddUsersToWorkList(*Caller);
10287     } else {
10288       NV = UndefValue::get(Caller->getType());
10289     }
10290   }
10291
10292
10293   if (!Caller->use_empty())
10294     Caller->replaceAllUsesWith(NV);
10295   
10296   EraseInstFromFunction(*Caller);
10297   return true;
10298 }
10299
10300 // transformCallThroughTrampoline - Turn a call to a function created by the
10301 // init_trampoline intrinsic into a direct call to the underlying function.
10302 //
10303 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10304   Value *Callee = CS.getCalledValue();
10305   const PointerType *PTy = cast<PointerType>(Callee->getType());
10306   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10307   const AttrListPtr &Attrs = CS.getAttributes();
10308
10309   // If the call already has the 'nest' attribute somewhere then give up -
10310   // otherwise 'nest' would occur twice after splicing in the chain.
10311   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10312     return 0;
10313
10314   IntrinsicInst *Tramp =
10315     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10316
10317   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10318   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10319   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10320
10321   const AttrListPtr &NestAttrs = NestF->getAttributes();
10322   if (!NestAttrs.isEmpty()) {
10323     unsigned NestIdx = 1;
10324     const Type *NestTy = 0;
10325     Attributes NestAttr = Attribute::None;
10326
10327     // Look for a parameter marked with the 'nest' attribute.
10328     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10329          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10330       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10331         // Record the parameter type and any other attributes.
10332         NestTy = *I;
10333         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10334         break;
10335       }
10336
10337     if (NestTy) {
10338       Instruction *Caller = CS.getInstruction();
10339       std::vector<Value*> NewArgs;
10340       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10341
10342       SmallVector<AttributeWithIndex, 8> NewAttrs;
10343       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10344
10345       // Insert the nest argument into the call argument list, which may
10346       // mean appending it.  Likewise for attributes.
10347
10348       // Add any result attributes.
10349       if (Attributes Attr = Attrs.getRetAttributes())
10350         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10351
10352       {
10353         unsigned Idx = 1;
10354         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10355         do {
10356           if (Idx == NestIdx) {
10357             // Add the chain argument and attributes.
10358             Value *NestVal = Tramp->getOperand(3);
10359             if (NestVal->getType() != NestTy)
10360               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10361             NewArgs.push_back(NestVal);
10362             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10363           }
10364
10365           if (I == E)
10366             break;
10367
10368           // Add the original argument and attributes.
10369           NewArgs.push_back(*I);
10370           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10371             NewAttrs.push_back
10372               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10373
10374           ++Idx, ++I;
10375         } while (1);
10376       }
10377
10378       // Add any function attributes.
10379       if (Attributes Attr = Attrs.getFnAttributes())
10380         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10381
10382       // The trampoline may have been bitcast to a bogus type (FTy).
10383       // Handle this by synthesizing a new function type, equal to FTy
10384       // with the chain parameter inserted.
10385
10386       std::vector<const Type*> NewTypes;
10387       NewTypes.reserve(FTy->getNumParams()+1);
10388
10389       // Insert the chain's type into the list of parameter types, which may
10390       // mean appending it.
10391       {
10392         unsigned Idx = 1;
10393         FunctionType::param_iterator I = FTy->param_begin(),
10394           E = FTy->param_end();
10395
10396         do {
10397           if (Idx == NestIdx)
10398             // Add the chain's type.
10399             NewTypes.push_back(NestTy);
10400
10401           if (I == E)
10402             break;
10403
10404           // Add the original type.
10405           NewTypes.push_back(*I);
10406
10407           ++Idx, ++I;
10408         } while (1);
10409       }
10410
10411       // Replace the trampoline call with a direct call.  Let the generic
10412       // code sort out any function type mismatches.
10413       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 
10414                                                 FTy->isVarArg());
10415       Constant *NewCallee =
10416         NestF->getType() == PointerType::getUnqual(NewFTy) ?
10417         NestF : ConstantExpr::getBitCast(NestF, 
10418                                          PointerType::getUnqual(NewFTy));
10419       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10420                                                    NewAttrs.end());
10421
10422       Instruction *NewCaller;
10423       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10424         NewCaller = InvokeInst::Create(NewCallee,
10425                                        II->getNormalDest(), II->getUnwindDest(),
10426                                        NewArgs.begin(), NewArgs.end(),
10427                                        Caller->getName(), Caller);
10428         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10429         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10430       } else {
10431         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10432                                      Caller->getName(), Caller);
10433         if (cast<CallInst>(Caller)->isTailCall())
10434           cast<CallInst>(NewCaller)->setTailCall();
10435         cast<CallInst>(NewCaller)->
10436           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10437         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10438       }
10439       if (!Caller->getType()->isVoidTy())
10440         Caller->replaceAllUsesWith(NewCaller);
10441       Caller->eraseFromParent();
10442       Worklist.Remove(Caller);
10443       return 0;
10444     }
10445   }
10446
10447   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10448   // parameter, there is no need to adjust the argument list.  Let the generic
10449   // code sort out any function type mismatches.
10450   Constant *NewCallee =
10451     NestF->getType() == PTy ? NestF : 
10452                               ConstantExpr::getBitCast(NestF, PTy);
10453   CS.setCalledFunction(NewCallee);
10454   return CS.getInstruction();
10455 }
10456
10457 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10458 /// and if a/b/c and the add's all have a single use, turn this into a phi
10459 /// and a single binop.
10460 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10461   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10462   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10463   unsigned Opc = FirstInst->getOpcode();
10464   Value *LHSVal = FirstInst->getOperand(0);
10465   Value *RHSVal = FirstInst->getOperand(1);
10466     
10467   const Type *LHSType = LHSVal->getType();
10468   const Type *RHSType = RHSVal->getType();
10469   
10470   // Scan to see if all operands are the same opcode, and all have one use.
10471   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10472     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10473     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10474         // Verify type of the LHS matches so we don't fold cmp's of different
10475         // types or GEP's with different index types.
10476         I->getOperand(0)->getType() != LHSType ||
10477         I->getOperand(1)->getType() != RHSType)
10478       return 0;
10479
10480     // If they are CmpInst instructions, check their predicates
10481     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10482       if (cast<CmpInst>(I)->getPredicate() !=
10483           cast<CmpInst>(FirstInst)->getPredicate())
10484         return 0;
10485     
10486     // Keep track of which operand needs a phi node.
10487     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10488     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10489   }
10490
10491   // If both LHS and RHS would need a PHI, don't do this transformation,
10492   // because it would increase the number of PHIs entering the block,
10493   // which leads to higher register pressure. This is especially
10494   // bad when the PHIs are in the header of a loop.
10495   if (!LHSVal && !RHSVal)
10496     return 0;
10497   
10498   // Otherwise, this is safe to transform!
10499   
10500   Value *InLHS = FirstInst->getOperand(0);
10501   Value *InRHS = FirstInst->getOperand(1);
10502   PHINode *NewLHS = 0, *NewRHS = 0;
10503   if (LHSVal == 0) {
10504     NewLHS = PHINode::Create(LHSType,
10505                              FirstInst->getOperand(0)->getName() + ".pn");
10506     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10507     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10508     InsertNewInstBefore(NewLHS, PN);
10509     LHSVal = NewLHS;
10510   }
10511   
10512   if (RHSVal == 0) {
10513     NewRHS = PHINode::Create(RHSType,
10514                              FirstInst->getOperand(1)->getName() + ".pn");
10515     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10516     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10517     InsertNewInstBefore(NewRHS, PN);
10518     RHSVal = NewRHS;
10519   }
10520   
10521   // Add all operands to the new PHIs.
10522   if (NewLHS || NewRHS) {
10523     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10524       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10525       if (NewLHS) {
10526         Value *NewInLHS = InInst->getOperand(0);
10527         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10528       }
10529       if (NewRHS) {
10530         Value *NewInRHS = InInst->getOperand(1);
10531         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10532       }
10533     }
10534   }
10535     
10536   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10537     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10538   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10539   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10540                          LHSVal, RHSVal);
10541 }
10542
10543 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10544   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10545   
10546   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10547                                         FirstInst->op_end());
10548   // This is true if all GEP bases are allocas and if all indices into them are
10549   // constants.
10550   bool AllBasePointersAreAllocas = true;
10551
10552   // We don't want to replace this phi if the replacement would require
10553   // more than one phi, which leads to higher register pressure. This is
10554   // especially bad when the PHIs are in the header of a loop.
10555   bool NeededPhi = false;
10556   
10557   // Scan to see if all operands are the same opcode, and all have one use.
10558   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10559     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10560     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10561       GEP->getNumOperands() != FirstInst->getNumOperands())
10562       return 0;
10563
10564     // Keep track of whether or not all GEPs are of alloca pointers.
10565     if (AllBasePointersAreAllocas &&
10566         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10567          !GEP->hasAllConstantIndices()))
10568       AllBasePointersAreAllocas = false;
10569     
10570     // Compare the operand lists.
10571     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10572       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10573         continue;
10574       
10575       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10576       // if one of the PHIs has a constant for the index.  The index may be
10577       // substantially cheaper to compute for the constants, so making it a
10578       // variable index could pessimize the path.  This also handles the case
10579       // for struct indices, which must always be constant.
10580       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10581           isa<ConstantInt>(GEP->getOperand(op)))
10582         return 0;
10583       
10584       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10585         return 0;
10586
10587       // If we already needed a PHI for an earlier operand, and another operand
10588       // also requires a PHI, we'd be introducing more PHIs than we're
10589       // eliminating, which increases register pressure on entry to the PHI's
10590       // block.
10591       if (NeededPhi)
10592         return 0;
10593
10594       FixedOperands[op] = 0;  // Needs a PHI.
10595       NeededPhi = true;
10596     }
10597   }
10598   
10599   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10600   // bother doing this transformation.  At best, this will just save a bit of
10601   // offset calculation, but all the predecessors will have to materialize the
10602   // stack address into a register anyway.  We'd actually rather *clone* the
10603   // load up into the predecessors so that we have a load of a gep of an alloca,
10604   // which can usually all be folded into the load.
10605   if (AllBasePointersAreAllocas)
10606     return 0;
10607   
10608   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10609   // that is variable.
10610   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10611   
10612   bool HasAnyPHIs = false;
10613   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10614     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10615     Value *FirstOp = FirstInst->getOperand(i);
10616     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10617                                      FirstOp->getName()+".pn");
10618     InsertNewInstBefore(NewPN, PN);
10619     
10620     NewPN->reserveOperandSpace(e);
10621     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10622     OperandPhis[i] = NewPN;
10623     FixedOperands[i] = NewPN;
10624     HasAnyPHIs = true;
10625   }
10626
10627   
10628   // Add all operands to the new PHIs.
10629   if (HasAnyPHIs) {
10630     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10631       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10632       BasicBlock *InBB = PN.getIncomingBlock(i);
10633       
10634       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10635         if (PHINode *OpPhi = OperandPhis[op])
10636           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10637     }
10638   }
10639   
10640   Value *Base = FixedOperands[0];
10641   return cast<GEPOperator>(FirstInst)->isInBounds() ?
10642     GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10643                                       FixedOperands.end()) :
10644     GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10645                               FixedOperands.end());
10646 }
10647
10648
10649 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10650 /// sink the load out of the block that defines it.  This means that it must be
10651 /// obvious the value of the load is not changed from the point of the load to
10652 /// the end of the block it is in.
10653 ///
10654 /// Finally, it is safe, but not profitable, to sink a load targetting a
10655 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10656 /// to a register.
10657 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10658   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10659   
10660   for (++BBI; BBI != E; ++BBI)
10661     if (BBI->mayWriteToMemory())
10662       return false;
10663   
10664   // Check for non-address taken alloca.  If not address-taken already, it isn't
10665   // profitable to do this xform.
10666   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10667     bool isAddressTaken = false;
10668     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10669          UI != E; ++UI) {
10670       if (isa<LoadInst>(UI)) continue;
10671       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10672         // If storing TO the alloca, then the address isn't taken.
10673         if (SI->getOperand(1) == AI) continue;
10674       }
10675       isAddressTaken = true;
10676       break;
10677     }
10678     
10679     if (!isAddressTaken && AI->isStaticAlloca())
10680       return false;
10681   }
10682   
10683   // If this load is a load from a GEP with a constant offset from an alloca,
10684   // then we don't want to sink it.  In its present form, it will be
10685   // load [constant stack offset].  Sinking it will cause us to have to
10686   // materialize the stack addresses in each predecessor in a register only to
10687   // do a shared load from register in the successor.
10688   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10689     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10690       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10691         return false;
10692   
10693   return true;
10694 }
10695
10696
10697 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10698 // operator and they all are only used by the PHI, PHI together their
10699 // inputs, and do the operation once, to the result of the PHI.
10700 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10701   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10702
10703   // Scan the instruction, looking for input operations that can be folded away.
10704   // If all input operands to the phi are the same instruction (e.g. a cast from
10705   // the same type or "+42") we can pull the operation through the PHI, reducing
10706   // code size and simplifying code.
10707   Constant *ConstantOp = 0;
10708   const Type *CastSrcTy = 0;
10709   bool isVolatile = false;
10710   if (isa<CastInst>(FirstInst)) {
10711     CastSrcTy = FirstInst->getOperand(0)->getType();
10712   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10713     // Can fold binop, compare or shift here if the RHS is a constant, 
10714     // otherwise call FoldPHIArgBinOpIntoPHI.
10715     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10716     if (ConstantOp == 0)
10717       return FoldPHIArgBinOpIntoPHI(PN);
10718   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10719     isVolatile = LI->isVolatile();
10720     // We can't sink the load if the loaded value could be modified between the
10721     // load and the PHI.
10722     if (LI->getParent() != PN.getIncomingBlock(0) ||
10723         !isSafeAndProfitableToSinkLoad(LI))
10724       return 0;
10725     
10726     // If the PHI is of volatile loads and the load block has multiple
10727     // successors, sinking it would remove a load of the volatile value from
10728     // the path through the other successor.
10729     if (isVolatile &&
10730         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10731       return 0;
10732     
10733   } else if (isa<GetElementPtrInst>(FirstInst)) {
10734     return FoldPHIArgGEPIntoPHI(PN);
10735   } else {
10736     return 0;  // Cannot fold this operation.
10737   }
10738
10739   // Check to see if all arguments are the same operation.
10740   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10741     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10742     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10743     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10744       return 0;
10745     if (CastSrcTy) {
10746       if (I->getOperand(0)->getType() != CastSrcTy)
10747         return 0;  // Cast operation must match.
10748     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10749       // We can't sink the load if the loaded value could be modified between 
10750       // the load and the PHI.
10751       if (LI->isVolatile() != isVolatile ||
10752           LI->getParent() != PN.getIncomingBlock(i) ||
10753           !isSafeAndProfitableToSinkLoad(LI))
10754         return 0;
10755       
10756       // If the PHI is of volatile loads and the load block has multiple
10757       // successors, sinking it would remove a load of the volatile value from
10758       // the path through the other successor.
10759       if (isVolatile &&
10760           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10761         return 0;
10762       
10763     } else if (I->getOperand(1) != ConstantOp) {
10764       return 0;
10765     }
10766   }
10767
10768   // Okay, they are all the same operation.  Create a new PHI node of the
10769   // correct type, and PHI together all of the LHS's of the instructions.
10770   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10771                                    PN.getName()+".in");
10772   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10773
10774   Value *InVal = FirstInst->getOperand(0);
10775   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10776
10777   // Add all operands to the new PHI.
10778   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10779     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10780     if (NewInVal != InVal)
10781       InVal = 0;
10782     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10783   }
10784
10785   Value *PhiVal;
10786   if (InVal) {
10787     // The new PHI unions all of the same values together.  This is really
10788     // common, so we handle it intelligently here for compile-time speed.
10789     PhiVal = InVal;
10790     delete NewPN;
10791   } else {
10792     InsertNewInstBefore(NewPN, PN);
10793     PhiVal = NewPN;
10794   }
10795
10796   // Insert and return the new operation.
10797   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10798     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10799   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10800     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10801   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10802     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10803                            PhiVal, ConstantOp);
10804   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10805   
10806   // If this was a volatile load that we are merging, make sure to loop through
10807   // and mark all the input loads as non-volatile.  If we don't do this, we will
10808   // insert a new volatile load and the old ones will not be deletable.
10809   if (isVolatile)
10810     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10811       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10812   
10813   return new LoadInst(PhiVal, "", isVolatile);
10814 }
10815
10816 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10817 /// that is dead.
10818 static bool DeadPHICycle(PHINode *PN,
10819                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10820   if (PN->use_empty()) return true;
10821   if (!PN->hasOneUse()) return false;
10822
10823   // Remember this node, and if we find the cycle, return.
10824   if (!PotentiallyDeadPHIs.insert(PN))
10825     return true;
10826   
10827   // Don't scan crazily complex things.
10828   if (PotentiallyDeadPHIs.size() == 16)
10829     return false;
10830
10831   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10832     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10833
10834   return false;
10835 }
10836
10837 /// PHIsEqualValue - Return true if this phi node is always equal to
10838 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10839 ///   z = some value; x = phi (y, z); y = phi (x, z)
10840 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10841                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10842   // See if we already saw this PHI node.
10843   if (!ValueEqualPHIs.insert(PN))
10844     return true;
10845   
10846   // Don't scan crazily complex things.
10847   if (ValueEqualPHIs.size() == 16)
10848     return false;
10849  
10850   // Scan the operands to see if they are either phi nodes or are equal to
10851   // the value.
10852   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10853     Value *Op = PN->getIncomingValue(i);
10854     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10855       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10856         return false;
10857     } else if (Op != NonPhiInVal)
10858       return false;
10859   }
10860   
10861   return true;
10862 }
10863
10864
10865 // PHINode simplification
10866 //
10867 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10868   // If LCSSA is around, don't mess with Phi nodes
10869   if (MustPreserveLCSSA) return 0;
10870   
10871   if (Value *V = PN.hasConstantValue())
10872     return ReplaceInstUsesWith(PN, V);
10873
10874   // If all PHI operands are the same operation, pull them through the PHI,
10875   // reducing code size.
10876   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10877       isa<Instruction>(PN.getIncomingValue(1)) &&
10878       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10879       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10880       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10881       // than themselves more than once.
10882       PN.getIncomingValue(0)->hasOneUse())
10883     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10884       return Result;
10885
10886   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10887   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10888   // PHI)... break the cycle.
10889   if (PN.hasOneUse()) {
10890     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10891     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10892       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10893       PotentiallyDeadPHIs.insert(&PN);
10894       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10895         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10896     }
10897    
10898     // If this phi has a single use, and if that use just computes a value for
10899     // the next iteration of a loop, delete the phi.  This occurs with unused
10900     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10901     // common case here is good because the only other things that catch this
10902     // are induction variable analysis (sometimes) and ADCE, which is only run
10903     // late.
10904     if (PHIUser->hasOneUse() &&
10905         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10906         PHIUser->use_back() == &PN) {
10907       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10908     }
10909   }
10910
10911   // We sometimes end up with phi cycles that non-obviously end up being the
10912   // same value, for example:
10913   //   z = some value; x = phi (y, z); y = phi (x, z)
10914   // where the phi nodes don't necessarily need to be in the same block.  Do a
10915   // quick check to see if the PHI node only contains a single non-phi value, if
10916   // so, scan to see if the phi cycle is actually equal to that value.
10917   {
10918     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10919     // Scan for the first non-phi operand.
10920     while (InValNo != NumOperandVals && 
10921            isa<PHINode>(PN.getIncomingValue(InValNo)))
10922       ++InValNo;
10923
10924     if (InValNo != NumOperandVals) {
10925       Value *NonPhiInVal = PN.getOperand(InValNo);
10926       
10927       // Scan the rest of the operands to see if there are any conflicts, if so
10928       // there is no need to recursively scan other phis.
10929       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10930         Value *OpVal = PN.getIncomingValue(InValNo);
10931         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10932           break;
10933       }
10934       
10935       // If we scanned over all operands, then we have one unique value plus
10936       // phi values.  Scan PHI nodes to see if they all merge in each other or
10937       // the value.
10938       if (InValNo == NumOperandVals) {
10939         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10940         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10941           return ReplaceInstUsesWith(PN, NonPhiInVal);
10942       }
10943     }
10944   }
10945   return 0;
10946 }
10947
10948 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10949   Value *PtrOp = GEP.getOperand(0);
10950   // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
10951   if (GEP.getNumOperands() == 1)
10952     return ReplaceInstUsesWith(GEP, PtrOp);
10953
10954   if (isa<UndefValue>(GEP.getOperand(0)))
10955     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10956
10957   bool HasZeroPointerIndex = false;
10958   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10959     HasZeroPointerIndex = C->isNullValue();
10960
10961   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10962     return ReplaceInstUsesWith(GEP, PtrOp);
10963
10964   // Eliminate unneeded casts for indices.
10965   if (TD) {
10966     bool MadeChange = false;
10967     unsigned PtrSize = TD->getPointerSizeInBits();
10968     
10969     gep_type_iterator GTI = gep_type_begin(GEP);
10970     for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10971          I != E; ++I, ++GTI) {
10972       if (!isa<SequentialType>(*GTI)) continue;
10973       
10974       // If we are using a wider index than needed for this platform, shrink it
10975       // to what we need.  If narrower, sign-extend it to what we need.  This
10976       // explicit cast can make subsequent optimizations more obvious.
10977       unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
10978       if (OpBits == PtrSize)
10979         continue;
10980       
10981       *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
10982       MadeChange = true;
10983     }
10984     if (MadeChange) return &GEP;
10985   }
10986
10987   // Combine Indices - If the source pointer to this getelementptr instruction
10988   // is a getelementptr instruction, combine the indices of the two
10989   // getelementptr instructions into a single instruction.
10990   //
10991   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
10992     // Note that if our source is a gep chain itself that we wait for that
10993     // chain to be resolved before we perform this transformation.  This
10994     // avoids us creating a TON of code in some cases.
10995     //
10996     if (GetElementPtrInst *SrcGEP =
10997           dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10998       if (SrcGEP->getNumOperands() == 2)
10999         return 0;   // Wait until our source is folded to completion.
11000
11001     SmallVector<Value*, 8> Indices;
11002
11003     // Find out whether the last index in the source GEP is a sequential idx.
11004     bool EndsWithSequential = false;
11005     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11006          I != E; ++I)
11007       EndsWithSequential = !isa<StructType>(*I);
11008
11009     // Can we combine the two pointer arithmetics offsets?
11010     if (EndsWithSequential) {
11011       // Replace: gep (gep %P, long B), long A, ...
11012       // With:    T = long A+B; gep %P, T, ...
11013       //
11014       Value *Sum;
11015       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11016       Value *GO1 = GEP.getOperand(1);
11017       if (SO1 == Constant::getNullValue(SO1->getType())) {
11018         Sum = GO1;
11019       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
11020         Sum = SO1;
11021       } else {
11022         // If they aren't the same type, then the input hasn't been processed
11023         // by the loop above yet (which canonicalizes sequential index types to
11024         // intptr_t).  Just avoid transforming this until the input has been
11025         // normalized.
11026         if (SO1->getType() != GO1->getType())
11027           return 0;
11028         Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11029       }
11030
11031       // Update the GEP in place if possible.
11032       if (Src->getNumOperands() == 2) {
11033         GEP.setOperand(0, Src->getOperand(0));
11034         GEP.setOperand(1, Sum);
11035         return &GEP;
11036       }
11037       Indices.append(Src->op_begin()+1, Src->op_end()-1);
11038       Indices.push_back(Sum);
11039       Indices.append(GEP.op_begin()+2, GEP.op_end());
11040     } else if (isa<Constant>(*GEP.idx_begin()) &&
11041                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11042                Src->getNumOperands() != 1) {
11043       // Otherwise we can do the fold if the first index of the GEP is a zero
11044       Indices.append(Src->op_begin()+1, Src->op_end());
11045       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
11046     }
11047
11048     if (!Indices.empty())
11049       return (cast<GEPOperator>(&GEP)->isInBounds() &&
11050               Src->isInBounds()) ?
11051         GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11052                                           Indices.end(), GEP.getName()) :
11053         GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
11054                                   Indices.end(), GEP.getName());
11055   }
11056   
11057   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11058   if (Value *X = getBitCastOperand(PtrOp)) {
11059     assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
11060
11061     // If the input bitcast is actually "bitcast(bitcast(x))", then we don't 
11062     // want to change the gep until the bitcasts are eliminated.
11063     if (getBitCastOperand(X)) {
11064       Worklist.AddValue(PtrOp);
11065       return 0;
11066     }
11067     
11068     // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11069     // into     : GEP [10 x i8]* X, i32 0, ...
11070     //
11071     // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11072     //           into     : GEP i8* X, ...
11073     // 
11074     // This occurs when the program declares an array extern like "int X[];"
11075     if (HasZeroPointerIndex) {
11076       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11077       const PointerType *XTy = cast<PointerType>(X->getType());
11078       if (const ArrayType *CATy =
11079           dyn_cast<ArrayType>(CPTy->getElementType())) {
11080         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11081         if (CATy->getElementType() == XTy->getElementType()) {
11082           // -> GEP i8* X, ...
11083           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11084           return cast<GEPOperator>(&GEP)->isInBounds() ?
11085             GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11086                                               GEP.getName()) :
11087             GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11088                                       GEP.getName());
11089         }
11090         
11091         if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
11092           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11093           if (CATy->getElementType() == XATy->getElementType()) {
11094             // -> GEP [10 x i8]* X, i32 0, ...
11095             // At this point, we know that the cast source type is a pointer
11096             // to an array of the same type as the destination pointer
11097             // array.  Because the array type is never stepped over (there
11098             // is a leading zero) we can fold the cast into this GEP.
11099             GEP.setOperand(0, X);
11100             return &GEP;
11101           }
11102         }
11103       }
11104     } else if (GEP.getNumOperands() == 2) {
11105       // Transform things like:
11106       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11107       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11108       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11109       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11110       if (TD && isa<ArrayType>(SrcElTy) &&
11111           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11112           TD->getTypeAllocSize(ResElTy)) {
11113         Value *Idx[2];
11114         Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11115         Idx[1] = GEP.getOperand(1);
11116         Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11117           Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11118           Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11119         // V and GEP are both pointer types --> BitCast
11120         return new BitCastInst(NewGEP, GEP.getType());
11121       }
11122       
11123       // Transform things like:
11124       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11125       //   (where tmp = 8*tmp2) into:
11126       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11127       
11128       if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
11129         uint64_t ArrayEltSize =
11130             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11131         
11132         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11133         // allow either a mul, shift, or constant here.
11134         Value *NewIdx = 0;
11135         ConstantInt *Scale = 0;
11136         if (ArrayEltSize == 1) {
11137           NewIdx = GEP.getOperand(1);
11138           Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
11139         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11140           NewIdx = ConstantInt::get(CI->getType(), 1);
11141           Scale = CI;
11142         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11143           if (Inst->getOpcode() == Instruction::Shl &&
11144               isa<ConstantInt>(Inst->getOperand(1))) {
11145             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11146             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11147             Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11148                                      1ULL << ShAmtVal);
11149             NewIdx = Inst->getOperand(0);
11150           } else if (Inst->getOpcode() == Instruction::Mul &&
11151                      isa<ConstantInt>(Inst->getOperand(1))) {
11152             Scale = cast<ConstantInt>(Inst->getOperand(1));
11153             NewIdx = Inst->getOperand(0);
11154           }
11155         }
11156         
11157         // If the index will be to exactly the right offset with the scale taken
11158         // out, perform the transformation. Note, we don't know whether Scale is
11159         // signed or not. We'll use unsigned version of division/modulo
11160         // operation after making sure Scale doesn't have the sign bit set.
11161         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11162             Scale->getZExtValue() % ArrayEltSize == 0) {
11163           Scale = ConstantInt::get(Scale->getType(),
11164                                    Scale->getZExtValue() / ArrayEltSize);
11165           if (Scale->getZExtValue() != 1) {
11166             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11167                                                        false /*ZExt*/);
11168             NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
11169           }
11170
11171           // Insert the new GEP instruction.
11172           Value *Idx[2];
11173           Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11174           Idx[1] = NewIdx;
11175           Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11176             Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11177             Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11178           // The NewGEP must be pointer typed, so must the old one -> BitCast
11179           return new BitCastInst(NewGEP, GEP.getType());
11180         }
11181       }
11182     }
11183   }
11184   
11185   /// See if we can simplify:
11186   ///   X = bitcast A* to B*
11187   ///   Y = gep X, <...constant indices...>
11188   /// into a gep of the original struct.  This is important for SROA and alias
11189   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11190   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11191     if (TD &&
11192         !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11193       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11194       // a constant back from EmitGEPOffset.
11195       ConstantInt *OffsetV =
11196                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11197       int64_t Offset = OffsetV->getSExtValue();
11198       
11199       // If this GEP instruction doesn't move the pointer, just replace the GEP
11200       // with a bitcast of the real input to the dest type.
11201       if (Offset == 0) {
11202         // If the bitcast is of an allocation, and the allocation will be
11203         // converted to match the type of the cast, don't touch this.
11204         if (isa<AllocaInst>(BCI->getOperand(0)) ||
11205             isMalloc(BCI->getOperand(0))) {
11206           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11207           if (Instruction *I = visitBitCast(*BCI)) {
11208             if (I != BCI) {
11209               I->takeName(BCI);
11210               BCI->getParent()->getInstList().insert(BCI, I);
11211               ReplaceInstUsesWith(*BCI, I);
11212             }
11213             return &GEP;
11214           }
11215         }
11216         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11217       }
11218       
11219       // Otherwise, if the offset is non-zero, we need to find out if there is a
11220       // field at Offset in 'A's type.  If so, we can pull the cast through the
11221       // GEP.
11222       SmallVector<Value*, 8> NewIndices;
11223       const Type *InTy =
11224         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11225       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11226         Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11227           Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11228                                      NewIndices.end()) :
11229           Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11230                              NewIndices.end());
11231         
11232         if (NGEP->getType() == GEP.getType())
11233           return ReplaceInstUsesWith(GEP, NGEP);
11234         NGEP->takeName(&GEP);
11235         return new BitCastInst(NGEP, GEP.getType());
11236       }
11237     }
11238   }    
11239     
11240   return 0;
11241 }
11242
11243 Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
11244   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11245   if (AI.isArrayAllocation()) {  // Check C != 1
11246     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11247       const Type *NewTy = 
11248         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11249       assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11250       AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
11251       New->setAlignment(AI.getAlignment());
11252
11253       // Scan to the end of the allocation instructions, to skip over a block of
11254       // allocas if possible...also skip interleaved debug info
11255       //
11256       BasicBlock::iterator It = New;
11257       while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11258
11259       // Now that I is pointing to the first non-allocation-inst in the block,
11260       // insert our getelementptr instruction...
11261       //
11262       Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
11263       Value *Idx[2];
11264       Idx[0] = NullIdx;
11265       Idx[1] = NullIdx;
11266       Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11267                                                    New->getName()+".sub", It);
11268
11269       // Now make everything use the getelementptr instead of the original
11270       // allocation.
11271       return ReplaceInstUsesWith(AI, V);
11272     } else if (isa<UndefValue>(AI.getArraySize())) {
11273       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11274     }
11275   }
11276
11277   if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11278     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11279     // Note that we only do this for alloca's, because malloc should allocate
11280     // and return a unique pointer, even for a zero byte allocation.
11281     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11282       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11283
11284     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11285     if (AI.getAlignment() == 0)
11286       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11287   }
11288
11289   return 0;
11290 }
11291
11292 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11293   Value *Op = FI.getOperand(0);
11294
11295   // free undef -> unreachable.
11296   if (isa<UndefValue>(Op)) {
11297     // Insert a new store to null because we cannot modify the CFG here.
11298     new StoreInst(ConstantInt::getTrue(*Context),
11299            UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
11300     return EraseInstFromFunction(FI);
11301   }
11302   
11303   // If we have 'free null' delete the instruction.  This can happen in stl code
11304   // when lots of inlining happens.
11305   if (isa<ConstantPointerNull>(Op))
11306     return EraseInstFromFunction(FI);
11307   
11308   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11309   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11310     FI.setOperand(0, CI->getOperand(0));
11311     return &FI;
11312   }
11313   
11314   // Change free (gep X, 0,0,0,0) into free(X)
11315   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11316     if (GEPI->hasAllZeroIndices()) {
11317       Worklist.Add(GEPI);
11318       FI.setOperand(0, GEPI->getOperand(0));
11319       return &FI;
11320     }
11321   }
11322   
11323   if (isMalloc(Op)) {
11324     if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11325       if (Op->hasOneUse() && CI->hasOneUse()) {
11326         EraseInstFromFunction(FI);
11327         EraseInstFromFunction(*CI);
11328         return EraseInstFromFunction(*cast<Instruction>(Op));
11329       }
11330     } else {
11331       // Op is a call to malloc
11332       if (Op->hasOneUse()) {
11333         EraseInstFromFunction(FI);
11334         return EraseInstFromFunction(*cast<Instruction>(Op));
11335       }
11336     }
11337   }
11338
11339   return 0;
11340 }
11341
11342 Instruction *InstCombiner::visitFree(Instruction &FI) {
11343   Value *Op = FI.getOperand(1);
11344
11345   // free undef -> unreachable.
11346   if (isa<UndefValue>(Op)) {
11347     // Insert a new store to null because we cannot modify the CFG here.
11348     new StoreInst(ConstantInt::getTrue(*Context),
11349            UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
11350     return EraseInstFromFunction(FI);
11351   }
11352   
11353   // If we have 'free null' delete the instruction.  This can happen in stl code
11354   // when lots of inlining happens.
11355   if (isa<ConstantPointerNull>(Op))
11356     return EraseInstFromFunction(FI);
11357
11358   // FIXME: Bring back free (gep X, 0,0,0,0) into free(X) transform
11359   
11360   if (isMalloc(Op)) {
11361     if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11362       if (Op->hasOneUse() && CI->hasOneUse()) {
11363         EraseInstFromFunction(FI);
11364         EraseInstFromFunction(*CI);
11365         return EraseInstFromFunction(*cast<Instruction>(Op));
11366       }
11367     } else {
11368       // Op is a call to malloc
11369       if (Op->hasOneUse()) {
11370         EraseInstFromFunction(FI);
11371         return EraseInstFromFunction(*cast<Instruction>(Op));
11372       }
11373     }
11374   }
11375
11376   return 0;
11377 }
11378
11379 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11380 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11381                                         const TargetData *TD) {
11382   User *CI = cast<User>(LI.getOperand(0));
11383   Value *CastOp = CI->getOperand(0);
11384   LLVMContext *Context = IC.getContext();
11385
11386   const PointerType *DestTy = cast<PointerType>(CI->getType());
11387   const Type *DestPTy = DestTy->getElementType();
11388   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11389
11390     // If the address spaces don't match, don't eliminate the cast.
11391     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11392       return 0;
11393
11394     const Type *SrcPTy = SrcTy->getElementType();
11395
11396     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11397          isa<VectorType>(DestPTy)) {
11398       // If the source is an array, the code below will not succeed.  Check to
11399       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11400       // constants.
11401       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11402         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11403           if (ASrcTy->getNumElements() != 0) {
11404             Value *Idxs[2];
11405             Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11406             Idxs[1] = Idxs[0];
11407             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11408             SrcTy = cast<PointerType>(CastOp->getType());
11409             SrcPTy = SrcTy->getElementType();
11410           }
11411
11412       if (IC.getTargetData() &&
11413           (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11414             isa<VectorType>(SrcPTy)) &&
11415           // Do not allow turning this into a load of an integer, which is then
11416           // casted to a pointer, this pessimizes pointer analysis a lot.
11417           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11418           IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11419                IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11420
11421         // Okay, we are casting from one integer or pointer type to another of
11422         // the same size.  Instead of casting the pointer before the load, cast
11423         // the result of the loaded value.
11424         Value *NewLoad = 
11425           IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
11426         // Now cast the result of the load.
11427         return new BitCastInst(NewLoad, LI.getType());
11428       }
11429     }
11430   }
11431   return 0;
11432 }
11433
11434 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11435   Value *Op = LI.getOperand(0);
11436
11437   // Attempt to improve the alignment.
11438   if (TD) {
11439     unsigned KnownAlign =
11440       GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11441     if (KnownAlign >
11442         (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11443                                   LI.getAlignment()))
11444       LI.setAlignment(KnownAlign);
11445   }
11446
11447   // load (cast X) --> cast (load X) iff safe.
11448   if (isa<CastInst>(Op))
11449     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11450       return Res;
11451
11452   // None of the following transforms are legal for volatile loads.
11453   if (LI.isVolatile()) return 0;
11454   
11455   // Do really simple store-to-load forwarding and load CSE, to catch cases
11456   // where there are several consequtive memory accesses to the same location,
11457   // separated by a few arithmetic operations.
11458   BasicBlock::iterator BBI = &LI;
11459   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11460     return ReplaceInstUsesWith(LI, AvailableVal);
11461
11462   // load(gep null, ...) -> unreachable
11463   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11464     const Value *GEPI0 = GEPI->getOperand(0);
11465     // TODO: Consider a target hook for valid address spaces for this xform.
11466     if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
11467       // Insert a new store to null instruction before the load to indicate
11468       // that this code is not reachable.  We do this instead of inserting
11469       // an unreachable instruction directly because we cannot modify the
11470       // CFG.
11471       new StoreInst(UndefValue::get(LI.getType()),
11472                     Constant::getNullValue(Op->getType()), &LI);
11473       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11474     }
11475   } 
11476
11477   // load null/undef -> unreachable
11478   // TODO: Consider a target hook for valid address spaces for this xform.
11479   if (isa<UndefValue>(Op) ||
11480       (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
11481     // Insert a new store to null instruction before the load to indicate that
11482     // this code is not reachable.  We do this instead of inserting an
11483     // unreachable instruction directly because we cannot modify the CFG.
11484     new StoreInst(UndefValue::get(LI.getType()),
11485                   Constant::getNullValue(Op->getType()), &LI);
11486     return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11487   }
11488
11489   // Instcombine load (constantexpr_cast global) -> cast (load global)
11490   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
11491     if (CE->isCast())
11492       if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11493         return Res;
11494   
11495   if (Op->hasOneUse()) {
11496     // Change select and PHI nodes to select values instead of addresses: this
11497     // helps alias analysis out a lot, allows many others simplifications, and
11498     // exposes redundancy in the code.
11499     //
11500     // Note that we cannot do the transformation unless we know that the
11501     // introduced loads cannot trap!  Something like this is valid as long as
11502     // the condition is always false: load (select bool %C, int* null, int* %G),
11503     // but it would not be valid if we transformed it to load from null
11504     // unconditionally.
11505     //
11506     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11507       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11508       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11509           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11510         Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11511                                         SI->getOperand(1)->getName()+".val");
11512         Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11513                                         SI->getOperand(2)->getName()+".val");
11514         return SelectInst::Create(SI->getCondition(), V1, V2);
11515       }
11516
11517       // load (select (cond, null, P)) -> load P
11518       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11519         if (C->isNullValue()) {
11520           LI.setOperand(0, SI->getOperand(2));
11521           return &LI;
11522         }
11523
11524       // load (select (cond, P, null)) -> load P
11525       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11526         if (C->isNullValue()) {
11527           LI.setOperand(0, SI->getOperand(1));
11528           return &LI;
11529         }
11530     }
11531   }
11532   return 0;
11533 }
11534
11535 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11536 /// when possible.  This makes it generally easy to do alias analysis and/or
11537 /// SROA/mem2reg of the memory object.
11538 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11539   User *CI = cast<User>(SI.getOperand(1));
11540   Value *CastOp = CI->getOperand(0);
11541
11542   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11543   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11544   if (SrcTy == 0) return 0;
11545   
11546   const Type *SrcPTy = SrcTy->getElementType();
11547
11548   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11549     return 0;
11550   
11551   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11552   /// to its first element.  This allows us to handle things like:
11553   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11554   /// on 32-bit hosts.
11555   SmallVector<Value*, 4> NewGEPIndices;
11556   
11557   // If the source is an array, the code below will not succeed.  Check to
11558   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11559   // constants.
11560   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11561     // Index through pointer.
11562     Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
11563     NewGEPIndices.push_back(Zero);
11564     
11565     while (1) {
11566       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11567         if (!STy->getNumElements()) /* Struct can be empty {} */
11568           break;
11569         NewGEPIndices.push_back(Zero);
11570         SrcPTy = STy->getElementType(0);
11571       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11572         NewGEPIndices.push_back(Zero);
11573         SrcPTy = ATy->getElementType();
11574       } else {
11575         break;
11576       }
11577     }
11578     
11579     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11580   }
11581
11582   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11583     return 0;
11584   
11585   // If the pointers point into different address spaces or if they point to
11586   // values with different sizes, we can't do the transformation.
11587   if (!IC.getTargetData() ||
11588       SrcTy->getAddressSpace() != 
11589         cast<PointerType>(CI->getType())->getAddressSpace() ||
11590       IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11591       IC.getTargetData()->getTypeSizeInBits(DestPTy))
11592     return 0;
11593
11594   // Okay, we are casting from one integer or pointer type to another of
11595   // the same size.  Instead of casting the pointer before 
11596   // the store, cast the value to be stored.
11597   Value *NewCast;
11598   Value *SIOp0 = SI.getOperand(0);
11599   Instruction::CastOps opcode = Instruction::BitCast;
11600   const Type* CastSrcTy = SIOp0->getType();
11601   const Type* CastDstTy = SrcPTy;
11602   if (isa<PointerType>(CastDstTy)) {
11603     if (CastSrcTy->isInteger())
11604       opcode = Instruction::IntToPtr;
11605   } else if (isa<IntegerType>(CastDstTy)) {
11606     if (isa<PointerType>(SIOp0->getType()))
11607       opcode = Instruction::PtrToInt;
11608   }
11609   
11610   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11611   // emit a GEP to index into its first field.
11612   if (!NewGEPIndices.empty())
11613     CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11614                                            NewGEPIndices.end());
11615   
11616   NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11617                                    SIOp0->getName()+".c");
11618   return new StoreInst(NewCast, CastOp);
11619 }
11620
11621 /// equivalentAddressValues - Test if A and B will obviously have the same
11622 /// value. This includes recognizing that %t0 and %t1 will have the same
11623 /// value in code like this:
11624 ///   %t0 = getelementptr \@a, 0, 3
11625 ///   store i32 0, i32* %t0
11626 ///   %t1 = getelementptr \@a, 0, 3
11627 ///   %t2 = load i32* %t1
11628 ///
11629 static bool equivalentAddressValues(Value *A, Value *B) {
11630   // Test if the values are trivially equivalent.
11631   if (A == B) return true;
11632   
11633   // Test if the values come form identical arithmetic instructions.
11634   // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11635   // its only used to compare two uses within the same basic block, which
11636   // means that they'll always either have the same value or one of them
11637   // will have an undefined value.
11638   if (isa<BinaryOperator>(A) ||
11639       isa<CastInst>(A) ||
11640       isa<PHINode>(A) ||
11641       isa<GetElementPtrInst>(A))
11642     if (Instruction *BI = dyn_cast<Instruction>(B))
11643       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
11644         return true;
11645   
11646   // Otherwise they may not be equivalent.
11647   return false;
11648 }
11649
11650 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11651 // return the llvm.dbg.declare.
11652 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11653   if (!V->hasNUses(2))
11654     return 0;
11655   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11656        UI != E; ++UI) {
11657     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11658       return DI;
11659     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11660       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11661         return DI;
11662       }
11663   }
11664   return 0;
11665 }
11666
11667 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11668   Value *Val = SI.getOperand(0);
11669   Value *Ptr = SI.getOperand(1);
11670
11671   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11672     EraseInstFromFunction(SI);
11673     ++NumCombined;
11674     return 0;
11675   }
11676   
11677   // If the RHS is an alloca with a single use, zapify the store, making the
11678   // alloca dead.
11679   // If the RHS is an alloca with a two uses, the other one being a 
11680   // llvm.dbg.declare, zapify the store and the declare, making the
11681   // alloca dead.  We must do this to prevent declare's from affecting
11682   // codegen.
11683   if (!SI.isVolatile()) {
11684     if (Ptr->hasOneUse()) {
11685       if (isa<AllocaInst>(Ptr)) {
11686         EraseInstFromFunction(SI);
11687         ++NumCombined;
11688         return 0;
11689       }
11690       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11691         if (isa<AllocaInst>(GEP->getOperand(0))) {
11692           if (GEP->getOperand(0)->hasOneUse()) {
11693             EraseInstFromFunction(SI);
11694             ++NumCombined;
11695             return 0;
11696           }
11697           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11698             EraseInstFromFunction(*DI);
11699             EraseInstFromFunction(SI);
11700             ++NumCombined;
11701             return 0;
11702           }
11703         }
11704       }
11705     }
11706     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11707       EraseInstFromFunction(*DI);
11708       EraseInstFromFunction(SI);
11709       ++NumCombined;
11710       return 0;
11711     }
11712   }
11713
11714   // Attempt to improve the alignment.
11715   if (TD) {
11716     unsigned KnownAlign =
11717       GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11718     if (KnownAlign >
11719         (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11720                                   SI.getAlignment()))
11721       SI.setAlignment(KnownAlign);
11722   }
11723
11724   // Do really simple DSE, to catch cases where there are several consecutive
11725   // stores to the same location, separated by a few arithmetic operations. This
11726   // situation often occurs with bitfield accesses.
11727   BasicBlock::iterator BBI = &SI;
11728   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11729        --ScanInsts) {
11730     --BBI;
11731     // Don't count debug info directives, lest they affect codegen,
11732     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11733     // It is necessary for correctness to skip those that feed into a
11734     // llvm.dbg.declare, as these are not present when debugging is off.
11735     if (isa<DbgInfoIntrinsic>(BBI) ||
11736         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11737       ScanInsts++;
11738       continue;
11739     }    
11740     
11741     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11742       // Prev store isn't volatile, and stores to the same location?
11743       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11744                                                           SI.getOperand(1))) {
11745         ++NumDeadStore;
11746         ++BBI;
11747         EraseInstFromFunction(*PrevSI);
11748         continue;
11749       }
11750       break;
11751     }
11752     
11753     // If this is a load, we have to stop.  However, if the loaded value is from
11754     // the pointer we're loading and is producing the pointer we're storing,
11755     // then *this* store is dead (X = load P; store X -> P).
11756     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11757       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11758           !SI.isVolatile()) {
11759         EraseInstFromFunction(SI);
11760         ++NumCombined;
11761         return 0;
11762       }
11763       // Otherwise, this is a load from some other location.  Stores before it
11764       // may not be dead.
11765       break;
11766     }
11767     
11768     // Don't skip over loads or things that can modify memory.
11769     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11770       break;
11771   }
11772   
11773   
11774   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11775
11776   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11777   if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
11778     if (!isa<UndefValue>(Val)) {
11779       SI.setOperand(0, UndefValue::get(Val->getType()));
11780       if (Instruction *U = dyn_cast<Instruction>(Val))
11781         Worklist.Add(U);  // Dropped a use.
11782       ++NumCombined;
11783     }
11784     return 0;  // Do not modify these!
11785   }
11786
11787   // store undef, Ptr -> noop
11788   if (isa<UndefValue>(Val)) {
11789     EraseInstFromFunction(SI);
11790     ++NumCombined;
11791     return 0;
11792   }
11793
11794   // If the pointer destination is a cast, see if we can fold the cast into the
11795   // source instead.
11796   if (isa<CastInst>(Ptr))
11797     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11798       return Res;
11799   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11800     if (CE->isCast())
11801       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11802         return Res;
11803
11804   
11805   // If this store is the last instruction in the basic block (possibly
11806   // excepting debug info instructions and the pointer bitcasts that feed
11807   // into them), and if the block ends with an unconditional branch, try
11808   // to move it to the successor block.
11809   BBI = &SI; 
11810   do {
11811     ++BBI;
11812   } while (isa<DbgInfoIntrinsic>(BBI) ||
11813            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11814   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11815     if (BI->isUnconditional())
11816       if (SimplifyStoreAtEndOfBlock(SI))
11817         return 0;  // xform done!
11818   
11819   return 0;
11820 }
11821
11822 /// SimplifyStoreAtEndOfBlock - Turn things like:
11823 ///   if () { *P = v1; } else { *P = v2 }
11824 /// into a phi node with a store in the successor.
11825 ///
11826 /// Simplify things like:
11827 ///   *P = v1; if () { *P = v2; }
11828 /// into a phi node with a store in the successor.
11829 ///
11830 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11831   BasicBlock *StoreBB = SI.getParent();
11832   
11833   // Check to see if the successor block has exactly two incoming edges.  If
11834   // so, see if the other predecessor contains a store to the same location.
11835   // if so, insert a PHI node (if needed) and move the stores down.
11836   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11837   
11838   // Determine whether Dest has exactly two predecessors and, if so, compute
11839   // the other predecessor.
11840   pred_iterator PI = pred_begin(DestBB);
11841   BasicBlock *OtherBB = 0;
11842   if (*PI != StoreBB)
11843     OtherBB = *PI;
11844   ++PI;
11845   if (PI == pred_end(DestBB))
11846     return false;
11847   
11848   if (*PI != StoreBB) {
11849     if (OtherBB)
11850       return false;
11851     OtherBB = *PI;
11852   }
11853   if (++PI != pred_end(DestBB))
11854     return false;
11855
11856   // Bail out if all the relevant blocks aren't distinct (this can happen,
11857   // for example, if SI is in an infinite loop)
11858   if (StoreBB == DestBB || OtherBB == DestBB)
11859     return false;
11860
11861   // Verify that the other block ends in a branch and is not otherwise empty.
11862   BasicBlock::iterator BBI = OtherBB->getTerminator();
11863   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11864   if (!OtherBr || BBI == OtherBB->begin())
11865     return false;
11866   
11867   // If the other block ends in an unconditional branch, check for the 'if then
11868   // else' case.  there is an instruction before the branch.
11869   StoreInst *OtherStore = 0;
11870   if (OtherBr->isUnconditional()) {
11871     --BBI;
11872     // Skip over debugging info.
11873     while (isa<DbgInfoIntrinsic>(BBI) ||
11874            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11875       if (BBI==OtherBB->begin())
11876         return false;
11877       --BBI;
11878     }
11879     // If this isn't a store, or isn't a store to the same location, bail out.
11880     OtherStore = dyn_cast<StoreInst>(BBI);
11881     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11882       return false;
11883   } else {
11884     // Otherwise, the other block ended with a conditional branch. If one of the
11885     // destinations is StoreBB, then we have the if/then case.
11886     if (OtherBr->getSuccessor(0) != StoreBB && 
11887         OtherBr->getSuccessor(1) != StoreBB)
11888       return false;
11889     
11890     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11891     // if/then triangle.  See if there is a store to the same ptr as SI that
11892     // lives in OtherBB.
11893     for (;; --BBI) {
11894       // Check to see if we find the matching store.
11895       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11896         if (OtherStore->getOperand(1) != SI.getOperand(1))
11897           return false;
11898         break;
11899       }
11900       // If we find something that may be using or overwriting the stored
11901       // value, or if we run out of instructions, we can't do the xform.
11902       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11903           BBI == OtherBB->begin())
11904         return false;
11905     }
11906     
11907     // In order to eliminate the store in OtherBr, we have to
11908     // make sure nothing reads or overwrites the stored value in
11909     // StoreBB.
11910     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11911       // FIXME: This should really be AA driven.
11912       if (I->mayReadFromMemory() || I->mayWriteToMemory())
11913         return false;
11914     }
11915   }
11916   
11917   // Insert a PHI node now if we need it.
11918   Value *MergedVal = OtherStore->getOperand(0);
11919   if (MergedVal != SI.getOperand(0)) {
11920     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11921     PN->reserveOperandSpace(2);
11922     PN->addIncoming(SI.getOperand(0), SI.getParent());
11923     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11924     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11925   }
11926   
11927   // Advance to a place where it is safe to insert the new store and
11928   // insert it.
11929   BBI = DestBB->getFirstNonPHI();
11930   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11931                                     OtherStore->isVolatile()), *BBI);
11932   
11933   // Nuke the old stores.
11934   EraseInstFromFunction(SI);
11935   EraseInstFromFunction(*OtherStore);
11936   ++NumCombined;
11937   return true;
11938 }
11939
11940
11941 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11942   // Change br (not X), label True, label False to: br X, label False, True
11943   Value *X = 0;
11944   BasicBlock *TrueDest;
11945   BasicBlock *FalseDest;
11946   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11947       !isa<Constant>(X)) {
11948     // Swap Destinations and condition...
11949     BI.setCondition(X);
11950     BI.setSuccessor(0, FalseDest);
11951     BI.setSuccessor(1, TrueDest);
11952     return &BI;
11953   }
11954
11955   // Cannonicalize fcmp_one -> fcmp_oeq
11956   FCmpInst::Predicate FPred; Value *Y;
11957   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
11958                              TrueDest, FalseDest)) &&
11959       BI.getCondition()->hasOneUse())
11960     if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11961         FPred == FCmpInst::FCMP_OGE) {
11962       FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11963       Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11964       
11965       // Swap Destinations and condition.
11966       BI.setSuccessor(0, FalseDest);
11967       BI.setSuccessor(1, TrueDest);
11968       Worklist.Add(Cond);
11969       return &BI;
11970     }
11971
11972   // Cannonicalize icmp_ne -> icmp_eq
11973   ICmpInst::Predicate IPred;
11974   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11975                       TrueDest, FalseDest)) &&
11976       BI.getCondition()->hasOneUse())
11977     if (IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
11978         IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11979         IPred == ICmpInst::ICMP_SGE) {
11980       ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11981       Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11982       // Swap Destinations and condition.
11983       BI.setSuccessor(0, FalseDest);
11984       BI.setSuccessor(1, TrueDest);
11985       Worklist.Add(Cond);
11986       return &BI;
11987     }
11988
11989   return 0;
11990 }
11991
11992 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11993   Value *Cond = SI.getCondition();
11994   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11995     if (I->getOpcode() == Instruction::Add)
11996       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11997         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11998         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11999           SI.setOperand(i,
12000                    ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
12001                                                 AddRHS));
12002         SI.setOperand(0, I->getOperand(0));
12003         Worklist.Add(I);
12004         return &SI;
12005       }
12006   }
12007   return 0;
12008 }
12009
12010 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12011   Value *Agg = EV.getAggregateOperand();
12012
12013   if (!EV.hasIndices())
12014     return ReplaceInstUsesWith(EV, Agg);
12015
12016   if (Constant *C = dyn_cast<Constant>(Agg)) {
12017     if (isa<UndefValue>(C))
12018       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12019       
12020     if (isa<ConstantAggregateZero>(C))
12021       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12022
12023     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12024       // Extract the element indexed by the first index out of the constant
12025       Value *V = C->getOperand(*EV.idx_begin());
12026       if (EV.getNumIndices() > 1)
12027         // Extract the remaining indices out of the constant indexed by the
12028         // first index
12029         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12030       else
12031         return ReplaceInstUsesWith(EV, V);
12032     }
12033     return 0; // Can't handle other constants
12034   } 
12035   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12036     // We're extracting from an insertvalue instruction, compare the indices
12037     const unsigned *exti, *exte, *insi, *inse;
12038     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12039          exte = EV.idx_end(), inse = IV->idx_end();
12040          exti != exte && insi != inse;
12041          ++exti, ++insi) {
12042       if (*insi != *exti)
12043         // The insert and extract both reference distinctly different elements.
12044         // This means the extract is not influenced by the insert, and we can
12045         // replace the aggregate operand of the extract with the aggregate
12046         // operand of the insert. i.e., replace
12047         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12048         // %E = extractvalue { i32, { i32 } } %I, 0
12049         // with
12050         // %E = extractvalue { i32, { i32 } } %A, 0
12051         return ExtractValueInst::Create(IV->getAggregateOperand(),
12052                                         EV.idx_begin(), EV.idx_end());
12053     }
12054     if (exti == exte && insi == inse)
12055       // Both iterators are at the end: Index lists are identical. Replace
12056       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12057       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12058       // with "i32 42"
12059       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12060     if (exti == exte) {
12061       // The extract list is a prefix of the insert list. i.e. replace
12062       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12063       // %E = extractvalue { i32, { i32 } } %I, 1
12064       // with
12065       // %X = extractvalue { i32, { i32 } } %A, 1
12066       // %E = insertvalue { i32 } %X, i32 42, 0
12067       // by switching the order of the insert and extract (though the
12068       // insertvalue should be left in, since it may have other uses).
12069       Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12070                                                  EV.idx_begin(), EV.idx_end());
12071       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12072                                      insi, inse);
12073     }
12074     if (insi == inse)
12075       // The insert list is a prefix of the extract list
12076       // We can simply remove the common indices from the extract and make it
12077       // operate on the inserted value instead of the insertvalue result.
12078       // i.e., replace
12079       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12080       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12081       // with
12082       // %E extractvalue { i32 } { i32 42 }, 0
12083       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12084                                       exti, exte);
12085   }
12086   // Can't simplify extracts from other values. Note that nested extracts are
12087   // already simplified implicitely by the above (extract ( extract (insert) )
12088   // will be translated into extract ( insert ( extract ) ) first and then just
12089   // the value inserted, if appropriate).
12090   return 0;
12091 }
12092
12093 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12094 /// is to leave as a vector operation.
12095 static bool CheapToScalarize(Value *V, bool isConstant) {
12096   if (isa<ConstantAggregateZero>(V)) 
12097     return true;
12098   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12099     if (isConstant) return true;
12100     // If all elts are the same, we can extract.
12101     Constant *Op0 = C->getOperand(0);
12102     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12103       if (C->getOperand(i) != Op0)
12104         return false;
12105     return true;
12106   }
12107   Instruction *I = dyn_cast<Instruction>(V);
12108   if (!I) return false;
12109   
12110   // Insert element gets simplified to the inserted element or is deleted if
12111   // this is constant idx extract element and its a constant idx insertelt.
12112   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12113       isa<ConstantInt>(I->getOperand(2)))
12114     return true;
12115   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12116     return true;
12117   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12118     if (BO->hasOneUse() &&
12119         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12120          CheapToScalarize(BO->getOperand(1), isConstant)))
12121       return true;
12122   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12123     if (CI->hasOneUse() &&
12124         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12125          CheapToScalarize(CI->getOperand(1), isConstant)))
12126       return true;
12127   
12128   return false;
12129 }
12130
12131 /// Read and decode a shufflevector mask.
12132 ///
12133 /// It turns undef elements into values that are larger than the number of
12134 /// elements in the input.
12135 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12136   unsigned NElts = SVI->getType()->getNumElements();
12137   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12138     return std::vector<unsigned>(NElts, 0);
12139   if (isa<UndefValue>(SVI->getOperand(2)))
12140     return std::vector<unsigned>(NElts, 2*NElts);
12141
12142   std::vector<unsigned> Result;
12143   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12144   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12145     if (isa<UndefValue>(*i))
12146       Result.push_back(NElts*2);  // undef -> 8
12147     else
12148       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12149   return Result;
12150 }
12151
12152 /// FindScalarElement - Given a vector and an element number, see if the scalar
12153 /// value is already around as a register, for example if it were inserted then
12154 /// extracted from the vector.
12155 static Value *FindScalarElement(Value *V, unsigned EltNo,
12156                                 LLVMContext *Context) {
12157   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12158   const VectorType *PTy = cast<VectorType>(V->getType());
12159   unsigned Width = PTy->getNumElements();
12160   if (EltNo >= Width)  // Out of range access.
12161     return UndefValue::get(PTy->getElementType());
12162   
12163   if (isa<UndefValue>(V))
12164     return UndefValue::get(PTy->getElementType());
12165   else if (isa<ConstantAggregateZero>(V))
12166     return Constant::getNullValue(PTy->getElementType());
12167   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12168     return CP->getOperand(EltNo);
12169   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12170     // If this is an insert to a variable element, we don't know what it is.
12171     if (!isa<ConstantInt>(III->getOperand(2))) 
12172       return 0;
12173     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12174     
12175     // If this is an insert to the element we are looking for, return the
12176     // inserted value.
12177     if (EltNo == IIElt) 
12178       return III->getOperand(1);
12179     
12180     // Otherwise, the insertelement doesn't modify the value, recurse on its
12181     // vector input.
12182     return FindScalarElement(III->getOperand(0), EltNo, Context);
12183   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12184     unsigned LHSWidth =
12185       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12186     unsigned InEl = getShuffleMask(SVI)[EltNo];
12187     if (InEl < LHSWidth)
12188       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12189     else if (InEl < LHSWidth*2)
12190       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12191     else
12192       return UndefValue::get(PTy->getElementType());
12193   }
12194   
12195   // Otherwise, we don't know.
12196   return 0;
12197 }
12198
12199 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12200   // If vector val is undef, replace extract with scalar undef.
12201   if (isa<UndefValue>(EI.getOperand(0)))
12202     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12203
12204   // If vector val is constant 0, replace extract with scalar 0.
12205   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12206     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12207   
12208   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12209     // If vector val is constant with all elements the same, replace EI with
12210     // that element. When the elements are not identical, we cannot replace yet
12211     // (we do that below, but only when the index is constant).
12212     Constant *op0 = C->getOperand(0);
12213     for (unsigned i = 1; i != C->getNumOperands(); ++i)
12214       if (C->getOperand(i) != op0) {
12215         op0 = 0; 
12216         break;
12217       }
12218     if (op0)
12219       return ReplaceInstUsesWith(EI, op0);
12220   }
12221   
12222   // If extracting a specified index from the vector, see if we can recursively
12223   // find a previously computed scalar that was inserted into the vector.
12224   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12225     unsigned IndexVal = IdxC->getZExtValue();
12226     unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
12227       
12228     // If this is extracting an invalid index, turn this into undef, to avoid
12229     // crashing the code below.
12230     if (IndexVal >= VectorWidth)
12231       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12232     
12233     // This instruction only demands the single element from the input vector.
12234     // If the input vector has a single use, simplify it based on this use
12235     // property.
12236     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12237       APInt UndefElts(VectorWidth, 0);
12238       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12239       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12240                                                 DemandedMask, UndefElts)) {
12241         EI.setOperand(0, V);
12242         return &EI;
12243       }
12244     }
12245     
12246     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12247       return ReplaceInstUsesWith(EI, Elt);
12248     
12249     // If the this extractelement is directly using a bitcast from a vector of
12250     // the same number of elements, see if we can find the source element from
12251     // it.  In this case, we will end up needing to bitcast the scalars.
12252     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12253       if (const VectorType *VT = 
12254               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12255         if (VT->getNumElements() == VectorWidth)
12256           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12257                                              IndexVal, Context))
12258             return new BitCastInst(Elt, EI.getType());
12259     }
12260   }
12261   
12262   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12263     // Push extractelement into predecessor operation if legal and
12264     // profitable to do so
12265     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12266       if (I->hasOneUse() &&
12267           CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12268         Value *newEI0 =
12269           Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12270                                         EI.getName()+".lhs");
12271         Value *newEI1 =
12272           Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12273                                         EI.getName()+".rhs");
12274         return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12275       }
12276     } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12277       // Extracting the inserted element?
12278       if (IE->getOperand(2) == EI.getOperand(1))
12279         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12280       // If the inserted and extracted elements are constants, they must not
12281       // be the same value, extract from the pre-inserted value instead.
12282       if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
12283         Worklist.AddValue(EI.getOperand(0));
12284         EI.setOperand(0, IE->getOperand(0));
12285         return &EI;
12286       }
12287     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12288       // If this is extracting an element from a shufflevector, figure out where
12289       // it came from and extract from the appropriate input element instead.
12290       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12291         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12292         Value *Src;
12293         unsigned LHSWidth =
12294           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12295
12296         if (SrcIdx < LHSWidth)
12297           Src = SVI->getOperand(0);
12298         else if (SrcIdx < LHSWidth*2) {
12299           SrcIdx -= LHSWidth;
12300           Src = SVI->getOperand(1);
12301         } else {
12302           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12303         }
12304         return ExtractElementInst::Create(Src,
12305                          ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12306                                           false));
12307       }
12308     }
12309     // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12310   }
12311   return 0;
12312 }
12313
12314 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12315 /// elements from either LHS or RHS, return the shuffle mask and true. 
12316 /// Otherwise, return false.
12317 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12318                                          std::vector<Constant*> &Mask,
12319                                          LLVMContext *Context) {
12320   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12321          "Invalid CollectSingleShuffleElements");
12322   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12323
12324   if (isa<UndefValue>(V)) {
12325     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12326     return true;
12327   } else if (V == LHS) {
12328     for (unsigned i = 0; i != NumElts; ++i)
12329       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12330     return true;
12331   } else if (V == RHS) {
12332     for (unsigned i = 0; i != NumElts; ++i)
12333       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
12334     return true;
12335   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12336     // If this is an insert of an extract from some other vector, include it.
12337     Value *VecOp    = IEI->getOperand(0);
12338     Value *ScalarOp = IEI->getOperand(1);
12339     Value *IdxOp    = IEI->getOperand(2);
12340     
12341     if (!isa<ConstantInt>(IdxOp))
12342       return false;
12343     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12344     
12345     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12346       // Okay, we can handle this if the vector we are insertinting into is
12347       // transitively ok.
12348       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12349         // If so, update the mask to reflect the inserted undef.
12350         Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
12351         return true;
12352       }      
12353     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12354       if (isa<ConstantInt>(EI->getOperand(1)) &&
12355           EI->getOperand(0)->getType() == V->getType()) {
12356         unsigned ExtractedIdx =
12357           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12358         
12359         // This must be extracting from either LHS or RHS.
12360         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12361           // Okay, we can handle this if the vector we are insertinting into is
12362           // transitively ok.
12363           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12364             // If so, update the mask to reflect the inserted value.
12365             if (EI->getOperand(0) == LHS) {
12366               Mask[InsertedIdx % NumElts] = 
12367                  ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12368             } else {
12369               assert(EI->getOperand(0) == RHS);
12370               Mask[InsertedIdx % NumElts] = 
12371                 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
12372               
12373             }
12374             return true;
12375           }
12376         }
12377       }
12378     }
12379   }
12380   // TODO: Handle shufflevector here!
12381   
12382   return false;
12383 }
12384
12385 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12386 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12387 /// that computes V and the LHS value of the shuffle.
12388 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12389                                      Value *&RHS, LLVMContext *Context) {
12390   assert(isa<VectorType>(V->getType()) && 
12391          (RHS == 0 || V->getType() == RHS->getType()) &&
12392          "Invalid shuffle!");
12393   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12394
12395   if (isa<UndefValue>(V)) {
12396     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12397     return V;
12398   } else if (isa<ConstantAggregateZero>(V)) {
12399     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
12400     return V;
12401   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12402     // If this is an insert of an extract from some other vector, include it.
12403     Value *VecOp    = IEI->getOperand(0);
12404     Value *ScalarOp = IEI->getOperand(1);
12405     Value *IdxOp    = IEI->getOperand(2);
12406     
12407     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12408       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12409           EI->getOperand(0)->getType() == V->getType()) {
12410         unsigned ExtractedIdx =
12411           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12412         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12413         
12414         // Either the extracted from or inserted into vector must be RHSVec,
12415         // otherwise we'd end up with a shuffle of three inputs.
12416         if (EI->getOperand(0) == RHS || RHS == 0) {
12417           RHS = EI->getOperand(0);
12418           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12419           Mask[InsertedIdx % NumElts] = 
12420             ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
12421           return V;
12422         }
12423         
12424         if (VecOp == RHS) {
12425           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12426                                             RHS, Context);
12427           // Everything but the extracted element is replaced with the RHS.
12428           for (unsigned i = 0; i != NumElts; ++i) {
12429             if (i != InsertedIdx)
12430               Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
12431           }
12432           return V;
12433         }
12434         
12435         // If this insertelement is a chain that comes from exactly these two
12436         // vectors, return the vector and the effective shuffle.
12437         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12438                                          Context))
12439           return EI->getOperand(0);
12440         
12441       }
12442     }
12443   }
12444   // TODO: Handle shufflevector here!
12445   
12446   // Otherwise, can't do anything fancy.  Return an identity vector.
12447   for (unsigned i = 0; i != NumElts; ++i)
12448     Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12449   return V;
12450 }
12451
12452 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12453   Value *VecOp    = IE.getOperand(0);
12454   Value *ScalarOp = IE.getOperand(1);
12455   Value *IdxOp    = IE.getOperand(2);
12456   
12457   // Inserting an undef or into an undefined place, remove this.
12458   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12459     ReplaceInstUsesWith(IE, VecOp);
12460   
12461   // If the inserted element was extracted from some other vector, and if the 
12462   // indexes are constant, try to turn this into a shufflevector operation.
12463   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12464     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12465         EI->getOperand(0)->getType() == IE.getType()) {
12466       unsigned NumVectorElts = IE.getType()->getNumElements();
12467       unsigned ExtractedIdx =
12468         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12469       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12470       
12471       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12472         return ReplaceInstUsesWith(IE, VecOp);
12473       
12474       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12475         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12476       
12477       // If we are extracting a value from a vector, then inserting it right
12478       // back into the same place, just use the input vector.
12479       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12480         return ReplaceInstUsesWith(IE, VecOp);      
12481       
12482       // If this insertelement isn't used by some other insertelement, turn it
12483       // (and any insertelements it points to), into one big shuffle.
12484       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12485         std::vector<Constant*> Mask;
12486         Value *RHS = 0;
12487         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12488         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12489         // We now have a shuffle of LHS, RHS, Mask.
12490         return new ShuffleVectorInst(LHS, RHS,
12491                                      ConstantVector::get(Mask));
12492       }
12493     }
12494   }
12495
12496   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12497   APInt UndefElts(VWidth, 0);
12498   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12499   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12500     return &IE;
12501
12502   return 0;
12503 }
12504
12505
12506 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12507   Value *LHS = SVI.getOperand(0);
12508   Value *RHS = SVI.getOperand(1);
12509   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12510
12511   bool MadeChange = false;
12512
12513   // Undefined shuffle mask -> undefined value.
12514   if (isa<UndefValue>(SVI.getOperand(2)))
12515     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12516
12517   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12518
12519   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12520     return 0;
12521
12522   APInt UndefElts(VWidth, 0);
12523   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12524   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12525     LHS = SVI.getOperand(0);
12526     RHS = SVI.getOperand(1);
12527     MadeChange = true;
12528   }
12529   
12530   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12531   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12532   if (LHS == RHS || isa<UndefValue>(LHS)) {
12533     if (isa<UndefValue>(LHS) && LHS == RHS) {
12534       // shuffle(undef,undef,mask) -> undef.
12535       return ReplaceInstUsesWith(SVI, LHS);
12536     }
12537     
12538     // Remap any references to RHS to use LHS.
12539     std::vector<Constant*> Elts;
12540     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12541       if (Mask[i] >= 2*e)
12542         Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12543       else {
12544         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12545             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12546           Mask[i] = 2*e;     // Turn into undef.
12547           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12548         } else {
12549           Mask[i] = Mask[i] % e;  // Force to LHS.
12550           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
12551         }
12552       }
12553     }
12554     SVI.setOperand(0, SVI.getOperand(1));
12555     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12556     SVI.setOperand(2, ConstantVector::get(Elts));
12557     LHS = SVI.getOperand(0);
12558     RHS = SVI.getOperand(1);
12559     MadeChange = true;
12560   }
12561   
12562   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12563   bool isLHSID = true, isRHSID = true;
12564     
12565   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12566     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12567     // Is this an identity shuffle of the LHS value?
12568     isLHSID &= (Mask[i] == i);
12569       
12570     // Is this an identity shuffle of the RHS value?
12571     isRHSID &= (Mask[i]-e == i);
12572   }
12573
12574   // Eliminate identity shuffles.
12575   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12576   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12577   
12578   // If the LHS is a shufflevector itself, see if we can combine it with this
12579   // one without producing an unusual shuffle.  Here we are really conservative:
12580   // we are absolutely afraid of producing a shuffle mask not in the input
12581   // program, because the code gen may not be smart enough to turn a merged
12582   // shuffle into two specific shuffles: it may produce worse code.  As such,
12583   // we only merge two shuffles if the result is one of the two input shuffle
12584   // masks.  In this case, merging the shuffles just removes one instruction,
12585   // which we know is safe.  This is good for things like turning:
12586   // (splat(splat)) -> splat.
12587   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12588     if (isa<UndefValue>(RHS)) {
12589       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12590
12591       std::vector<unsigned> NewMask;
12592       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12593         if (Mask[i] >= 2*e)
12594           NewMask.push_back(2*e);
12595         else
12596           NewMask.push_back(LHSMask[Mask[i]]);
12597       
12598       // If the result mask is equal to the src shuffle or this shuffle mask, do
12599       // the replacement.
12600       if (NewMask == LHSMask || NewMask == Mask) {
12601         unsigned LHSInNElts =
12602           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12603         std::vector<Constant*> Elts;
12604         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12605           if (NewMask[i] >= LHSInNElts*2) {
12606             Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12607           } else {
12608             Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
12609           }
12610         }
12611         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12612                                      LHSSVI->getOperand(1),
12613                                      ConstantVector::get(Elts));
12614       }
12615     }
12616   }
12617
12618   return MadeChange ? &SVI : 0;
12619 }
12620
12621
12622
12623
12624 /// TryToSinkInstruction - Try to move the specified instruction from its
12625 /// current block into the beginning of DestBlock, which can only happen if it's
12626 /// safe to move the instruction past all of the instructions between it and the
12627 /// end of its block.
12628 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12629   assert(I->hasOneUse() && "Invariants didn't hold!");
12630
12631   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12632   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12633     return false;
12634
12635   // Do not sink alloca instructions out of the entry block.
12636   if (isa<AllocaInst>(I) && I->getParent() ==
12637         &DestBlock->getParent()->getEntryBlock())
12638     return false;
12639
12640   // We can only sink load instructions if there is nothing between the load and
12641   // the end of block that could change the value.
12642   if (I->mayReadFromMemory()) {
12643     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12644          Scan != E; ++Scan)
12645       if (Scan->mayWriteToMemory())
12646         return false;
12647   }
12648
12649   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12650
12651   CopyPrecedingStopPoint(I, InsertPos);
12652   I->moveBefore(InsertPos);
12653   ++NumSunkInst;
12654   return true;
12655 }
12656
12657
12658 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12659 /// all reachable code to the worklist.
12660 ///
12661 /// This has a couple of tricks to make the code faster and more powerful.  In
12662 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12663 /// them to the worklist (this significantly speeds up instcombine on code where
12664 /// many instructions are dead or constant).  Additionally, if we find a branch
12665 /// whose condition is a known constant, we only visit the reachable successors.
12666 ///
12667 static bool AddReachableCodeToWorklist(BasicBlock *BB, 
12668                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12669                                        InstCombiner &IC,
12670                                        const TargetData *TD) {
12671   bool MadeIRChange = false;
12672   SmallVector<BasicBlock*, 256> Worklist;
12673   Worklist.push_back(BB);
12674   
12675   std::vector<Instruction*> InstrsForInstCombineWorklist;
12676   InstrsForInstCombineWorklist.reserve(128);
12677
12678   SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
12679   
12680   while (!Worklist.empty()) {
12681     BB = Worklist.back();
12682     Worklist.pop_back();
12683     
12684     // We have now visited this block!  If we've already been here, ignore it.
12685     if (!Visited.insert(BB)) continue;
12686
12687     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12688       Instruction *Inst = BBI++;
12689       
12690       // DCE instruction if trivially dead.
12691       if (isInstructionTriviallyDead(Inst)) {
12692         ++NumDeadInst;
12693         DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
12694         Inst->eraseFromParent();
12695         continue;
12696       }
12697       
12698       // ConstantProp instruction if trivially constant.
12699       if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
12700         if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12701           DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12702                        << *Inst << '\n');
12703           Inst->replaceAllUsesWith(C);
12704           ++NumConstProp;
12705           Inst->eraseFromParent();
12706           continue;
12707         }
12708       
12709       
12710       
12711       if (TD) {
12712         // See if we can constant fold its operands.
12713         for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
12714              i != e; ++i) {
12715           ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
12716           if (CE == 0) continue;
12717           
12718           // If we already folded this constant, don't try again.
12719           if (!FoldedConstants.insert(CE))
12720             continue;
12721           
12722           Constant *NewC =
12723             ConstantFoldConstantExpression(CE, BB->getContext(), TD);
12724           if (NewC && NewC != CE) {
12725             *i = NewC;
12726             MadeIRChange = true;
12727           }
12728         }
12729       }
12730       
12731
12732       InstrsForInstCombineWorklist.push_back(Inst);
12733     }
12734
12735     // Recursively visit successors.  If this is a branch or switch on a
12736     // constant, only visit the reachable successor.
12737     TerminatorInst *TI = BB->getTerminator();
12738     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12739       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12740         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12741         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12742         Worklist.push_back(ReachableBB);
12743         continue;
12744       }
12745     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12746       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12747         // See if this is an explicit destination.
12748         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12749           if (SI->getCaseValue(i) == Cond) {
12750             BasicBlock *ReachableBB = SI->getSuccessor(i);
12751             Worklist.push_back(ReachableBB);
12752             continue;
12753           }
12754         
12755         // Otherwise it is the default destination.
12756         Worklist.push_back(SI->getSuccessor(0));
12757         continue;
12758       }
12759     }
12760     
12761     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12762       Worklist.push_back(TI->getSuccessor(i));
12763   }
12764   
12765   // Once we've found all of the instructions to add to instcombine's worklist,
12766   // add them in reverse order.  This way instcombine will visit from the top
12767   // of the function down.  This jives well with the way that it adds all uses
12768   // of instructions to the worklist after doing a transformation, thus avoiding
12769   // some N^2 behavior in pathological cases.
12770   IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
12771                               InstrsForInstCombineWorklist.size());
12772   
12773   return MadeIRChange;
12774 }
12775
12776 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12777   MadeIRChange = false;
12778   
12779   DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12780         << F.getNameStr() << "\n");
12781
12782   {
12783     // Do a depth-first traversal of the function, populate the worklist with
12784     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12785     // track of which blocks we visit.
12786     SmallPtrSet<BasicBlock*, 64> Visited;
12787     MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12788
12789     // Do a quick scan over the function.  If we find any blocks that are
12790     // unreachable, remove any instructions inside of them.  This prevents
12791     // the instcombine code from having to deal with some bad special cases.
12792     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12793       if (!Visited.count(BB)) {
12794         Instruction *Term = BB->getTerminator();
12795         while (Term != BB->begin()) {   // Remove instrs bottom-up
12796           BasicBlock::iterator I = Term; --I;
12797
12798           DEBUG(errs() << "IC: DCE: " << *I << '\n');
12799           // A debug intrinsic shouldn't force another iteration if we weren't
12800           // going to do one without it.
12801           if (!isa<DbgInfoIntrinsic>(I)) {
12802             ++NumDeadInst;
12803             MadeIRChange = true;
12804           }
12805
12806           // If I is not void type then replaceAllUsesWith undef.
12807           // This allows ValueHandlers and custom metadata to adjust itself.
12808           if (!I->getType()->isVoidTy())
12809             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12810           I->eraseFromParent();
12811         }
12812       }
12813   }
12814
12815   while (!Worklist.isEmpty()) {
12816     Instruction *I = Worklist.RemoveOne();
12817     if (I == 0) continue;  // skip null values.
12818
12819     // Check to see if we can DCE the instruction.
12820     if (isInstructionTriviallyDead(I)) {
12821       DEBUG(errs() << "IC: DCE: " << *I << '\n');
12822       EraseInstFromFunction(*I);
12823       ++NumDeadInst;
12824       MadeIRChange = true;
12825       continue;
12826     }
12827
12828     // Instruction isn't dead, see if we can constant propagate it.
12829     if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
12830       if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12831         DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
12832
12833         // Add operands to the worklist.
12834         ReplaceInstUsesWith(*I, C);
12835         ++NumConstProp;
12836         EraseInstFromFunction(*I);
12837         MadeIRChange = true;
12838         continue;
12839       }
12840
12841     // See if we can trivially sink this instruction to a successor basic block.
12842     if (I->hasOneUse()) {
12843       BasicBlock *BB = I->getParent();
12844       Instruction *UserInst = cast<Instruction>(I->use_back());
12845       BasicBlock *UserParent;
12846       
12847       // Get the block the use occurs in.
12848       if (PHINode *PN = dyn_cast<PHINode>(UserInst))
12849         UserParent = PN->getIncomingBlock(I->use_begin().getUse());
12850       else
12851         UserParent = UserInst->getParent();
12852       
12853       if (UserParent != BB) {
12854         bool UserIsSuccessor = false;
12855         // See if the user is one of our successors.
12856         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12857           if (*SI == UserParent) {
12858             UserIsSuccessor = true;
12859             break;
12860           }
12861
12862         // If the user is one of our immediate successors, and if that successor
12863         // only has us as a predecessors (we'd have to split the critical edge
12864         // otherwise), we can keep going.
12865         if (UserIsSuccessor && UserParent->getSinglePredecessor())
12866           // Okay, the CFG is simple enough, try to sink this instruction.
12867           MadeIRChange |= TryToSinkInstruction(I, UserParent);
12868       }
12869     }
12870
12871     // Now that we have an instruction, try combining it to simplify it.
12872     Builder->SetInsertPoint(I->getParent(), I);
12873     
12874 #ifndef NDEBUG
12875     std::string OrigI;
12876 #endif
12877     DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
12878     DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
12879
12880     if (Instruction *Result = visit(*I)) {
12881       ++NumCombined;
12882       // Should we replace the old instruction with a new one?
12883       if (Result != I) {
12884         DEBUG(errs() << "IC: Old = " << *I << '\n'
12885                      << "    New = " << *Result << '\n');
12886
12887         // Everything uses the new instruction now.
12888         I->replaceAllUsesWith(Result);
12889
12890         // Push the new instruction and any users onto the worklist.
12891         Worklist.Add(Result);
12892         Worklist.AddUsersToWorkList(*Result);
12893
12894         // Move the name to the new instruction first.
12895         Result->takeName(I);
12896
12897         // Insert the new instruction into the basic block...
12898         BasicBlock *InstParent = I->getParent();
12899         BasicBlock::iterator InsertPos = I;
12900
12901         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
12902           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12903             ++InsertPos;
12904
12905         InstParent->getInstList().insert(InsertPos, Result);
12906
12907         EraseInstFromFunction(*I);
12908       } else {
12909 #ifndef NDEBUG
12910         DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12911                      << "    New = " << *I << '\n');
12912 #endif
12913
12914         // If the instruction was modified, it's possible that it is now dead.
12915         // if so, remove it.
12916         if (isInstructionTriviallyDead(I)) {
12917           EraseInstFromFunction(*I);
12918         } else {
12919           Worklist.Add(I);
12920           Worklist.AddUsersToWorkList(*I);
12921         }
12922       }
12923       MadeIRChange = true;
12924     }
12925   }
12926
12927   Worklist.Zap();
12928   return MadeIRChange;
12929 }
12930
12931
12932 bool InstCombiner::runOnFunction(Function &F) {
12933   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12934   Context = &F.getContext();
12935   TD = getAnalysisIfAvailable<TargetData>();
12936
12937   
12938   /// Builder - This is an IRBuilder that automatically inserts new
12939   /// instructions into the worklist when they are created.
12940   IRBuilder<true, TargetFolder, InstCombineIRInserter> 
12941     TheBuilder(F.getContext(), TargetFolder(TD, F.getContext()),
12942                InstCombineIRInserter(Worklist));
12943   Builder = &TheBuilder;
12944   
12945   bool EverMadeChange = false;
12946
12947   // Iterate while there is work to do.
12948   unsigned Iteration = 0;
12949   while (DoOneIteration(F, Iteration++))
12950     EverMadeChange = true;
12951   
12952   Builder = 0;
12953   return EverMadeChange;
12954 }
12955
12956 FunctionPass *llvm::createInstructionCombiningPass() {
12957   return new InstCombiner();
12958 }